从Excel工作表中读取数字正在更改值

时间:2019-02-12 18:12:26

标签: c# excel xslt openxml-sdk

我有一个C#程序,可以读取excel工作簿,然后构建可以针对XSLT运行的XML文件。突然出现的问题是,字段之一是数字,并且当从excel工作表中读取它时,值正在更改。这是示例:

将读取excel电子表格,并将数据加载到数据表中。我执行此操作的方法之一是获取我创建的电子表格文档,然后在此处将单元格引用传递给此方法:

dataRow[columnIndex] = GetCellValue(spreadSheetDocument, cell);

private static string GetCellValue(SpreadsheetDocument document, Cell cell)
    {
        //This process uses the OpenXML SDK to get individual cells values to populate the DataTable
        SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
        string value = "";
        //One of the things that needed to be accounted for was empty cells
        try
        {
            value = cell.CellValue.InnerXml;
        }
        catch (Exception)
        {
            value = "";
        }
        //Setting cell data type right now just sets everything to strings
        //Later, the better option will be to work on the Date Conversions and Data Types here
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
        }
        else
        {
            return value;
        }
    }

因此,例如,如果正在读取的单元格为115,则输出如下所示:

114.99999999999999

然后在其他时间,如果值是125,则输出看起来像这样:

125.00000000000001

输出中的不一致有点令人困惑。希望也许我能对导致此问题的原因有所了解,而不是稍后再在XSLT中对其进行修复。

1 个答案:

答案 0 :(得分:1)

因此,我找到了一种解决方法,而不是实际的解决方案。显然,这是OpenXML SDK中的错误。我找到了指向该方向here

的初始文档。

我找到一种解决方法是:

private static string GetCellValue(SpreadsheetDocument document, Cell cell)
    {
        //This process uses the OpenXML SDK to get individual cells values to populate the DataTable
        SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
        string value = "";
        //One of the things that needed to be accounted for was empty cells
        try
        {
            value = cell.CellValue.InnerXml;
        }
        catch (Exception)
        {
            value = "";
        }
        //Checking to see if this string contains a decimal with values on either side
        if (Regex.IsMatch(value, regexpattern))
        {
            value = Math.Round(Double.Parse(value), 0, MidpointRounding.AwayFromZero).ToString();
        }
        //Setting cell data type right now just sets everything to strings
        //Later, the better option will be to work on the Date Conversions and Data Types here
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
        }
        else
        {
            return value;
        }
    }

我正在使用Regex确定是否遇到此错误,然后使用一些舍入进行补偿。有趣的是,只有整数出现了。

谢谢!