我的Web应用程序具有以下功能:允许用户下载包含用户可在界面上选择的数据的示例excel文件。 例如:在我的界面中有1个用于选择国家/地区的保管箱,以及一个“下载”按钮。 在我的应用程序中有一个excel文件“Template.xls”。当用户选择国家并单击“下载”按钮时,我在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();
}
功能onSubmit(点击“下载”按钮时):
@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文件是否已更新。有没有身体帮助我?非常感谢!