使用C#中的Open Xml SDK将DataTable导出到Excel时保留数据类型
问题描述:
除了将数字保留为数字外,我的代码正常工作。如果语句在我调试时捕获到double值。然而,我不能写入数据类型,除了字符串到Excel。如果我应该更精确,Excel中的单元格是正确的,但它们不是数字。使用C#中的Open Xml SDK将DataTable导出到Excel时保留数据类型
foreach (System.Data.DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
if (dsrow[col].GetType() == typeof(Double))
{
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
}
else
{
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
}
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
答
我一直在努力解决同样的问题。 看来如果您使用逗号作为小数点分隔符的语言环境,则会出现问题。在XML中,它应该是美式格式。
因此,在指定的ToString工作CutureInfo我:
var dataRow = new Row();
var cell = new Cell();
cell.CellValue = new CellValue(1.234.ToString(new CultureInfo("en-US")));
cell.DataType = CellValues.Number;
dataRow.AppendChild(cell);
sheetData.AppendChild(dataRow);
[的Office Open XML SDK号码写入到表(可能的重复https://stackoverflow.com/questions/16607063/office-open-xml -sdk-writing-numbers-to-sheet) – Kyra
正如我刚刚在数字的情况下报告为重复的问题的答案中可以看到的,首先将该值放入数据类型中,然后更改数据类型。否则,你仍然使用'ToString'方法将它作为一个字符串 – Kyra