Password protected excel using NPOI

2019-07-24 06:50发布

问题:

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.

回答1:

This is not working in 1.2.5 may work in 2.0 Try

var sheet = book.CreateSheet("StatusReport");
            sheet.ProtectSheet("Password");


回答2:

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?