How to download an excel file after editing it
<p>My web application has a function: allow user download a sample excel file contains data that user can choose on the interface.
For example: in my interface has 1 dropbox to choose country, and a button "Download".
In my application has an excel file "Template.xls". When user choose country and click button "Download", I edit "Country" field in Template.xls with the value is equal to the value of country dropbox, then write to response. User will receipt an excel file "Template.xls" with the value of country. My code as follow:</p>

<p>Function editExcelFile:</p>

<pre><code>private void editExcelFile(String filePath, String country) throws IOException, InterruptedException {
    InputStream fileIn = this.getClass().getResourceAsStream(filePath);

    HSSFWorkbook workbook = new HSSFWorkbook(fileIn);
    HSSFSheet sheet = workbook.getSheetAt(0);
    HSSFRow row = sheet.getRow(1);
    if (row == null ) {
        row = sheet.createRow(1);
    }
    HSSFCell cell7 = row.getCell(7);
    if (cell7 == null)
        cell7 = row.createCell(7);
    cell7.setCellType(Cell.CELL_TYPE_STRING);
    cell7.setCellValue(country);

    HSSFCell cell14 = row.getCell(14);
    if (cell14 == null)
        cell14 = row.createCell(14);
    cell14.setCellType(Cell.CELL_TYPE_STRING);
    cell14.setCellValue(country);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream(this.getClass().getResource(filePath).getPath());
    workbook.write(fileOut);
    fileOut.flush();
    fileOut.close();
    fileIn.close();
}
</code></pre>

<p>Function onSubmit (when click "Download" button):</p>

<pre><code>@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
    String templateFilePath = "/Template.xls";
    String country = request.getParameter("country");
    editExcelFile(templateFilePath, country);
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=Template.xls");
    InputStream fileIn = this.getClass().getResourceAsStream(templateFilePath);
    ServletOutputStream out = response.getOutputStream();

    byte[] outputByte = new byte[4096];
    while (fileIn.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    fileIn.close();
    out.flush();
    out.close();
    return null;
}
</code></pre>

<p>But when Template.xls is downloaded, the value of country is not last choices because the "Template.xls" file is not yet updated but is downloaded. So, how can I check my excel file is updated before download it. Is there any body help me? Thanks so much!</p>
