使用C#中的Open XML SDK将DataTable导出到Excel是一种常见的数据导出方法。Open XML SDK是一个免费的开源库,可以用于创建、读取和编辑Microsoft Office格式的文档,如Word、Excel等。
以下是使用Open XML SDK将DataTable导出到Excel的步骤:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Data;
using System.IO;
public static void ExportDataTableToExcel(DataTable dataTable, string filePath)
{
using (var spreadsheetDocument = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
var workbookPart = spreadsheetDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
var headerRow = new Row();
foreach (DataColumn column in dataTable.Columns)
{
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in dataTable.Rows)
{
var dataRow = new Row();
foreach (DataColumn column in dataTable.Columns)
{
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(row[column].ToString());
dataRow.AppendChild(cell);
}
sheetData.AppendChild(dataRow);
}
}
}
var dataTable = new DataTable();
// 添加列和数据到DataTable
ExportDataTableToExcel(dataTable, "output.xlsx");
这样就可以将DataTable导出到Excel文件中了。需要注意的是,Open XML SDK可能不支持所有的Excel功能,因此在使用时需要根据具体情况进行调整。
领取专属 10元无门槛券
手把手带您无忧上云