The example in this article describes how ASP.net uses the GridView to export Excel implementations. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
<summary>
Export DataTable data to Excel, which automatically returns a downloadable file stream after calling this method
</summary>
<param name= "Dtdata" > Data source to export </param>
public static void Datatable1excel (System.Data.DataTable dtdata)
{
System.Web.UI.WebControls.GridView gvexport = null;
Current Conversation
System.Web.HttpContext curcontext = System.Web.HttpContext.Current;
IO is used to export and return Excel files
System.IO.StringWriter strwriter = null;
System.Web.UI.HtmlTextWriter htmlwriter = null;
if (dtdata!= null)
{
Set encoding and attachment formats
CurContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("gb2312");
CurContext.Response.Charset = "Utf-8";
Export Excel Files
Strwriter = new System.IO.StringWriter ();
HTMLWriter = new System.Web.UI.HtmlTextWriter (strwriter);
In order to resolve the possibility of paging in Gvdata, a GridView without pagination is redefined
Gvexport = new System.Web.UI.WebControls.GridView ();
Gvexport.datasource = Dtdata.defaultview;
Gvexport.allowpaging = false;
Gvexport.databind ();
Back to Client
Gvexport.rendercontrol (HTMLWriter);
CurContext.Response.Write ("<meta http-equiv=\" content-type\ "content=\" text/html; charset=gb2312\ "/>" + Strwriter.tostring ());
CurContext.Response.End ();
}
}
<summary>
Direct Output Excel
</summary>
<param name= "Dtdata" ></param>
public static void Datatable2excel (System.Data.DataTable dtdata)
{
System.Web.UI.WebControls.DataGrid dgexport = null;
Current Conversation
System.Web.HttpContext curcontext = System.Web.HttpContext.Current;
IO is used to export and return Excel files
System.IO.StringWriter strwriter = null;
System.Web.UI.HtmlTextWriter htmlwriter = null;
if (dtdata!= null)
{
Set encoding and attachment formats
CurContext.Response.ContentType = "application/vnd.ms-excel";
CurContext.Response.ContentEncoding =system.text.encoding.utf8;
CurContext.Response.Charset = "";
Export Excel Files
Strwriter = new System.IO.StringWriter ();
HTMLWriter = new System.Web.UI.HtmlTextWriter (strwriter);
To address possible paging in dgdata, you need to redefine a DataGrid that has no paging
Dgexport = new System.Web.UI.WebControls.DataGrid ();
Dgexport.datasource = Dtdata.defaultview;
Dgexport.allowpaging = false;
Dgexport.databind ();
Back to Client
Dgexport.rendercontrol (HTMLWriter);
CurContext.Response.Write (Strwriter.tostring ());
CurContext.Response.End ();
}
}
I hope this article will help you with the ASP.net program design.