POI-XSSF:用户定义的数据格式

我正在阅读一个excel,这似乎有user defined data formats 。 例如它有一个数据格式: "yyyy"E ,它只是以yyyy格式显示date,后面跟着字母E.

现在,这种格式不是内置的可用格式的一部分。

所以,似乎当我尝试将此设置为CellStyle DataFormat ,它不起作用。

首先我读了一个工作簿,然后从这个工作簿中创buildDataFormat

 XSSFWorkbook wb = new XSSFWorkbook(excelToRead); XSSFDataFormat df = wb.createDataFormat(); 

df对象现在也具有user defined data formats (通过打印检查直到200)。 现在,我尝试在同一个工作簿中创build一个新的单元格,使用这种新的样式:

 XSSFCell cellTemp = row.createCell(0); XSSFCellStyle styleTemp = wb.createCellStyle(); styleTemp.setDataFormat(df.getFormat(cell.getCellStyle().getDataFormatString())); cellTemp.setCellStyle(styleTemp); cellTemp.setCellValue(cell.getStringCellValue()); System.out.print(formatter.formatCellValue(cellTemp)+" "); 

但是,格式化程序没有给我正确的string值,而是给了我date的基础Integer值(如果格式不被识别,我猜是默认值)。

在XSSF中使用用户定义格式的正确方法是什么?

更新 :似乎我能够使用其他用户定义的格式,如yyyy0.0%但不是yyyy"E"yyyy"A"

我不清楚你到底想要达到什么目的。 但是,如果DataFormatter格式不正确,那么还可以使用从CellFormatter派生的类。

例:

 import java.io.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.format.*; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.awt.Desktop; import java.util.Date; class CustomDateFormatTest { public static void main(String[] args) { try { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("Sheet1"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue(new Date()); DataFormat format = wb.createDataFormat(); CellStyle cellstyle = wb.createCellStyle(); cellstyle.setDataFormat(format.getFormat("yyyy\"E\"")); cell.setCellStyle(cellstyle); OutputStream out = new FileOutputStream("CustomDateFormatTest.xlsx"); wb.write(out); wb.close(); System.out.println("Done"); File outputfile = new File("CustomDateFormatTest.xlsx"); Desktop.getDesktop().open(outputfile); InputStream inp = new FileInputStream("CustomDateFormatTest.xlsx"); wb = WorkbookFactory.create(inp); sheet = wb.getSheetAt(0); row = sheet.getRow(0); cell = row.getCell(0); //This will not format properly DataFormatter dataformatter = new DataFormatter(); System.out.println(dataformatter.formatCellValue(cell)); //This will format properly String formatstring = cell.getCellStyle().getDataFormatString(); System.out.println(formatstring); CellDateFormatter celldateformatter = new CellDateFormatter(formatstring); //For using CellDateFormatter we need to know that the cell value is a Date. System.out.println(celldateformatter.format(cell.getDateCellValue())); } catch (InvalidFormatException ifex) { } catch (FileNotFoundException fnfex) { } catch (IOException ioex) { } } }