Java 如何在编辑excel文件后下载该文件

Java 如何在编辑excel文件后下载该文件,java,Java,我的web应用程序有一个功能:允许用户下载包含用户可以在界面上选择的数据的示例excel文件。 例如:在我的界面上有一个选择国家的下拉框,还有一个下载按钮。 在我的应用程序中有一个excel文件Template.xls。当用户选择country并单击按钮Download时,我在Template.xls中编辑country字段,其值等于country dropbox的值,然后写入响应。用户将收到一个excel文件Template.xls,其值为country。我的代码如下: 函数editExcel

我的web应用程序有一个功能:允许用户下载包含用户可以在界面上选择的数据的示例excel文件。 例如:在我的界面上有一个选择国家的下拉框,还有一个下载按钮。 在我的应用程序中有一个excel文件Template.xls。当用户选择country并单击按钮Download时,我在Template.xls中编辑country字段,其值等于country dropbox的值,然后写入响应。用户将收到一个excel文件Template.xls,其值为country。我的代码如下:

函数editExcelFile:

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();
}
单击下载按钮时提交的函数:

@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;
}

但下载Template.xls时,country的值不是最后的选择,因为Template.xls文件尚未更新,但已下载。那么,我如何检查我的excel文件在下载之前是否已更新。有人帮我吗?非常感谢

不要认为这会解决您的问题,但是,对我来说,将签名更改为follow public Workbook editExcelFileString、String,从而更改为onSubmit using Workbook.writeresponse.getOutputStream可能您的浏览器正在缓存请求?尝试使用curl-v'http://localhost/path/to/resource?country=us'-o output.xls