如何覆盖PrimeFaces p:dataExporter错误地将数字导出为Excel中的文本?

PrimeFace p:dataExporter标签默认情况下将数字数据导出为文本,导致在左上angular有一个绿色三angular形的单元格。 在PrimeFaces展示示例中也可以看到,如果您单击cars表下的Excel导出。

我怎样才能覆盖这个默认值,以确保我的数字列不导出为文本? 我试图使用postProcessor属性指向我的方法,它使用POI API设置所有数据单元格的Excel格式,但没有生效(没有改变任何东西):

 public void formatExcel(Object doc) { HSSFWorkbook book = (HSSFWorkbook)doc; HSSFSheet sheet = book.getSheetAt(0); HSSFRow header = sheet.getRow(0); int colCount = header.getPhysicalNumberOfCells(); int rowCount = sheet.getPhysicalNumberOfRows(); HSSFCellStyle numStyle = book.createCellStyle(); numStyle.setDataFormat((short)1); for(int rowInd = 1; rowInd < rowCount; rowInd++) { HSSFRow row = sheet.getRow(rowInd); for(int cellInd = 1; cellInd < colCount; cellInd++) { HSSFCell cell = row.getCell(cellInd); String val = cell.getStringCellValue(); cell.setCellStyle(numStyle); } } } 

我也试过了

 cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); 

但是那给了我

 java.lang.IllegalStateException: Cannot get a numeric value from a text cell 

所以这意味着所有的数据都被不加区分地导出为文本,之后你甚至不能改变它。

在你的后处理程序中,你无处设置单元格的值为一个整数。 你设置的types,但不是值。 设置types是不够的。 您必须将值转换为数字并重新设置

这是最终为我工作的。 这是远离优雅,但它的作品:

 HSSFCellStyle intStyle = book.createCellStyle(); intStyle.setDataFormat((short)1); HSSFCellStyle decStyle = book.createCellStyle(); decStyle.setDataFormat((short)2); HSSFCellStyle dollarStyle = book.createCellStyle(); dollarStyle.setDataFormat((short)5); for(int rowInd = 1; rowInd < rowCount; rowInd++) { HSSFRow row = sheet.getRow(rowInd); for(int cellInd = 1; cellInd < colCount; cellInd++) { HSSFCell cell = row.getCell(cellInd); //This is sortof a hack to counter PF exporting all data as text //We capture the existing value as string, convert to int, //then format the cell to be numeric and reset the value to be int String strVal = cell.getStringCellValue(); //this has to be done to temporarily blank out the cell value //because setting the type to numeric directly will cause //an IllegalStateException because POI stupidly thinks //the cell is text because it was exported as such by PF... cell.setCellType(HSSFCell.CELL_TYPE_BLANK); cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); strVal = strVal.replace(",", StringUtils.EMPTY); if(strVal.indexOf('.') == -1) { //integer //numStyle.setDataFormat((short)1); int intVal = Integer.valueOf(strVal); cell.setCellStyle(intStyle); cell.setCellValue(intVal); } else { //double if(strVal.startsWith("$")) { strVal = strVal.replace("$", StringUtils.EMPTY); //numStyle.setDataFormat((short)5); cell.setCellStyle(dollarStyle); } else { //numStyle.setDataFormat((short)2); cell.setCellStyle(decStyle); } double dblVal = Double.valueOf(strVal); cell.setCellValue(dblVal); } } }