Search code examples
javagrailsgroovyapache-poi

writing excel file with encryption in grails


I have written a logic to download file in grails. For writing xls file i'm using ApachePOI. I wants to encrypt file with password and data should be encrypted after download completed. I have gone through ApachePOI encryption doc(https://poi.apache.org/encryption.html). but I didn't get any relevant information.


Solution

  • I managed to solve above problem. Insted of ".xls", now using ".xlsx". Dummy solution is as follow:

    def encryptedFile(){
    String fileName = "${name_of_xlsx_file}.xlsx"
    response.setContentType('application/vnd.ms-excel')
    response.setHeader("Content-disposition", "attachment; filename=${fileName}")
    //Biff8EncryptionKey.setCurrentUserPassword("****");
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("sheet_no_1");
    XSSFRow rowhead = sheet.createRow((short) 0)
    rowhead.createCell(0).setCellValue("Created On")
    rowhead.createCell(1).setCellValue("Email")
    rowhead.createCell(2).setCellValue("First Name")
    rowhead.createCell(3).setCellValue("Last Name")
    rowhead.createCell(4).setCellValue("Send Newsletter")
    rowhead.createCell(5).setCellValue("Code")
    {
     // worksheet writing logic goes here.....
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    workbook.write(byteArrayOutputStream);
    byteArrayOutputStream.close();
    ByteArrayInputStream byteArrayInputStream = new 
    ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    String password="password_to_set"
    encrypt(byteArrayInputStream, response.outputStream, password);
    byteArrayInputStream.close();   
    }   
    public static void encrypt(InputStream input, OutputStream output, String password)
    throws IOException {
    try {
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword(password)
    OPCPackage opc = OPCPackage.open(input);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();
    fs.writeFilesystem(output);
    output.close();
    } catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
    } catch (InvalidFormatException e) {
    throw new RuntimeException(e);
    }
    }