使用NPOI在Excel中设置整数值
我有一个Excel行,我需要在第一列使用NPOI编写5
,第二列使用7.0
。 编写这些值非常简单,但是当我需要在同一行中写入时, 5
被格式化为5.0
。
写5
,我用:
public static void SetCellValue(IRow row) { var cell = row.CreateCell(1); // column 1 int value = 5; cell.SetCellType(CellType.Numeric); cell.SetCellValue(value); // 5 is written }
要写7.0
,我使用:
public static void SetCellValue(IRow row) { var cell = row.CreateCell(2); // column 2 int value = 7; cell.SetCellType(CellType.Numeric); cell.SetCellValue(value); var dataFormat = cell.Sheet.Workbook.CreateDataFormat(); var strFormat = "0.0"; cell.CellStyle.DataFormat = dataFormat.GetFormat(strFormat); // 7.0 is written }
要写5
和7.0
,我正在使用:
public static void SetCellValue(IRow row) { var cell1 = row.CreateCell(1); // column 1 int value1 = 5; cell1.SetCellType(CellType.Numeric); cell1.SetCellValue(value1); var cell2 = row.CreateCell(2); // column 2 int value2 = 7; cell2.SetCellType(CellType.Numeric); cell2.SetCellValue(value2); var dataFormat = cell2.Sheet.Workbook.CreateDataFormat(); var strFormat = "0.0"; cell2.CellStyle.DataFormat = dataFormat.GetFormat(strFormat); // 5.0 and 7.0 is written and not 5 and 7.0 }
有什么build议么? 我试图格式化第一个元素(数字5
)使用格式,如var strFormat = "0";
和var strFormat = "#";
但它仍然是5.0
而不是5
附加说明:我正在使用NPOI版本2.1.1
我喜欢NPOI,但是有时我会遇到一些奇怪的错误。 你的问题似乎是那种types之一。
要解决这个问题,你必须:
-
在Excel模板中创build一行,并根据需要进行格式化。
-
从格式化的内容创build一个新的行(您要写入的地方)复制。
int formattedRowIndex = 1; int newRowIndex = 2; IRow row = sheet.CopyRow(formattedRowIndex, newRowIndex);
- 写入值而不应用任何其他格式。
row.CreateCell(1).setCellValue(5); row.CreateCell(2).setCellValue(7); // Output: 5 and 7.0
- 删除虚拟行:
sheet.RemoveRow(formattedRowIndex);