![](/img/trans.png)
[英]File is corrupted after creating excel (.xlsx) file by using Apache POI with Java
[英]Apache Poi the Excel(.xlsx) file is corrupted. (Using XSSF)
我正在使用Apache POI ,我创建了一个 XSSF 工作簿并尝试打开一个 xlsx 文件。 它在本地运行良好。 但是当我用 excel 打开来自真实服务器(AWS EC2、Tomcat8、JDK 1.8)的 Excel 文件时,它说文件已损坏(.xls 有效)。 这是我的代码:
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractXlsxView;
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
@SuppressWarnings("unchecked")
List<BoardArticleDto> list = (List<BoardArticleDto>)model.get("data");
String filename = HttpUtils.uriEncoding("문의내역리스트.xlsx", StandardCharsets.UTF_8);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";");
response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
int cnt = 0, rowNum = 0;
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("문의내역리스트");
Row row = null;
row = sheet.createRow(rowNum++);
row.createCell(cnt++).setCellValue( "유형" );
sheet.setColumnWidth(cnt, 30 * 256);
row.createCell(cnt++).setCellValue( "첨부파일" );
sheet.setColumnWidth(cnt, 40 * 256);
row.createCell(cnt++).setCellValue( "제목" );
sheet.setColumnWidth(cnt, 20 * 256);
row.createCell(cnt++).setCellValue( "작성자" );
sheet.setColumnWidth(cnt, 26 * 256);
row.createCell(cnt++).setCellValue( "등록일자" );
row.createCell(cnt++).setCellValue( "답변여부" );
int rownum = 1;
if( null != list ){
for( BoardArticleDto bda : list ){
cnt = 0;
row = sheet.createRow(rownum);
row.createCell(cnt++).setCellValue( Converter.toStr(bda.getCSC_NAME1()) );
row.createCell(cnt++).setCellValue( Converter.toStr(bda.getBDA_FILE1()) );
row.createCell(cnt++).setCellValue( Converter.toStr(bda.getBDA_NAME()) );
row.createCell(cnt++).setCellValue( Converter.toStr(bda.getMB_NAME()) );
row.createCell(cnt++).setCellValue( Converter.toStr(bda.getBDA_INDATE()).substring(0, 10) );
row.createCell(cnt++).setCellValue( Converter.toStr(bda.getBDA_REPLYYN()) );
rownum++;
}
}
OutputStream fileOut = response.getOutputStream();
wb.write(fileOut);
fileOut.close();
}
}
本地Spring4、jdk1.8、tomcat 8.0、maven
真正的AWS EC2 Amazon linux2、jdk1.8、tomcat 8.0(不含 Apache Webserver)
Apache POI版本 3.10.1
我看不到整个代码,但我建议检查这个response.getOutputStream()
Debug 并查看它返回什么,如果该值不是您想要的,请检查您的响应可能有什么问题。
如果正确,请尝试使用普通字符(不是韩语)创建一个简单的文件。如果创建此文件没有问题,则是编码问题。 通过这种方式,您可以找到问题的根本原因。
我不确定这是否会解决您的问题,但是当您不再需要它时,请始终使用wb.close()
您的工作簿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.