2017-11-02 3 views
-1

レスポンスからOutputStreamを取得した場合、ブラウザに返されるレスポンスにOutputStreamの内容を書き込むことはできますか? 私のシナリオでは、シートをダウンロードする際にパスワードをExcelファイルに設定したいと考えています。 そのようなコードを書いたのです。Java Servletを使用してレスポンスからExcelheetへのパスワード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(); 
関連する問題