简体   繁体   English

使用Apache POI下载文件

[英]Download a file with Apache POI

I currently use Apache POI. 我目前正在使用Apache POI。 For the development of my application I used the method proposed in most tutorials. 为了开发我的应用程序,我使用了大多数教程中提出的方法。

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

But for further development, I need to be able to download the file and not just to create in a directory. 但是为了进行进一步的开发,我需要能够下载文件,而不仅仅是在目录中创建文件。 I watched a little HttpServletRequest but I am completely lost. 我看了一下HttpServletRequest,但是我完全迷路了。

Thank you in advance! 先感谢您!

You need to create some sort of end point to call ie a Spring Controller end point. 您需要创建某种端点来调用,即Spring Controller端点。 The you should call this functions: 您应该调用此函数:

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