java poi對Excel文件加密


@SuppressWarnings("deprecation")
    @Override
    public InputStream exportItemProjectExcel(List<String> ITEM_PROJECT_ID_LIST) throws Exception {

        FileInputStream inputStream = new FileInputStream(new File(this.getClass().getResource("/../../resource/分項工程.xlsx").getFile()));
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);// 讀取第-頁

        Row row;
        for (int i = 0; i < ITEM_PROJECT_ID_LIST.size(); i++) {
            row = sheet.createRow(i);
            row.createCell(0).setCellValue((String) ITEM_PROJECT_ID_LIST.get(i));
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);// 臨時存儲流到內存
        baos.flush();

        ByteArrayInputStream workbookInput = new ByteArrayInputStream(baos.toByteArray());
        // 創建POIFS文件系統 加密文件
        POIFSFileSystem fs = new POIFSFileSystem();
        EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
        Encryptor enc = info.getEncryptor();
        enc.confirmPassword("itemProject");
        // 然后把字節輸入到輸入流,然后輸入到OPC包里面
        OPCPackage opc = OPCPackage.open(workbookInput);
        OutputStream os = enc.getDataStream(fs);

        opc.save(os);
        opc.close();

        baos = new ByteArrayOutputStream();
        fs.writeFilesystem(baos);
        baos.flush();

        inputStream.close();
        workbook.close();
        baos.close();

        return new ByteArrayInputStream(baos.toByteArray());
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM