我正在嘗試更改的單元格類型已填充 Apache POI中的單元格,但我不斷收到IllegalStateException。問題應該可以使用POI(-ooxml)3.16重現。Apache POI無法將填充的單元格格式化爲數字
public static void main(String[] args) throws Exception
{
//Setting up the workbook and the sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet s = wb.createSheet();
//Setting up the CTTable
XSSFTable t = s.createTable();
CTTable ctt = t.getCTTable();
ctt.setId(1);
ctt.setName("CT Table Test");
ctt.setRef("A1:B2");
CTTableColumns cttcs = ctt.addNewTableColumns();
CTTableColumn cttc1 = cttcs.addNewTableColumn();
cttc1.setId(1);
CTTableColumn cttc2 = cttcs.addNewTableColumn();
cttc2.setId(2);
//Creating the cells
XSSFCell c1 = s.createRow(0).createCell(0);
XSSFCell c2 = s.getRow(0).createCell(1);
XSSFCell c3 = s.createRow(1).createCell(0);
XSSFCell c4 = s.getRow(1).createCell(1);
//Inserting values; some numeric strings, some alphabetical strings
c1.setCellValue(/*12*/"12"); //Numbers have to be inputted as a string
c2.setCellValue(/*34*/"34"); //for the code to work
c3.setCellValue("AB");
c4.setCellValue("CD");
//With those lines, the code would also crash
//c1.setCellType(CellType.NUMERIC);
//c2.setCellType(CellType.NUMERIC);
//On write() it produces a "java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell"
FileOutputStream fos = new FileOutputStream("test.xlsx");
wb.write(fos);
fos.flush();
fos.close();
wb.close();
}
而且,在不設置任何CellValue C1和C2,你實際上可以設置自己的單元格類型,以 NUMERIC突然代碼工作一次。它也可以在沒有CTTable的情況下工作。
任何想法或解決方法?或者它是POI的錯誤(因爲它試圖從任何Cell獲取字符串值,而不管其CellType如何)?
爲什麼你明確地設置細胞類型?爲什麼不讓Apache POI根據提供的值自動檢測類型? – Gagravarr
@Gagravarr如代碼註釋中所述,數字爲「自動檢測」會使代碼崩潰!不要緊,如果我去'c1.setCellValue(「12」); c1.setCellType(CellType.NUMERIC);'或者只是'c1.setCellValue(12);'。事實上,如果最後,當我想寫我的工作簿到一個文件,有一個CTTable中的任何數字單元格,它會拋出一個IllegalStateException:( –