0

I currently use 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.

Thank you in advance!

f_puras
  • 2,521
  • 4
  • 33
  • 38
  • Does this code run on the server side. Do you want download xls from client side? – Rudziankoŭ Mar 11 '16 at 10:00
  • 3
    Consider using a [file download servlet](http://stackoverflow.com/q/1442893/1606632). – f_puras Mar 11 '16 at 10:03
  • Yes the code is executed on the server side, the client has to press a button and I would like that when he appuit above, it starts downloading the file since actuellementle xls file is simply file in the directory. fileOut = new FileOutputStream("monfichier.xls"); – Guillaume Taillez Mar 11 '16 at 10:04
  • it doesn't have nothing to do with Apache POI. Since client doesn't have to know anything about server processes except path of created xls. Hope it makes things clear. – Rudziankoŭ Mar 11 '16 at 10:13
  • 1
    Maybe this is what you need [send excel file to client using java servlets](http://stackoverflow.com/questions/17491527/send-excel-file-to-client-using-java-servlets) – Igor Kudryashov Mar 11 '16 at 10:22
  • Yes I have tried using servlets but the problem is that when I launched my application, my IDE crashed. – Guillaume Taillez Mar 11 '16 at 10:25
  • It sounds simple but in person arrives to meet me = S – Guillaume Taillez Mar 14 '16 at 14:41

1 Answers1

1

You need to create some sort of end point to call i.e a Spring Controller end point. 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"));
    }
}
rogger2016
  • 821
  • 3
  • 11
  • 28