用NPOI 時, 當存取的cell 為方程式時, 會有機會因為它將小數當做double 計算而出錯. 在 C# 中, double 與 decimal 最大分別是double 為浮位數 (Floating point), 即是它會用byte 進在儲存和運算. 而decimal 則是用十位數進行.
在專案中, 因為要保存格式, 故用cell的dataformat 進行轉換, 若轉換不到才用回原本的CellNumericValue. 部份程式碼如下:
// NPOI issue, it will calculate value in double format, so need to change in string format with cell data format and convert back to double.
// Append below if any specif char. found.
double castValue;
bool castResult= double.TryParse(cell.NumericCellValue.ToString(cell.CellStyle.GetDataFormatString())
.Replace(",", "")
.Replace("_", "")
.Replace("(", "")
.Replace(")", "")
.Replace("$", "")
, out castValue);
if (castResult == false)
castValue = cell.NumericCellValue;
dr[i] = castValue;
Leave a Reply