我有一个Web应用程序,其中有excel文件(.xls)下载选项。现在,我必须在.xlsx中提供该功能
我正在尝试使用POI罐。当我尝试将其作为独立的应用程序运行时,它可以很好地工作,但是当我尝试将其集成到Web应用程序中时,出现了以下错误:
Excel在FILENAME.xlsx中发现了不可读的内容。您要恢复此工作簿的内容吗?
如果您信任此工作簿的来源,请单击“是”!
XSSFWorkbook w = FileName.createExcelWorkbookPosition(
request.getParameter("BSNS_DT"));
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition","attachment;filename=filename.xlsx");
w.write(response.getOutputStream());
这是我创建电子表格的Java代码:
public static XSSFWorkbook createExcelWorkbookPosition(String BsnsDate)
throws Exception
{
FileOutputStream out = new FileOutputStream("workbook.xlsx");
// create a new workbook
XSSFWorkbook wb = new XSSFWorkbook();
// create a new sheet
XSSFSheet s = wb.createSheet();
// declare a row object reference
XSSFRow r = null;
// declare a cell object reference
XSSFCell c = null;
// header row and columns
r = s.createRow(0);
c = r.createCell(0);
c.setCellValue("Business Date");
//c.setCellStyle(cs);
c = r.createCell(1);
c.setCellValue("Account No");
try {
wb.write(out);
out.close();
System.out.println("File writed");
} catch (Exception e) {
System.out.println("Error");
System.out.println(e);
}
return wb;
}
谁能帮忙吗?对不起,英语不好!谢谢。
我有一个非常相似的问题,请看看强制浏览器在JAVA中下载docx文件会生成损坏的文档。重点是添加响应的Content-Length标头。
尝试createExcelWorkbookPosition
返回文件而不是XSSFWorkbook
:
public static File createExcelWorkbookPosition(String BsnsDate) throws Exception {
File file = new File("workbook.xlsx");
FileOutputStream out = new FileOutputStream(file);
// ...
return file;
}
然后:
File file = FileName.createExcelWorkbookPosition(request.getParameter("BSNS_DT"));
// ...
response.setContentLength((int) file.length());
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// if using Apache IO, the above code can be simplified to IOUtils.copy(in, out);
// if using Guava, Files.copy(file, out);
// don't forget to close your streams and flush the response buffer
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句