OpenXML 2.0 Gets wrong cell value

社会主义新天地 提交于 2020-02-22 07:32:46

问题


I'm having a bit of a problem reading a value from an Excel 2010 worksheet.

On a standard Excel 2010 worksheet I have a cell with the currency format with two decimal places and the value 1270,14 €.

When I read this value on OpenXML 2.0 (C# code) I get 1270.1400000000001 instead of the original 1270.14.

The same happens with other values on any cell with the same formating.

Get value from cell OpenXML code:

private string GetCellValue(string column, int row)
{
    column = column.ToUpper();
    var targetCell = cells.Where(p => p.CellReference == (column + row)).SingleOrDefault();

    var value = String.Empty;

    if (targetCell.DataType != null && targetCell.DataType.Value == CellValues.SharedString)
    {
        var index = int.Parse(targetCell.CellValue.Text);
        value = cellValues[index].InnerText.Trim();
    }
    else
    {
        if (targetCell.CellValue != null)
        {
            value = targetCell.CellValue.Text.Trim();
        }
        else
        {
            value = null;
        }
    }

    return value;
}

The specific value passes over the 'if' DataType is not null condition and retrieves the value with the line:

value = targetCell.CellValue.Text.Trim();

How can this be fixed ?

Why is this error even possible ?


回答1:


As the number is stored as double in Excel, you can first parse the string as double, then convert back to string to get the value for display:

    string s = Convert.ToDouble(value).ToString();

Let Microsoft handle its own problem.




回答2:


Though it may not fit your application, the easiest fix would be simply rounding off the value you get back and assigning it or returning it where applicable. somevarhere=Math.Round(Convert.ToDouble(value), 2)



来源:https://stackoverflow.com/questions/8728995/openxml-2-0-gets-wrong-cell-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!