首页 > 解决方案 > Apache POI - XSSFWorkbook + servlet 响应

问题描述

我发现使用 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 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃。”

实际上,文件数据是正确的,但我怎样才能删除此消息?

谢谢。

标签: javaexcelservletsapache-poixlsx

解决方案


添加内容长度后它可以工作:


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


推荐阅读