The information here is incorrect in some cases. I am reading a password protected file without having the password, as the protection is ReadOnly for the worksheets. If you have a read only password protected Excel file, you can read it without having the password. The trick is that you cannot use some of the methods that you can if the file was not proected... namly .SpecialCells(). .Net will tell you when various methods cannot be used on a protect sheet. In that case, there are other options.
I have a web service where users upload an Excel file and the app picks it up and reads the data into the database. There are half a dozen different formats and the users are inconsitent in having titles, headers, extra columns, etc. and some of them protect the worksheets so they are read-only. I had to create a reader that could read it without regard to the column location, where the header row shows up, and regardless if the worksheet was protected or not.
Here's a function I setup to capture the range of the sheet and read the values into an array. I am using this with files that are password protected and files that are not. But the key here is that I am NOT used OLEDB, as that was intended to allow you to work with the Excel application directly and not when you are using Excel to read from such as on a server. So I abandoned that very early on and went with Microsoft.Office.Interop.Excel. It has been working very nicely once I got over the initial issues with the protected and unprotected differences.
If you use this method, note that the final values are stored in an array... object[,] sheetvalues. The values must be stored in a 2d object array.
public void InitializeWorksheetArray(string startingCellId)
{
if (String.IsNullOrEmpty(startingCellId)) startingCellId = "A1";
Excel.Sheets sheets = excelApp.Worksheets;
Excel.Worksheet sheet = sheets.get_Item(_currentWorksheetIndex + 1);
var lastRow = sheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
var lastCol = sheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Column;
Excel.Range last = sheet.UsedRange[lastRow, lastCol];
Excel.Range range = sheet.get_Range(startingCellId, last);
sheetValues = range.Value2;
_rowColumnCount = sheetValues.GetLength(1);
_rowCount = sheetValues.GetLength(0);
}
You can also set the Excel file to readonly when you open it. It worked either way, but I set it just in case.
public void OpenExcelFile(string filename)
{
Filename = filename;
excelWorkbook = excelApp.Workbooks.Open(filename, Type.Missing, true);
}