Export GridView DataSet To Excel - potatoscript/csharp GitHub Wiki
STEP 1: Create a Button with an OnClick Event of ExportToExcel
<asp:Button ID="MEXCEL"
Text="Excel"
OnClick="ExportToExcel"
Style="cursor:pointer"
Width="80px"
Height="50px"
BackColor="LightGreen"
ClientIDMode="Static"
runat="server"/>
STEP 2: Button Onclick Listener Event
protected void ExportToExcel(object sender, EventArgs e)
{
//Clears all content output from the buffer stream.
Response.ClearContent();
//Adds an HTTP header to the output stream
//AppendHeader(string name, string value);
//name String - The name of the HTTP header to add to the output stream.
//value String - The string to append to the header.
//The "content-disposition" header distinguishes between files served for download and files to be displayed by the browser.
Response.AppendHeader("content-disposition", "attachment; filename = Used Machine Ratio.xls");
//Specifies the HTTP content type for the response.
//If no specified, default is text/HTML
Response.ContentType = "application/excel";
//Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.
StringWriter stringWriter = new StringWriter();
//Writes markup characters and text to an ASP.NET server control output stream.
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
//styling
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
foreach (TableCell tablecell in GridView1.HeaderRow.Cells)
{
tablecell.Style["background-color"] = "#507CD1";
tablecell.Style["border"] = "1px solid white";
tablecell.Style["text-align"] = "center";
tablecell.Style["color"] = "white";
tablecell.Style["font-size"] = "25px";
}
foreach(GridViewRow gridViewRow in GridView1.Rows)
{
gridViewRow.BackColor = System.Drawing.Color.White;
foreach(TableCell gridViewRowTableCell in gridViewRow.Cells)
{
gridViewRowTableCell.Style["background-color"] = "#EFF3FB";
gridViewRowTableCell.Style["border"] = "1px solid #060606";
gridViewRowTableCell.Style["text-align"] = "center";
gridViewRowTableCell.Style["color"] = "black";
gridViewRowTableCell.Style["font-size"] = "25px";
}
}
//Outputs server control content to a provided HtmlTextWriter object and stores tracking information about the control if tracing is enabled.
GridView1.RenderControl(htmlTextWriter);
// Writes information to an HTTP response output stream.
Response.Write(stringWriter.ToString());
// Sends all currently buffered output to the client, stops execution of the page.
Response.End();
}