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


Posted By  -  Karan Gupta
 
Posted On  -  Friday, January 16, 2015

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250