OpenXML 2.0 获取错误的单元格值
我在从 Excel 2010 工作表读取值时遇到一些问题。
在标准 Excel 2010 工作表上,我有一个单元格,其货币格式带有两位小数,值 1270,14 €
。
当我在 OpenXML 2.0(C# 代码)上读取此值时,我得到的是 1270.1400000000001
而不是原始的 1270.14
。
对于具有相同格式的任何单元格上的其他值,也会发生同样的情况。
从单元格 OpenXML 代码获取值:
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;
}
特定值传递“if”DataType 不为空条件并使用以下行检索值:
value = targetCell.CellValue.Text.Trim();
如何解决这个问题?
为什么会出现此错误?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于数字在 Excel 中存储为 double,因此您可以先将字符串解析为 double,然后转换回字符串以获取显示的值:
让 Microsoft 处理自己的问题。
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:
Let Microsoft handle its own problem.
尽管它可能不适合您的应用程序,但最简单的解决方法是简单地四舍五入您返回的值并分配它或在适用的情况下返回它。 somevarhere=Math.Round(Convert.ToDouble(value), 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)