在C#中使用Open XML SDK将DataTable导出到Excel时保留数据类型,可以按照以下步骤进行操作:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create("导出数据.xlsx", SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = spreadsheetDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
sheets.Append(sheet);
// 获取工作表的数据
DataTable dataTable = GetDataTable();
// 将数据写入工作表
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
WriteDataTableToSheet(dataTable, sheetData);
workbookPart.Workbook.Save();
}
private static void WriteDataTableToSheet(DataTable dataTable, SheetData sheetData)
{
// 添加表头
Row headerRow = new Row();
foreach (DataColumn column in dataTable.Columns)
{
Cell 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)
{
Row dataRow = new Row();
foreach (var item in row.ItemArray)
{
Cell cell = new Cell();
cell.DataType = GetCellDataType(item);
cell.CellValue = new CellValue(item.ToString());
dataRow.AppendChild(cell);
}
sheetData.AppendChild(dataRow);
}
}
private static CellValues GetCellDataType(object value)
{
if (value is int || value is long || value is short || value is byte || value is sbyte)
{
return CellValues.Number;
}
else if (value is decimal || value is double || value is float)
{
return CellValues.Number;
}
else if (value is DateTime)
{
return CellValues.Date;
}
else if (value is bool)
{
return CellValues.Boolean;
}
else
{
return CellValues.String;
}
}
以上代码将DataTable的数据写入到Excel工作表中,并根据数据类型设置相应的单元格数据类型。导出的Excel文件名为"导出数据.xlsx",工作表名为"Sheet1"。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云