Search code examples
javaservletsapache-poipoi-hssf

POI HSSF XLS Download issue in Servlet - New XLS file is downloading with previous sheets


I have created Servlet, which downloading POI XLS file, on the first get/post request new file is downloading with sheet0. When i am doing second request new file is downloading with two sheets sheet0 is previous request sheet1 is new request. Like wise if I did 4 request 4 sheet is available.

I want only one sheet for new request.

Servlet Code :

HSSFWorkbook wb = new HSSFWorkbook();

getGet(){
    String reportname = request.getParameter("repname");
    response.setContentType("application/vnd.ms-excel");
   response.setHeader("Content-Disposition", "attachment; filename=" + reportname + ".xls");
    HSSFSheet sheet = wb.createSheet();
    int i=0;
    while(i<10)
    {
        sheet.createRow(i);
        HSSFCell cell = sheet.getRow(i).createCell(0);
        cell.setCellValue("Test"+i);
        i++;
    }
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);
    byte [] outArray = outByteStream.toByteArray();
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();
    outStream.close();
}

Web code :

<body>
    <a href="../../DownloadXLS?repname=Myreport1">One</a>
    <a href="../../DownloadXLS?repname=Myreport2">two</a>
    <a href="../../DownloadXLS?repname=Myreport3">three</a>
</body>

I want only one sheet at the time of n'th request also.

  • Where I am wrong?
  • Any logical mistake?

Solution

  • Your servlet gets instantiated once when you start your program. Meaning that the line

    HSSFWorkbook wb = new HSSFWorkbook();
    

    only gets called once. So every time you call getGet() it will reuse the wb variable and create another sheet.

    If you move the HSSFWorkbook constructor inside your getGet() it will create a new one to work with for each get request.