NPOI Excel数字格式不显示在asp.net中的Excel工作表中

我正在尝试使用NPOI库在Excel中创build双精度和数字格式的单元格。 我使用类似的代码

Dim cell As HSSFCell = row.CreateCell(j) cell.SetCellValue(Double.Parse(dr(col).ToString)) 

在Excel中,数字alignment正确,但是当我检查格式时显示在“常规”

替代文字

然后我改变了我的代码,如下所示

  Dim cell As HSSFCell = row.CreateCell(j) cell.SetCellValue(Double.Parse(dr(col).ToString)) Dim cellStyle As HSSFCellStyle = hssfworkbook.CreateCellStyle cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,#0.0") cell.CellStyle = cellStyle 

然后,当打开文件时,它给出了错误,也花了这么久打开。 但Excel格式显示在“数字”

显示错误如下。

替代文字

如何解决这个问题?

看看这个 ,你是否为每个单元格创build一个cellStyle对象? 如果不这样做。 尝试在创build单元格之前创build几个样式,然后将这些预定义的样式应用于您创build的单元格。

Hare是使用NPOI在Excel文档中创build双格式的简单方法。

 //make NUMERIC Format in Excel Document // Author: Akavrelishvili var eRow = sheet.CreateRow(rowIndex); //create new Row , rowIndex - it's integer, like : 1,2,3 eRow.CreateCell(0).SetCellValue(row["ProvidName"].ToString()); //create cell and set string value double Amount = Convert.ToDouble(row["Amount"].ToString()); //convert string to double eRow.CreateCell(1).SetCellValue(Amount); // create cell and set double value. 

这是工作版本,我用了很多项目。

非常困难的是在Excel中插入DateTime格式,在互联网上没有很好的例子,我认为这有助于人们做正确的方式。 我向你展示代码示例:

  //make Date Time Format in Excel Document // Author: Akavrelishvili 

var eRow = sheet.CreateRow(rowIndex); //创build新的Row // rowIndex – 它是整数,如:1,2,3

  ICellStyle cellDateStyle = workBook.CreateCellStyle(); //create custom style cellDateStyle.DataFormat = workBook.CreateDataFormat().GetFormat("dd/mm/yyyy"); //set day time Format eRow.CreateCell(3).SetCellValue(Convert.ToDateTime(row["Date"])); //set DateTime value to cell eRow.GetCell(6).CellStyle = cellDateStyle; // Restyle cell using "cellDateStyle" I hope it helps 

要修复太多不同的单元格样式,可以在任何可能正在运行的循环之外声明所有样式。

我假设你'j'将是枚举,所以我会放弃你在一个正确的格式为你。

 Dim cellStyle As HSSFCellStyle = hssfworkbook.CreateCellStyle cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,#0.0") For col = 0 To ColoumCounter For j = 0 To Counter Dim cell As HSSFCell = row.CreateCell(j) cell.SetCellValue(Double.Parse(dr(col).ToString)) cell.CellStyle = cellStyle Next Next 

这应该更好一些,通过限制“新”风格的数量。