简体   繁体   中英

C# code to set a Password for an Existing Excel(not for the new excel file), without any 3rd party dll's

I have a Microsoft Excel file on my desktop. How to set a password to that excel using C#? I need this because I will attach this excel and mail it to certain people.

I don't want to use any external dll's for this

Finally I was able to crack this, its a simple bit of code which resolved My issue.

I added "Microsoft Excel 16.0 Object Library" in References. Below is the code

//Namespace

using Excel = Microsoft.Office.Interop.Excel;

//Inside class declare 

private static Excel.Workbook MyBook = null;

private static Excel.Application MyApp = null;

//I have created one button in the design and on that button click event I have written the below code

        private void btn_Pwd_Click(object sender, EventArgs e)
        {
            try
            {
                string DB_PATH = "Your path to select that existing Excel file";
                MyApp = new Excel.Application();
                MyApp.Visible = false;
                MyBook = MyApp.Workbooks.Open(DB_PATH);
                MyBook.Password = "abc";
                MyBook.SaveAs("Your Path to save the copy of that excel which is password protected");
                MyBook.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {

            }


        }

This will create a copy of that Excel file and save it in a path which you specify and this copy will ask for the password to open that excel, in my above code the password is "abc"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM