本文介绍了从.xls的升级与POI为原来的.xlsx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序在我所擅长文件(.xls)下载选项。现在我要提供的.xlsx该功能

我试图使用POI罐。当我尝试这样做,因为它工作正常独立的应用程序,但是当我尝试在集成到Web应用程序,我得到一个错误

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());

Here's the Java code where I create the spreadsheet:

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

Can anyone please help? Sorry for any bad English! Thanks.

解决方案

I had a quite similar issue, please have a look at Forcing the browser to download a docx file in JAVA generates a corrupted document. The point was to add the Content-Length header of the response.

Try to make createExcelWorkbookPosition returning the file instead of the XSSFWorkbook:

public static File createExcelWorkbookPosition(String BsnsDate) throws Exception {
    File file = new File("workbook.xlsx");
    FileOutputStream out = new FileOutputStream(file);
    // ...
    return file;
}

Then:

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

这篇关于从.xls的升级与POI为原来的.xlsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:40
查看更多