C# example snippet to open excel file with password

.xls, .xlsx

namespace : Microsoft.Office.Interop.Excel

Open an existing excel with master password with sharp code, open as read-only after passing the value and at the end apply Visible.

Sample code to open excel file with master password

code to open excel with password

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace Excel_Password
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = @"D:\",
                Title = "Browse Text Files",
                CheckFileExists = true,
                CheckPathExists = true,
                DefaultExt = "Excel",
                Filter = "Excel files (*.xlsx)|*.xlsx",
                FilterIndex = 2,
                RestoreDirectory = true,
                ReadOnlyChecked = true,
                ShowReadOnly = true
            };
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = openFileDialog1.FileName;
            }  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var WFile = new Excel.Application();
                Object Missing = System.Reflection.Missing.Value;     

                Excel.Workbook ExcelWorkbook1 = WFile.Workbooks.Open(textBox2.Text, Missing, ReadOnly: true, Password: textBox1.Text);

                WFile.Visible = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}