簡體   English   中英

Apache POI - XSSFWorkbook + servlet 響應

[英]Apache POI - XSSFWorkbook + servlet response

我發現使用 apache-poi 有問題。 這是我的代碼。

XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(request.getSession().getServletContext().getRealPath("/Testing.xlsx")));

XSSFSheet spreadsheet = workbook.getSheet("TempSheet");

File template = new File(request.getSession().getServletContext().getRealPath("/Testing.xlsx"));
FileOutputStream out = new FileOutputStream(template);
workbook.write(out);
out.close();

      String currentTime = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
      String fileName = "TestingABC.xlsx";
      
      String absoluteDiskPath =  request.getSession().getServletContext().getRealPath("/Testing.xlsx");
      
      File f = new File(absoluteDiskPath);
      
      response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
      response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

      InputStream in = new FileInputStream(f);
      ServletOutputStream outs = response.getOutputStream();
      
      try {
          byte[] outputByte = new byte[4096];

          while (in.read(outputByte, 0, 4096) != -1) {
              outs.write(outputByte, 0, 4096);
          }
          outs.flush();
          outs.close();
          in.close();
          
      } catch (IOException ioe) {
          ioe.printStackTrace();
      } finally {
          try {
              if(outs != null)
                  outs.close(); 
              if(in != null)
                  in.close(); 
          }catch (Exception ioe2) {
              ioe2.printStackTrace(); 
          }
   
     } 
      }

Excel 文件正常下載,但是當我打開文件時,顯示以下錯誤消息:“當我嘗試此操作時,我收到消息:”我們發現 'TestingABC.xlsx' 中的某些內容存在問題。 你想讓我們盡量恢復嗎? 如果您信任此工作簿的來源,請單擊“是”

在我點擊“是”之后

錯誤如下:“Excel 已完成文件級驗證和修復。此工作簿的某些部分可能已被修復或丟棄。”

實際上,文件數據是正確的,但是如何刪除此消息?

謝謝。

添加內容長度后它工作:


response.setContentLength((int) file.length());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM