Вы также можете использовать другой способ преобразования набора данных в Excel с помощью офисного API.
Код:
private void button1_Click(object sender, EventArgs e)
{
DataSet set = new DataSet();
DataTable table1 = new DataTable();
table1.TableName = "Student";
table1.Columns.Add("Name");
table1.Columns.Add("Id");
table1.Columns.Add("Age");
table1.Rows.Add("test1", 1001, 22);
table1.Rows.Add("test2", 1005, 24);
table1.Rows.Add("test3", 1007, 26);
DataTable table2 = new DataTable();
table2.TableName = "Product";
table2.Columns.Add("ProductName");
table2.Columns.Add("Date");
table2.Columns.Add("Address");
table2.Rows.Add("test1", "2020-01-01", "home");
table2.Rows.Add("test2", "2020-02-01", "Company");
table2.Rows.Add("test3", "2020-03-01", "School");
set.Tables.Add(table1);
set.Tables.Add(table2);
ExportDataSetToExcel(set, "D:\\test.xlsx");
MessageBox.Show("success");
}
private void ExportDataSetToExcel(DataSet ds, string path)
{
//Creae an Excel application instance
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Create an Excel workbook instance and open it from the predefined location
Microsoft.Office.Interop.Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(Type.Missing);
int count = 1;
foreach (System.Data.DataTable table in ds.Tables)
{
//Add a new worksheet to workbook with the Datatable name
Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkBook.ActiveSheet;
excelWorkSheet.Name = table.TableName;
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
if(count<ds.Tables.Count)
{
excelWorkBook.Sheets.Add(excelWorkSheet);
}
count++;
}
excelWorkBook.SaveAs(path);
excelWorkBook.Close();
excelApp.Quit();
}