📅  最后修改于: 2023-12-03 15:13:48.898000             🧑  作者: Mango
In this tutorial, we will learn how to export a DataTable to Excel using C#. This is a very common task in many applications where data needs to be exported in a readable and editable format.
using Microsoft.Office.Interop.Excel;
var excelApp = new Excel.Application();
var workBook = excelApp.Workbooks.Add();
var workSheet = (Worksheet)workBook.ActiveSheet;
workSheet.Name = "Data";
for (int i = 0; i < dataTable.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
}
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
workSheet.Cells[i + 2, j + 1] = dataTable.Rows[i][j].ToString();
}
}
workSheet.Columns.AutoFit();
workSheet.Rows.AutoFit();
workSheet.Range["A1:B1"].Interior.Color = ColorTranslator.ToOle(Color.LightGray);
workBook.SaveAs(@"C:\Temp\Data.xlsx");
excelApp.Quit();
In this tutorial, we have learned how to export a DataTable to Excel using C#. This is a simple and effective way of exporting data in a readable and editable format.