简体   繁体   中英

Apache POI - XSSFWorkbook + servlet response

I find a problem on using apache-poi. Here is my code.

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 file is download normally, but when i open the file, the following error message display : "When i try this, i receive the message: "We found a problem with some content in 'TestingABC.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click 'Yes'"

After i click 'Yes'

the error is as follow: "Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded."

Actually, the file data is correct, but how can i remove this message ?

Thanks.

It work after adding content Length:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM