java poi 匯出excel加密

我和一隻貓發表於2017-03-27

java poi 匯出excel加密

匯出excel加密,要先把excel匯出到伺服器,獲取檔案路徑,加密,下載

maven引入新版本poi jar包

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16-beta2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16-beta2</version>
        </dependency>

程式碼

//匯出加密
public static void encryptExportExcel(List<Map> list,String path,String[] title,String[] colum) throws IOException, InvalidFormatException, GeneralSecurityException, org.apache.poi.openxml4j.exceptions.InvalidFormatException {
        try { 
            Workbook wb = new XSSFWorkbook();
            Sheet sheet = wb.createSheet("Sheet");
            Row row = sheet.createRow(0);
            for (int i = 0; i < title.length; i++) {
                sheet.setColumnWidth(i,5000);
                Cell cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            for (int i = 1; i < list.size(); i++) {
                Row rowI = sheet.createRow(i);
                for (int j = 0; j < colum.length; j++) {
                    Cell cell = rowI.createCell(j);
                    cell.setCellValue(list.get(i).get(colum[j])==null?"":list.get(i).get(colum[j]).toString());
                    //sheet1.createRow(i).createCell(j).setCellValue(list.get(i).get(colum[j])==null?"":list.get(i).get(colum[j]).toString());
                }
            }
            FileOutputStream fileOut = new FileOutputStream(path);
            wb.write(fileOut);
            fileOut.close();
            POIFSFileSystem fs = new POIFSFileSystem();
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword("123456");
            OPCPackage opc = OPCPackage.open(new File(path), PackageAccess.READ_WRITE);
            OutputStream os = enc.getDataStream(fs);
            opc.save(os);
            opc.close();
            FileOutputStream fos = new FileOutputStream(path);
            fs.writeFilesystem(fos);
            fos.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }

相關文章