Password protected excel using NPOI - c#

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.

This is not working in 1.2.5 may work in 2.0
Try
var sheet = book.CreateSheet("StatusReport");
sheet.ProtectSheet("Password");

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?

Related

Convert asp:Table to excel format

I am able to to generate excel file from asp:table,but after generating excel file while opening file it gives warning .file you are trying to open is in a different format than specified by the file extension I have found solution to this warning from this link http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx
so i have used ClosedXML Library but while adding data to excel sheet it's accepting datable,dataset format only and i got data in string format so it's generating blank excel sheet. please check code i have tried.
LoadDetailsToTable();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
tbl_loctbl.RenderControl(hw);
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("asd");
ws.Cell(2, 1).InsertTable(sw.ToString());
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format(#"attachment;filename=newfile.xlsx"));
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
MyMemoryStream.Close();
}
HttpContext.Current.Response.End();
}
Here LoadDetailsToTable() function load data to asp table.tbl_loctbl is table id.
Unfortunately the two markups you're using are incompatible. HTML table markup in Excel is supported, but its not in OpenXML which is what your library is expecting to output.
Under the hood, Excel is expecting a valid XML file format; html, while loosely supported, isn't the native xlsx format.
There are libraries available that will convert html to openxml on the internet, however this can be solved by iterating over your dataset and actually adding cells and rows using the OpenXML SDK

Generating Excel Sheet using HtmlWriter

i am generating Excel report using string writer.i generated the excel sheet but it generats only one sheet.but i need to create sheets based on my condition.
my code is:
string filename = "DownloadMobileNoExcel.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
tw.Write("<table>");
tw.Write("<tr><td>data1</td><td>data2</td><td>data3</td><td>data4</td><td>data5</td><td>data6</td></tr>");
tw.Write("<tr><td>data1</td><td>data2</td><td>data3</td><td>data4</td><td>data5</td><td>data6</td></tr>");
tw.Write("<tr><td>data1</td><td>data2</td><td>data3</td><td>data4</td><td>data5</td><td>data6</td></tr>");
tw.Write("</table>");
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
The above Code generate single sheet but i want to create based on my condtion,how can i create sheets,i want same method which would to append the Html ,advance Thanks
it can be done using frames: you'll have to create one .html file for each tab you want in the Excel sheet.
To see how it works,
- create an Excel file with 2 sheets
- Save As... .html
- look at the html written (+ the subfolder generated containing the sheets
If you create a similar structure (using the files from the above test as templates), Excel will be able to open it.
Another approach is to create an Excel file using OpenXml, as decribed here:
How to write data on new sheet of EXCEL

Export to excel opening it

I currently have an option in my app to export to Excel. It saves the data to a file in disk.
I would like to open Excel instead and show the data. Do any of you know if this is possible and how to accomplish it?
I guess I can just open the file I'm already saving to disk, but it would be just better to not save a file to disk at all.
I am assuming you are using Interop. Just set the Application to Visible.
excelApp.Visible = true;
where
InteropExcel.Application excelApp;
Just remember to still release all the COM references so that your application does not also hold a handle to Excel. That may cause your Excel file to be read-only.
How are you currently creating your file?
If you are using the Excel engine or POI (or what ever thier abbreviation is) to create an XLS / XLSX it would just be a case of not saving the workbook and making the instance visible (as per above)?
If you are not dependant on or do not want to be dependant on Excel (i.e. using 3rd party libraries like Syncfusion to create the file) or just outputting your data in an excel readable format like CSV, then I guess you're stuck with a file-based operation...
As for a temp file being easier than an unsaved one... the data needs to be created in either instance, either simple CSV or a coded population of Excel cells, so I don't quite see what is meant by that.
Refer Below code to open excel without saving
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=DateTime.Now + ".xls");
System.Web.HttpContext.Current.Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache); // If you want the option to open the Excel file without saving than
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Gridview1.RenderControl(htmlWrite);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
System.Web.HttpContext.Current.Response.Write(style);
System.Web.HttpContext.Current.Response.Output.Write(stringWrite.ToString());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();

read/write a simple excel file using c#

I'm trying to find a simple way of writing an excel file in c#, but everything that I've found on thank you for your help.
You have two options available to you
The First is to use Interop Assemblies here is a link to some sample code on how to do that Write Data to Excel using C#
The Second option is to use OLEDB. There is some information on Stack Overflow on that here
Use epplus as mentioned above,It makes it really simple. This is the code for a spread sheet i created with it today.
using (ExcelPackage pck = new ExcelPackage())
{
//Give the worksheet a name
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Inventory as of " + DateTime.Now.ToString("MM/dd/yyyy"));
//dt is a datable that i am turning into an excel document
ws.Cells["A1"].LoadFromDataTable(dt, true);
//Format the header columns(Color,Pattern,etc.)
using (ExcelRange rng = ws.Cells["A1:AA1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//End Format the header columns
//Give the file details(ie. filename, etc.)
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Inventory Report " + DateTime.Now.ToString("MM/dd/yyyy") + ".xlsx");
//Write the file
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
pck.Save();
}
what you would need is epplus, this will help you to create 2007+ excel file
not compatible with 2003 and under
There is no really easy way depending of the version of excel file you want to write. If you want to go for xls you won't have much options than using Excel interop which would also have the dependency to have Excel installed.
The newer version offers some more options as it is just XML in the background. You can choose yourself how to create it, either yourself, some libraries or again Interop.
If you just want to display a table without any styling, there was (afair) a way to write csv file and excel can open it quite well (depending on the data types you want to use in it).

How to make a real XLS file on asp.net c#?

I have this code to extract a table to computer in a .xls file:
// I have a string which contains HTML table codes, named as excelTable
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Disposition", String.Format("Attachment;Filename=file.xls", ));
response.Buffer = true;
response.ContentEncoding = System.Text.Encoding.Default;
response.ContentType = "application/vnd.ms-excel";
response.Write(excelTable);
response.End();
And I have seen that this is not a real .xls file. I can open it in Notepad and see my standart html table codes.
Now I understand that defining ContentType is not enough. So what else can I do to generate a pure .xls or .xlsx file? Or Should I certainly use Excel Libraries like OpenXML, Interop, etc. ?
Actual XLS/XLSX data must be sent back - that is, data generated with a library (e.g EEPlus) or other suitable source.
This common hack/approach works because Excel "knows how to read HTML". It doesn't actually turn the HTML into XSL/XLSX, although it can be saved as new spreadsheet once loaded by Excel.
Changing the content type will have no effect on the data, and instead will effectively stop this approach from working: the content type is used for associating the program (i.e. Excel) which will be used to open/read the data.
So yes: to generate a real XLS/XLSX document, use a library.

Categories

Resources