簡體   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