[英]Reading a Number from an Excel Sheet is changing the value
我有一個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中的錯誤。 我在這里找到了指向該方向的初始文檔
我找到的解決方法是:
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;
}
}
我正在使用正則表達式確定是否遇到此錯誤,然后使用一些舍入進行補償。 有趣的是,只有整數出現了。
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.