tonirush
tonirush

Reputation: 430

Open EXCEL (.xlsx) with password in C#

I try to open password protected .xlsx files (Excel 2007 format) without typing the password manually. I have installed Excel 2003 and the Microsoft Office Compatibility Pack that converts the file when opening.

The following code works, but it prompt for the password.

Microsoft.Office.Interop.Excel.Application ExcelApp;
Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook;
ExcelApp = new Microsoft.Office.Interop.Excel.Application();           
Object pwd = "xxx";
Object MissingValue = System.Reflection.Missing.Value;
ExcelWorkbook = ExcelApp.Workbooks.Open("C:\\temp\\test.xlsx",MissingValue, MissingValue, MissingValue,pwd);

If I use the same code to open a .xls File (Excel 2003), it works without prompting for the password. Opening .xlsx files without password protection also works fine.

How is it possible to open password protected .xlsx files without prompting for the password with Excel 2003 and the Microsoft Office Compatibility Pack?

The trick from a similar problem changing the readonly argument (3rd) to true

ExcelWorkbook = ExcelApp.Workbooks.Open("C:\\temp\\test.xlsx",MissingValue, true, MissingValue,pwd);

does not work here.

Upvotes: 5

Views: 27162

Answers (2)

NoumanQ
NoumanQ

Reputation: 337

The Answer by @J1mm1995 works when trying to open files as readonly, and fails to open some excel files when you want to open the excel file for modification(ReadOnly is set to false).

I understood that this was because the Workbooks.Open() method also expected you to specify the WritePassword. The following code worked for me:

var WFile = new Excel.Application();
Excel.Workbook Wbook = WFile.Workbooks.Open(path,  ReadOnly: false, Password: "mypassword", WriteResPassword: "mypassword");

Upvotes: 0

J1mm1995
J1mm1995

Reputation: 131

This may be late, but for any future person with Interop, for me it worked like this:

To open to write

var WFile = new Excel.Application();
Excel.Workbook Wbook = WFile.Workbooks.Open("myFilepath", ReadOnly: false, Password: "mypassword");

To open as read-only

var WFile = new Excel.Application();
Excel.Workbook Wbook = WFile.Workbooks.Open("myFilepath", ReadOnly: true, Password: "mypassword");

Upvotes: 13

Related Questions