繁体   English   中英

使用Apache POI下载文件

[英]Download a file with Apache POI

我目前正在使用Apache POI。 为了开发我的应用程序,我使用了大多数教程中提出的方法。

public void generateExcel() {

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("ma feuille");

    HSSFRow row = sheet.createRow(0);
    HSSFCell cell = row.createCell((short)0);
    cell.setCellValue(10);

    row.createCell((short)1).setCellValue(20);

    FileOutputStream fileOut;
    try {
      fileOut = new FileOutputStream("monfichier.xls");
      wb.write(fileOut);
      fileOut.close(); 
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
}

但是为了进行进一步的开发,我需要能够下载文件,而不仅仅是在目录中创建文件。 我看了一下HttpServletRequest,但是我完全迷路了。

先感谢您!

您需要创建某种端点来调用,即Spring Controller端点。 您应该调用此函数:

public void createExcelFile(final HttpServletResponse response) {
    XSSFWorkbook xssfWorkbook = null;
    try {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" file.xlsx");

        xssfWorkbook = new XSSFWorkbook();
        final XSSFSheet sheet = xssfWorkbook.createSheet("sheet1");

        writeExcelOutputData(//WRITE DATA TO FILE/SHEET/CELLS);

        xssfWorkbook.write(response.getOutputStream());
        xssfWorkbook.close();
    } catch (final Exception e) {
        LOGGER.error("File not created for download"));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM