Monday, December 21, 2009

How to password protect an excel file in C#

If we need to protect an excel document with a password by some coding how will we do that? We may require to protect a report by some password after exporting it to MS Excel format. I'm going to demonstrate this by a Console Application with Visual C# code.

First create a console application and add a reference Microsoft.Office.Interop.Excel to it and just write the following piece of code. I've a standard excel file called "Test.xls".

Code:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace MyConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string filePath = @"c:\Test.xls";
Application application = new Application();
try
{
Workbook myWorkBook = application.Workbooks.Open(filePath,
Missing.Value,
false,
5,
Missing.Value,
Missing.Value,
Missing.Value,
XlPlatform.xlWindows,
Missing.Value,
false,
false,
Missing.Value,
Missing.Value,
Missing.Value,
Missing.Value);

myWorkBook.Password = "koushik";
myWorkBook.Close(true, @"c:\Test2.xls", null);
Marshal.ReleaseComObject(myWorkBook);
}
catch (Exception ex)
{
application.Quit();
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}