【问题标题】:Preserving Data Type At Exporting DataTable to Excel with Open Xml SDK in C#在 C# 中使用 Open Xml SDK 将 DataTable 导出到 Excel 时保留数据类型
【发布时间】:2017-08-11 09:59:54
【问题描述】:

我的代码工作正常,除了将数字保持为数字。 If 语句在我调试时捕获双精度值。然而,除了字符串之外,我无法将数据类型写入 Excel。如果我更准确一点,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);
}

【问题讨论】:

  • 从我刚刚报告为重复的问题的答案中可以看出,在数字的情况下首先将值放入然后更改数据类型。否则,您仍然通过ToString 方法将其设为字符串

标签: c# xml excel datarow


【解决方案1】:

我也遇到过同样的问题。 如果您使用逗号作为小数分隔符的语言环境,似乎会出现问题。在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多