Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open EXCEL (.xlsx) with password in C#

Tags:

c#

excel

vsto

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.

like image 524
tonirush Avatar asked Feb 26 '16 08:02

tonirush


People also ask

How do I open an XLSX file with password?

Open the MS Excel file by double click on it. If you have protected the file with a password, then a pop up will appear on the screen. The pop up will indicate you that your Excel file is password protected and you will need a password to open it. Just enter the password to unlock the password-protected Excel file.

How do you unlock an Excel spreadsheet with a password?

On the Review tab, click Protect Sheet or Protect Workbook. Click Unprotect Sheet or Protect Workbook and enter the password. Clicking Unprotect Sheet automatically removes the password from the sheet. To add a new password, click Protect Sheet or Protect Workbook, type and confirm the new password, and then click OK.

Can I Encrypt Excel file with password?

Click Review > Protect Workbook. Note: The Windows option is available only in Excel 2007, Excel 2010, Excel for Mac 2011, and Excel 2016 for Mac. Select the Windows option if you want to prevent users from moving, resizing, or closing the workbook window, or hide/unhide windows. Enter a password in the Password box.


1 Answers

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");
like image 140
J1mm1995 Avatar answered Sep 27 '22 23:09

J1mm1995