I am attempting to create a datatable from an Excel spreadsheet using OpenXML. When getting a row's cell value using Cell.CellValue.innerXml the value returned for a monetary value entered by the user and visible on the spreadsheet is not the same value interpreted.
The spreadsheet cell is formatted as Text and the cell value is 570.81. When obtaining the data in OpenXML the value is interpreted as 570.80999999999995.
This method is used for many different excel imports where the data type for a cell by header or column index is not known when building the table.
I've seen a few post about the Ecma Office Open XML File Formats Standard and mention of numFmtId. Could this be of value?
I assume that since the data type is text and the number has two decimal places that there must be some assumption that the cell has been rounded (even though no formula exists).
I am hopeful someone can offer a solution for properly interpreting the data.
Below is the GetCellValue method:
private static string GetCellValue(SharedStringTablePart stringTablePart, DocumentFormat.OpenXml.Spreadsheet.Cell cell,DocumentFormat.OpenXml.Spreadsheet.Stylesheet styleSheet)
{
string value = cell.CellValue.InnerXml;
if (cell.DataType != null && cell.DataType.Value == DocumentFormat.OpenXml.Spreadsheet.CellValues.SharedString)
{
return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
}
else
{
if (cell.StyleIndex != null)
{
DocumentFormat.OpenXml.Spreadsheet.CellFormat cellFormat = (DocumentFormat.OpenXml.Spreadsheet.CellFormat)styleSheet.CellFormats.ChildElements[(int)cell.StyleIndex.Value];
int formatId = (int)cellFormat.NumberFormatId.Value;
if (formatId == 14) //[h]:mm:ss
{
DateTime newDate = DateTime.FromOADate(double.Parse(value));
value = newDate.Date.ToString(CultureInfo.InvariantCulture);
}
}
return value;
}
}