If you do not need to display it in the DataGridView, but need to put it in excel, please refer to this method:
private void Form1_Load(object sender, EventArgs e)
{
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Columns.Add("EmpNo", typeof(int));
dataTable.Columns.Add("EmpName", typeof(string));
dataTable.Columns.Add("Reasons", typeof(MyList<string>));
dataTable.Rows.Add(1, "Timon", new MyList<string>() { "late", "reason2" });
dataTable.Rows.Add(2, "Timon1", new MyList<string>() { "late", "reason2", "reason3" });
dataTable.Rows.Add(3, "Timon2", new MyList<string>() { "late", "reason2" });
ExportDataTableToExcel(dataTable, @"d:\test\excel\tet.xlsx");
}
public bool ExportDataTableToExcel(System.Data.DataTable dt, string filepath)
{
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application(); ;
Workbook oWB = oXL.Workbooks.Add(Missing.Value); ;
Worksheet oSheet;
try
{
oXL.Visible = true;
oXL.DisplayAlerts = false;
oSheet = (Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
oWB.SaveAs(filepath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
oWB.Close();
oXL.Quit();
}
return true;
}
Does this meet your requirements?
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Can anyone help us to proceed further