Convert asp:Table to excel format - c#

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

Related

Change the version of excel attached file in email using c#

I am trying to send the email with attached excel xlsx file.
I can download the attached excel file on my laptop, and galaxy phone but I can't download it on the iphone.
So I want to lower the excel version using https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat.aspx.
For this, when I change the code to
wb.SaveAs("filename.xls", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8);
It says SaveAs does not have a parameter for FileFormat.
They said they need 2 parameters. (Stream stream, bool validate)
So I have no idea where can I put those fileformat to change the fileformat from xlsx to xls on my code.
//set DataTable Name of Excel Sheet
data.TableName = "E_Data";
//Create a New Workbook
using (XLWorkbook wb = new XLWorkbook())
{
//Add the DataTable as Excel Workhseet
wb.Worksheets.Add(data);
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Excel Workbook to MemoryStream
wb.SaveAs(memoryStream);
//Convert MemoryStream to Byte array
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
...
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
}
}
You are using ClosedXml Libary, ClosedXML doesn't support the older format, hence you can not save your file as xls.
if you can use Microsoft.Office.Interop.Excel namespace (i.e office is installed on server \ pc) it will be very easy, create your excel file using Interop.Excel and than save it
using SaveAs() method for example: wb.SaveAs(c:\\memoryStream.xls,XlFileFormat.xlOpenXMLWorkbook)

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();

Creating an Excel file with multiple sheets

Do you make this code to create an Excel spreadsheet with two tabs? This only does one presently.
string attachment = string.Empty;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
frm.Attributes["runat"] = "server";
attachment = "attachment; filename=MyFile.xls";
GridView1.Parent.Controls.Add(frm);
frm.Controls.Add(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
I'm pretty sure you can't do it unless you're using MS Office Interop assemblies for Excel or some library such as Open XML SDK.
Note that you are not creating genuine excel file with the method above but just tricking excel into opening data you sent as if those are genuine excel files. This is why you'll most probably get warning message when opening this in MS Excel.
There appears to a Microsoft Article detailing how to export data from an application into Excel, although it's a bit dated (2005) http://support.microsoft.com/kb/306023
It appears to cover multiple worksheets, although I've never used these methods myself.

Code Upgrade - Export to Excel 2007 and up

I have some default functionality in a C# asp.net web application that will export a gridview to an excel file. This code is working great in Excel 2007, however it will not open in 2010. I need to upgrade this code to work in both, or find a new solution. Any help would be great.
Current code:
gvReport.Style.Add("font-size", "1em");
Response.Clear();
string attachment = "attachment; filename=FileName.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvReport.GridLines = GridLines.Horizontal;
gvReport.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Use EPPlus and export data to Excel, I presume that gvReport iz GridView control, so use data that you bind to that GridView and export it with EPPlus.
It's pretty easy, here you can find example of ashx handler that will return excel file created from DataTable :
https://stackoverflow.com/a/9569827/351383

Categories

Resources