Articles → .NET → Read Password Protected Excel File In C#
Read Password Protected Excel File In C#
Click to Enlarge
Microsoft.Office.Interop.Excel.Application excelObject = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBookObject = null;
Microsoft.Office.Interop.Excel.Sheets sheetObject = null;
Microsoft.Office.Interop.Excel.Worksheet workSheetObject = null;
Microsoft.Office.Interop.Excel.Range range = null;
// Get information for the workbook
workBookObject = excelObject.Workbooks.Open("file_path", Type.Missing, Type.Missing, Type.Missing, "password_on_file", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
sheetObject = workBookObject.Worksheets;
workSheetObject = (Microsoft.Office.Interop.Excel.Worksheet) sheetObject.get_Item(1); //Get the reference of second worksheet
range = workSheetObject.UsedRange;
DataTable dt = new DataTable();
dt.Columns.Add("MemberName");
for (int row = 2; row <= range.Rows.Count; row++) {
DataRow dr = dt.NewRow();
for (int column = 1; column <= range.Columns.Count; column++) {
dr[column - 1] = (range.Cells[row, column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
}
// Dispose objects
workBookObject.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excelObject.Quit();
Marshal.ReleaseComObject(workSheetObject);
Marshal.ReleaseComObject(workBookObject);
Marshal.ReleaseComObject(excelObject);
excelObject = null;
workBookObject = null;
sheetObject = null;
workSheetObject = null;
Output
Click to Enlarge