I am transfering values from a SQL Database into an ExcelSheet. I can write Strings and Integers no problem but when I write doubles Excel needs to repair the document. It says the Numbers are formated as text.
i use this code :
double val = Math.Round(reader.GetDouble(3),2);
cell.CellValue= new CellValue(Convert.ToString(val));
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
Please try to use:
cell.CellValue = new CellValue(val.ToString(CultureInfo.InvariantCulture));
instead of:
cell.CellValue= new CellValue(Convert.ToString(val));
Using CultureInfo.InvariantCulture does not cover all cases very large or very small numbers as well as NaN and +-Inf will stil trigger Excel to repair the file. At the moment I am using this as a work around:
bool isNumeric = IsNumeric(value, out double number);
if (isNumeric && ! (double.IsNaN(number) | double.IsInfinity(number) | Math.Abs(number) >1e100))
{
cell.DataType = CellValues.Number;
cell.CellValue = new CellValue(String.Format(CultureInfo.InvariantCulture, "{0:0.####################}", number));
}
else
{
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(value.ToString());
}
Is there a better solution to this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.