Can we protect excel workbook with Password using open XML SDK?

mamta choudhary 1 Reputation point
2021-02-24T07:25:51.307+00:00

I want to password protect the excel using C#. One approach is using interop libraries, but issue with this is we need to install MS office on our Server which is not allowed in organization. What is the other approach to password protect excel using C#?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,323 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-02-25T05:21:16.8+00:00

    Hi mamtachoudhary-6642,
    You could not protect an Excel file with openxml.
    Using password protection doesn't not generate an Office Open XML file and you will get a file in binary file format.
    The Open XML SDK does not work with the binary file formats.
    One suggestion is that you use Workbook.Password property to set the password:
    Here are some similar threads you can refer to.
    How to protect document with password using C# and openxml
    Protecting Excel file created through OpenXML
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. David 146 Reputation points
    2021-04-12T02:39:49.02+00:00

    Alternatively, you may use Spire.XLS for .NET for encryption or decryption of your Excel workbooks. It is a tiny .NET Excel library and does not require MS Excel to be installed on server or end users' machines. Below is the code example for your reference.

    using Spire.Xls;
    
    namespace ProtectExcel
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load Workbook
                Workbook book = new Workbook();
                book.LoadFromFile(@"E:\Documents\VendorInfo.xlsx");
                //Protect Workbook
                book.Protect("abc-123");
                //Save to file
                book.SaveToFile("ProtectExcel.xlsx", ExcelVersion.Version2013);
            }
        }
    }
    
    0 comments No comments