之前我使用Apache POI 2.5.1使用.xls
导出HSSFWorkbook
文件。
使用更新的Apache POI到3.13我使用.xlsx
导出SXSSFWorkbook
文件,但导出已损坏的文件。
MS Excel无法以文件格式或扩展程序无效错误打开文件。
请注意,我只在WebLogic
服务器上遇到此问题,它适用于JBoss
。
任何人都可以帮助我在这里做错了吗?
代码:
List<JRField> fields = ds.getFields();
SXSSFWorkbook wb = new SXSSFWorkbook();
SXSSFSheet sheet = wb.createSheet("Sheet1");
try {
CellStyle cellStyle = wb.createCellStyle();
CellStyle cellStyleColName = wb.createCellStyle();
CellStyle cellStyleTitle = wb.createCellStyle();
Font boldFont = wb.createFont();
boldFont.setFontHeightInPoints((short)16);
boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// Cell Style for body
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
cellStyle.setWrapText(true);
// Cell Style for Column Names
cellStyleColName.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
cellStyleColName.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyleColName.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); // single line border
cellStyleColName.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM); // single line border
// Cell Style for Title
cellStyleTitle.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
cellStyleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyleTitle.setFont(boldFont);
// Creating Title Row
Row row1 = sheet.createRow((short) 0);
// Creating the Title line
Cell cell1 = row1.createCell((short) 0);
cell1.setCellValue("Demo Title");
cell1.setCellStyle(cellStyleTitle);
// Title Region
CellRangeAddress regionTitle = new CellRangeAddress( (short) 0, // From Row
(short) 0, // From Col
(short) 0, // To Row
(short) (this.displayCols.size()-1) // To Col
);
sheet.addMergedRegion(regionTitle);
// Column Name Row
int j =0;
Row row2 = sheet.createRow((short) 1);
for (ReportColumn col : this.displayCols)
{
Cell cell2 = row2.createCell((short) j++);
cell2.setCellValue(col.getDisplayName());
cell2.setCellStyle(cellStyleColName);
}
int i =2;
while (ds.next()) {
Row rows = sheet.createRow((short) 0 + i);
int k = 0;
for (JRField field : fields) {
String fieldAsString = (ds.getFieldValue(field) != null ? ds.getFieldValue(field).toString():null);
Cell cell = rows.createCell((short) k++);
cell.setCellStyle(cellStyle);
cell.setCellValue(fieldAsString);
}
i++;
if (i > RECORD_LIMIT_FROM_POI){
log.info("Row limit from poi reached #1048576 and exported data is truncated.");
break;
}
}
wb.write(os);
}
catch (Exception e) {
log.error("error in createXlsFile method", e);
}
尝试失败:
application/vnd.ms-excel
的响应标头中的mime类型
到vnd.openxmlformats-officedocument.spreadsheetml.sheet
xlsx=vnd.openxmlformats-officedocument.spreadsheetml.sheet
答案 0 :(得分:0)
这可能会耗费更多资源,但您尝试过:
XSSFWorkbook wb = new SXSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Sheet1");
而不是SXSSF。
这里有各种类型的讨论:HSSFWorkbook vs XSSFWorkbook and the advantages/disadvantages of XSSFWorkbook and SXSSFWorkbook?