📜  c# export datatable to excel - C# (1)

📅  最后修改于: 2023-12-03 15:13:48.898000             🧑  作者: Mango

C# Export DataTable to Excel

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.

Steps to Export DataTable to Excel in C#
  1. First, we need to add the Microsoft Office Interop Excel reference in our application. In Visual Studio, right-click on References and select Add Reference. In the search box, type "Microsoft.Office.Interop.Excel" and select it.
using Microsoft.Office.Interop.Excel;
  1. Create a new instance of the Excel Application and Workbook.
var excelApp = new Excel.Application();
var workBook = excelApp.Workbooks.Add();
  1. Create a new sheet and set its name.
var workSheet = (Worksheet)workBook.ActiveSheet;
workSheet.Name = "Data";
  1. Loop through the DataTable and fill the sheet with its 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();
    }
}
  1. Format the sheet to make it more readable.
workSheet.Columns.AutoFit();
workSheet.Rows.AutoFit();
workSheet.Range["A1:B1"].Interior.Color = ColorTranslator.ToOle(Color.LightGray);
  1. Save the file and close the Excel application.
workBook.SaveAs(@"C:\Temp\Data.xlsx");
excelApp.Quit();
Conclusion

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.