Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password protected excel using NPOI

i have a .net c# application in which im downloading one excel file on button click. the code im using is

using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;

then some codes.

HSSFWorkbook book = new HSSFWorkbook();
var sheet = book.CreateSheet("StatusReport");

some code for formatting the excel,then some code for downloading the excel.

 HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "utf-16";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MpiDischargeReport.xls"));
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            book.Write(HttpContext.Current.Response.OutputStream);
            HttpContext.Current.ApplicationInstance.CompleteRequest();

this will help me to download the excel,but i need to make that excel as a password protected one. please help.

like image 945
ManjuVijayan Avatar asked Jun 06 '26 18:06

ManjuVijayan


2 Answers

This is not working in 1.2.5 may work in 2.0 Try

var sheet = book.CreateSheet("StatusReport");
            sheet.ProtectSheet("Password");
like image 50
sudhAnsu63 Avatar answered Jun 09 '26 07:06

sudhAnsu63


NPOI is a .net clone of the POI-Java-Libary. So I looked at the POI-Documentation for the class "HSSFWorkbook":
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
As you can see there is a method called "writeProtectWorkbook" that you can use to password protect the workbook.

Also take a look at the documentation for the class "HSSFSheet":
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html
As you can see there is a method called "protectSheet" that you can use to password protect the sheet.

I never tried it out . But may it help?

like image 35
tveng Avatar answered Jun 09 '26 08:06

tveng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!