Troubleshooting the encryption of XSSFWorkbook in styles.xml during the save process with Apache POI v3.16

Currently, I am using Apache POI 3.16 with Java version 1.7.0-251 (Unix).

I found inspiration in an example provided by @Aniruddh Chandegra on how to create and edit a password-protected excel sheet using Apache POI 3.14 (Link here).

[EDIT - Below is the code snippet of what I'm doing: creating XSSFWorkbook, extracting data, and then encrypting it]

Note: The code is running on server-side Javascript with Mozilla Rhino v1.7R3, which supports ECMAScript Edition 5 and some features from Mozilla Javascript 1.8.

var wb = new XSSFWorkbook();
var createHelper = wb.getCreationHelper();

// Filling in rows/cells
addMostRecentSheet(wb);

var filepath = [hidden]
var fileOut = new java.io.FileOutputStream(filepath);
wb.write(fileOut);
fileOut.close();

var fs = new POIFSFileSystem();

var info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);
var enc = info.getEncryptor();
enc.confirmPassword("password");

var os = enc.getDataStream(fs);
opc.saveImpl(os);  
opc.close();

var fos = new java.io.FileOutputStream(filepath);
fs.writeFilesystem(fos);
fos.close();  

I managed to save a password-protected xlsx file but had to remove Date column styling.

Here's the code to format cells into the Date cell type:

function createDateCell(row, colNum, value)
{
    var cell;
    if (value)
    {
        cell = row.createCell(colNum);
        cell.setCellValue(value);
        var cellStyle = wb.createCellStyle();
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
        cell.setCellStyle(cellStyle)
    }
    else
    {
        cell = row.createCell(colNum, Cell.CELL_TYPE_BLANK);
    }
    return cell;
}

However, when running the program, I consistently encounter this error. Is there a workaround to retain the Date column type?

org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: 
Fail to save: an error occurs while saving the package : 
The part /xl/styles.xml failed to be saved in the stream with marshaller
org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller@216fb8e 

Answer №1

In order to format cells as dates, follow these steps:

var wb = new XSSFWorkbook();
var createHelper = wb.getCreationHelper();
var dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));

You only have to do this setup once. By defining the cellStyle initially, you are only updating /xl/styles.xml file a single time.

When entering data into cells, just apply the dateStyle like so:

createDateCell(row, colNum++, tables.SHE_SOUTH.DOB.value, dateStyle);

The createDateCell function includes the cellStyle:

function createDateCell(row,colNum,value, cellStyle){
    var cell;
    if(value){
        cell = row.createCell(colNum, Cell.CELL_TYPE_NUMERIC);
        cell.setCellValue(value);
        cell.setCellStyle(cellStyle);
    }
    else
    {
        cell = row.createCell(colNum, Cell.CELL_TYPE_BLANK);
    }
    return cell;
}

This method prevents bloating of the /xl/styles.xml file, allowing for workbook encryption. This technique is highly effective, giving credit to Axel Richter

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

:after pseudo class not functioning properly when included in stylesheet and imported into React

I am currently utilizing style-loader and css-loader for importing stylesheets in a react project: require('../css/gallery/style.css'); Everything in the stylesheet is working smoothly, except for one specific rule: .grid::after { content: ...

Ensure that the page is fully loaded before proceeding with the redirection

I have a webpage that currently performs a small task before redirecting to a third-party site. The redirection is initiated by using Response.Redirect(); Now, I am looking to integrate another function using JavaScript this time. To add the JavaScript ...

Is it possible for jQuery to detect if an email was sent from the client's email account?

I am working towards a feature on my website where users fill out specific fields and then click "send email" to activate their email platform via "mailTo", with the email pre-populated for easy sending. The challenge lies in confirming if the user actuall ...

Generate Table Rows with Javascript - produces an excess of cells...>>

I am currently in the process of dynamically creating a table, but I am facing an issue with the number of cells being added. The table I am trying to create has a total of 8 columns (Monday to Friday and a total column at the end). You can view my progr ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

There was an error in the syntax: JSON parsing error, an unrecognized token '<'

Having trouble with a syntax error: JSON parse error due to an unrecognized token '<'. One page is functioning properly with the same code, while another is displaying this error. I am unable to identify my mistake. Front-end code: const getd ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

What is the best way to pass an input value into a function when a form is submitted in Angular 6?

When I press enter, my code works perfectly and the performSearch function runs successfully. However, when I attempt to run the function by clicking the submit button, I encounter the following error: Error: cannot read property of undefined This is m ...

Small jumps occur when implementing the scrollTop jquery animation

I've encountered an issue with the scrollTop jquery animation that I can't seem to resolve. It seems to micro-jump right before the animation, especially when there is heavier content. I'm puzzled as to why this is happening... Here's ...

Transferring a header across a series of interconnected services

I have a script that calls two services, combines their results, and displays them to the user. The services are: Service 1 (hello) and Service 2 (world), resulting in "Hello world". I want to include an ID in the headers to track the route of the calls. ...

Utilize a single function to toggle the visibility of passwords for multiple fields upon clicking

Is there a way to optimize the function used to hide passwords for multiple fields when clicked? Instead of having separate functions for each field, I would like to have one function that is only active on the clicked button. For example, if the toggle ...

Tips for effectively integrating data from MongoDB into a React application

Currently, I am utilizing two components to extract data from the database. One component is used to loop through the data entries, while the second one is dedicated to accessing and displaying the details for each entry. Within my database, there is a fie ...

How can values be passed to child components in Vue when using component tags for dynamically switching components?

Is there a way to pass values to children components in Vue when using the component tag? It appears that I am unable to pass values to a child component using the component tag without using v-if: <component :is="showNow"></component> ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

Firebase Operation Not Supported Error in next.js (auth/operation-not-supported-in-this-environment)

After successfully deploying a Next.js app hosted on Vercel with Firebase authentication that functions properly for users, I encountered a mysterious error during the "npm run build" phase: FirebaseError: Firebase: Error (auth/operation-not-supported-in ...

Exploring the capabilities of the Vuejs EventBus

I've been struggling with this issue for quite some time now, but I just can't seem to get it right! I've looked at various examples online, but none of them seem to solve the problem. Every time I run my test, I keep getting this error: Ex ...

Alert: Next.js 13 console error detected

Currently, I am utilizing Next js 13 for the development of a website. However, I have encountered this warning in the console: The resource http://localhost:3000/_next/static/chunks/polyfills.js was preloaded using link preload but not used within a few s ...

The jQuery code functions properly only if it is inserted directly into the console

I'm facing an issue with a Mobile Font markup switch function. It works fine in the console, but not when I run it within a document ready function or call the function separately. It's strange that I have to paste the code directly into the con ...

Alternative to updating object coordinates in Fabric JS 1.7.9 - seeking solutions for migration challenges

Update: JSFiddle: https://jsfiddle.net/Qanary/915fg6ka/ I am currently working on implementing the `curveText` function (found at the bottom of this post). It was functioning properly with `fabric.js 1.2.0`, but after updating to `fabric.js 1.7.9`, I not ...