我有一个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中修复它。
所以我找到了解决方法,而不仅仅是一个实际的解决方案。显然这是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;
}
}
我正在使用正则表达式来确定是否遇到了这个错误,然后使用一些舍入来补偿。值得注意的是,只有整数才会出现。
谢谢!