[JAVA] [Note] Apply password protection to Excel sheets with NPOI

What I wanted to do

I had to take measures to easily find out if Excel was tampered with in a certain case. "Then you should put a password on the book!" I thought, and started to investigate.

Conclusion

I started looking up, but I didn't know how to password the book. ** ** However, I know how to protect the sheet, so I will keep it as a memorandum.

For Apache POI 4.1.2

When I tried to handle POI from Java, I was able to lock both Worksheet and Workbook.

filename.java


XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample");

WriteCell(sheet, 0, 0, "Hello"); //Reference article: [C#] Create and edit Excel files using NPOI

//Worksheet protection
sheet.protectSheet("password");

//Workbook protection
workbook.lockStructure();
workbook.setWorkbookPassword("password", HashAlgorithm.sha256);

//Export workbook
var out = new FileOutputStream("C:\\hogehoge.xlsx");
workbook.write(out);
workbook.close();
out.close();

When I opened the generated Excel file "hogehoge.xlsx", it was certainly locked. image.png

For NPOI 2.5.1.

The Worksheet was able to lock, but I couldn't find a way to lock the Workbook.

Sample code to protect the worksheet

It is almost the same as the case of POI.

filename.cs


var workbook = new XSSFWorkBook();
ISheet worksheet = workBook.CreateSheet("testSheet1");

worksheet.ProtectSheet("password");  //Set password for sheet
workbook.LockStructure();            //Protect workbook structure(However, no password is required)

string srcFileName = @"C:\hogehoge.xlsx";
FileStream stream = (File.Exists(srcFileName))
      ? File.OpenWrite(srcFileName)
      : File.Create(srcFileName)
);
workbook.Write(stream);

Task

It should be noted that as long as there is software that removes the protection of workbooks in the first place, even if password protection is possible, tampering cannot be completely prevented. It should be considered as a simple protection.

Referenced articles and materials

-Protect workbook for structure * After all, it ends up unsolved ...

Edit history

(2020.06.20) I wrote about encryption with FileInfo, but I deleted it because it is necessary to scrutinize the information.

Recommended Posts

[Note] Apply password protection to Excel sheets with NPOI
[Java] Points to note with Arrays.asList ()
[Note] How to get started with Rspec
Sample to create PDF from Excel with Ruby