-1

Is it possible to use ClosedXML to open an Excel file protected with a password? And if so, how?

I tried using Interop but it's very slow.

Using Interop.Excel
Microsoft.Office.Interop.Excel.Application wb = xlApp.Workbooks.Open(Filename: "c:\TEST\MyFileProtected.xlsx", ReadOnly: true, Password: "PASSWORD");

I also tried with ClosedXML with no success

string path = openFileDialog1.FileName.ToString();

var wb = new XLWorkbook(path);
wb.Unprotect("password");

I'm getting the error

"File contains corrupted data" creating the XLWorkbook object.

user2988717
  • 127
  • 3
  • 8
  • 1
    looks like you cant: https://blogs.msdn.microsoft.com/openspecification/2009/07/17/overview-of-protected-office-open-xml-documents/ – Daniel A. White Feb 25 '19 at 21:04
  • 1
    Have you checked the [`Unprotect()`](https://github.com/ClosedXML/ClosedXML/blob/cacfb263adb8971a807fe18d2687af15f850d231/ClosedXML/Excel/XLWorkbook.cs#L1002) method? – Progman Feb 25 '19 at 21:06
  • @Progman I'm getting "File contains corrupted data" I tried this code: string path = openFileDialog1.FileName.ToString(); var wb = new XLWorkbook(path); wb.Unprotect("password"); It seams that is not possible... :( Stuck in interop loading an Excel file with 4 columns and 1000 rows in 10s or more... – user2988717 Feb 27 '19 at 10:16
  • How did you create the workbook? Can you open it with Excel without getting any errors about corrupt content? – LeonidasFett Feb 27 '19 at 13:50
  • Yes I can open it with Excel without getting any errors. Erverything it's ok with the file. The file was created in Excel 2016. I'm trying to develop in c# should I go back to VBA. Microsoft.Interop.Excel is not an option... Too Slow. – user2988717 Feb 27 '19 at 22:59

1 Answers1

3

Password protection to enable/disable the opening of a file is not supported with ClosedXML/OpenXML. See https://blogs.msdn.microsoft.com/openspecification/2009/07/17/overview-of-protected-office-open-xml-documents/

You can only lock the structure and windows of an OpenXML document and that is indeed what the wb.Protect() method does.

That said, ClosedXML supports only the legacy protection methods. Newer protection methods and password hashing algorithms, introduced in Excel 2013, are not supported yet. Refer to https://github.com/ClosedXML/ClosedXML/issues/866

Francois Botha
  • 4,520
  • 1
  • 34
  • 46