2017-11-02 11 views
-1

응답에서 OutputStream을 얻은 경우 브라우저로 다시 보내지는 응답에 OutputStream의 내용을 쓸 수 있습니까? 내 시나리오에서 시트를 다운로드하는 동안 Excel 파일에 암호를 설정하고 싶습니다. 이렇게 코드를 작성했습니다.자바 서블릿을 사용하여 엑셀 시트에 대한 응답에서 OutputStream 암호를 설정하려면

response.setContentType("application/vnd.ms-excel"); 
response.setHeader("Content-Disposition", "attachment; filename=TestFile.xls"); 
XSSFWorkbook wb = new XSSFWorkbook(); 
Sheet s = wb.createSheet("Demo"); 
Row row1 = s.createRow(0); 
Row row2 = s.createRow(1); 
// create cells in the row 
Cell row1col1 = row1.createCell(0); 
Cell row1col2 = row1.createCell(1); 
Cell row1col3 = row2.createCell(0); 
Cell row1col4 = row2.createCell(1); 
// add data to the cells 
row1col1.setCellValue("City Name"); 
row1col2.setCellValue("University"); 
row1col3.setCellValue("Hyderabad"); 
row1col4.setCellValue("JNTU"); 
// Add password protection and encrypt the file 
POIFSFileSystem fs = new POIFSFileSystem(); 
EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile); 
Encryptor enc = info.getEncryptor(); 
// set the password 
enc.confirmPassword("123"); 
// encrypt the file 
OPCPackage opc = wb.getPackage(); 
OutputStream os = enc.getDataStream(fs); 
opc.save(os); 
opc.close(); 
fs.writeFilesystem(response.getOutputStream()); 

암호는 Excel 시트로 설정되었지만 아래 오류가 발생하는 동안 데이터를 열 수 없습니다. enter image description here 데이터를받지 못하는 이유를 확인하고 답변 해주십시오. 미리 감사드립니다.

답변

-1

Apache POI는 xls 파일을 만드는 데 HSSFWorkbook 객체를 사용하고 xlsx 파일을 위해 XSSFWorkbook 객체를 사용합니다. xls을 만들 때 사용한 객체를 확인하십시오.

response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
response.setHeader("Content-Disposition", "attachment; filename="TestFile.xlsx"); 

         File fileVal = new File("TestFile.xlsx"); 

         XSSFWorkbook wb = new XSSFWorkbook(); 
         Sheet s = wb.createSheet("Demo"); 

           //Add data to your sheet 

          // write the excel to a file 
          try { 
           FileOutputStream fileOut = new FileOutputStream(fileVal); 
           wb.write(fileOut); 
           fileOut.close(); 
          } catch (IOException e) { 
           e.printStackTrace(); 
          } 

          // Add password protection and encrypt the file 
          POIFSFileSystem fs = new POIFSFileSystem(); 
          EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile); 
          Encryptor enc = info.getEncryptor(); 

          // set the password 
          enc.confirmPassword("123"); 

          // encrypt the file 
          OPCPackage opc = OPCPackage.open(fileVal, PackageAccess.READ_WRITE); 
          OutputStream os = enc.getDataStream(fs); 
          opc.save(os); 
          opc.close(); 

          // save the file back to the filesystem 
          FileOutputStream fos = new FileOutputStream(fileVal); 
          fs.writeFilesystem(response.getOutputStream()); 
          fos.close();