gpt4 book ai didi

java - 使用 POI 从 .xls 升级到 .xlsx

转载 作者:行者123 更新时间:2023-11-29 03:21:34 26 4
gpt4 key购买 nike

我有一个网络应用程序,其中有 excel 文件 (.xls) 下载选项。现在我必须在 .xlsx 中提供该功能

我正在尝试使用 POI Jar。当我尝试将其作为一个独立的应用程序时,它工作正常,但是当我尝试将其集成到 Web 应用程序中时,出现错误

Excel Found Unreadable Content in FILENAME.xlsx. do you want to recover the content of this workbook?
If you trust the source of this workbook click yes!

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;
}

有人可以帮忙吗?对不起任何糟糕的英语!谢谢。

最佳答案

我有一个非常相似的问题,请查看 Forcing the browser to download a docx file in JAVA generates a corrupted document .重点是添加响应的 Content-Length header 。

尝试让 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

关于java - 使用 POI 从 .xls 升级到 .xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com