9,632 questions
Take a look at Spreadsheetlight NuGet package (free).
Example with no formatting.
public static void ExportToExcel(DataTable table, string fileName, bool includeHeader, string sheetName)
{
using var document = new SLDocument();
// import to first row, first column
document.ImportDataTable(1, SLConvert.ToColumnIndex("A"), table, includeHeader);
// give sheet a useful name
document.RenameWorksheet(SLDocument.DefaultFirstSheetName, sheetName);
document.SaveAs(fileName);
}
Example showing how to format a date column and specify the start row.
public static void ExportToExcel(DataTable table, string fileName, bool includeHeader, string sheetName, int row)
{
using var document = new SLDocument();
document.ImportDataTable(row, SLConvert.ToColumnIndex("A"), table, includeHeader);
// give sheet a useful name
document.RenameWorksheet(SLDocument.DefaultFirstSheetName, sheetName);
SLStyle dateStyle = document.CreateStyle();
dateStyle.FormatCode = "mm-dd-yyyy";
// format a specific column using above style
int dateColumnIndex = 6;
document.SetColumnStyle(dateColumnIndex, dateStyle);
document.SaveAs(fileName);
}