![](/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.