在Apache Poi 3.7中以特定格式写入数值单元格的Double值

我需要在数值单元格中使用特定的格式编写一个Double值,我的意思是,生成的xls必须包含包含Double值的数字单元格,例如:8,1。 我正在尝试类似于:

DecimalFormat dFormat = new DecimalFormat("##.#"); dFormat.format(doubleValue); 

但是,由于格式方法返回一个string,无论我是否创build单元格作为数字或不,他们总是performance为文本单元格。 我在想两个select:

  • 强制单元格performance为数字单元格。
  • 忘记DecimalFormat并使用Double类指定逗号作为小数点分隔符,我不确定这是可能的。

任何想法?

我可能会遗漏一些东西,但是我想你只是想用格式规则来设置单元格的样式来显示一个小数位

 // Do this only once per file CellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat( wb.getCreationHelper().createDataFormat().getFormat("#.#")); // Create the cell Cell c = row.createCell(2); c.setCellValue(8.1); c.setCellStyle(cellStyle); 

这将创build一个格式化规则,创build一个单元格,将单元格设置为值8.1,然后对其进行设置

我试过这个工作正常…

 HSSFCellStyle cellStyle = wb.createCellStyle(); HSSFDataFormat hssfDataFormat = wb.createDataFormat(); String cellVal = "2500"; cellStyle.setDataFormat(hssfDataFormat.getFormat("#,##0.000")); newCell.setCellStyle(cellStyle); newCell.setCellValue(new Double(cellVal)); newCell.setCellType(Cell.CELL_TYPE_NUMERIC); 

输出是所需格式的数字值:2,500.000

你需要把两个值放在一个单元格中吗? 你能把它们分成两列吗? Excel有一个内置的“文本到列”function,你应该能够引用这个function,它将基于分隔符(如逗号)将整列文本string分成多列。 在VBA中,它看起来像这样:

 Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _ Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _ :=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True 

至于你的第一个build议的解决scheme,不可能强制Excel将某些东西作为一个数字,如果它不能转换为数字。