Simple and practical.net DataTable export Execl
- 2020-10-23 20:54:09
- OfStack
DataTable export Execl
The code is too simple. Let's just look at the code.
protected void btnPrint_Click(object sender, EventArgs e)
{
string strPath = "MFOut" + DateTime.Now.ToString("yyyymmddhhmmssfff") + ".xls";
DataGrid dg = new DataGrid();
dg.DataSource = dtMain;
dg.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + strPath + "");
Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;// If you don't set it, there will be messy code
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
// This method cannot be deleted When exporting, it should be used, otherwise an error will be reported:
// Type" GridView "Control" ctl00_ContentPlaceHolder1_GridView1 "Must be placed in having runat=server Inside the form tag
}