In this asp.net tutorial you will learn how to export div data to excel. Sometime we may have got requirement to export the div data to excel and this tutorial is written for fulfilling that purpose. You can export data that lie within table, paragraphs etc to excel. In this tutorial i have put table inside the div and then export that div. Now let's have a look over how to do so
Export div data to excel in asp.net using Export_div_data.aspx
<form id="form1" runat="server"> <div id="divExport" runat="server"> ">Har> </form> <asp:Button
Simply in .aspx page we have a div, I give id to the div and also used its runat="server" attribute so that div can be accessed from server side, inside div we have a table that data will be exported to excel.
Export_div_data.aspx.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.IO;//Donot forget to import this namespace protected void Button1_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); divExport.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); }This code is quite simple, I m adding header for .xls file and then using StringWriter and HtmlTextWriter class I am exporting div data into excel.
Happy Coding!!!
6 comments:
divExport contains images and css applied from css files, in this case what to do?
Where are you passing the div ID to the export function? i.e. how does the function know which div contents have to be exported to excel?
My dear by using this below line of code
divExport.RenderControl(htmlWrite);
the funcion will come to know that divExport contents will be exported to excel.
Thanks!
I have a question though, How would you implement this in MVC3 using Razor(.cshtml)?
In your example, since ExpToExcel.aspx.cs and ExpToExcel.aspx are connected, we can just directly call the divID in the .cs file without any problems.
How would we do this using .cshtml files? do we pass the divID from the View(.cshtml file) to the controller(.cs file)? If so, can you give an example of how its done?
Thanks in advance.
hi!! i liked your tutorial is excellent and saved me alot of time but im having a problem im trying to export to .xlsx i tryied application/vnd.ms-excel but is not working any ideas? thanks
Hi isaac! Just for you a quick reference that can solve your problem is
I will write a post that will discuss this topic as well but if you have bit urgency then above reference can solve your problem.