1

私のWebアプリケーションには機能があります。ユーザーがインターフェイスで選択できるデータを含むサンプルのExcelファイルをダウンロードできるようにします。例: 私のインターフェイスには、国を選択するための 1 つのドロップボックスと、[ダウンロード] ボタンがあります。私のアプリケーションには、Excel ファイル「Template.xls」があります。ユーザーが国を選択して「ダウンロード」ボタンをクリックすると、Template.xls の「国」フィールドを国ドロップボックスの値と同じ値で編集し、応答に書き込みます。ユーザーは、国の値を含む Excel ファイル「Template.xls」を受け取ります。次のように私のコード:

関数 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 をダウンロードする場合、「Template.xls」ファイルはまだ更新されていませんがダウンロードされるため、country の値は最後の選択肢ではありません。では、ダウンロードする前にExcelファイルが更新されていることを確認するにはどうすればよいですか。私を助けてくれる体はありますか?本当にありがとう!

4

0 に答える 0