【发布时间】:2016-09-06 15:49:41
【问题描述】:
之前我使用 Apache POI 2.5.1 使用 HSSFWorkbook 导出 .xls 文件。
随着将 Apache POI 更新到 3.13,我正在使用 SXSSFWorkbook 导出 .xlsx 文件,但它正在导出损坏的文件。
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 - 在 WebLogic 的自定义 mime 映射文件中添加了
xlsx=vnd.openxmlformats-officedocument.spreadsheetml.sheet
【问题讨论】:
-
哪个weblogic版本? 12.1.3?
-
@Slettal 它的 10.3.5.0
-
好的,您的代码在 WL 12.1.3 上运行没有问题。没有安装 10.3.5 :(
-
我能拿到的最旧版本是 10.3.6,它也可以工作。我只添加了以下 3 个 POI 库:poi-3.13、poi-ooxml-3.13、poi-ooxml-schema-3.13。全部在 windows 7 系统上,在 java 8 SDK 上运行
标签: java excel apache-poi weblogic xlsx