DataTable導出Execl
代碼太簡單,我們直接看代碼。
復制代碼 代碼如下:
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;//不設置會有亂碼
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)
{
//這個方法不能刪除掉 導出時要用到,不然會報錯:
//類型“GridView”的控件“ctl00_ContentPlaceHolder1_GridView1”必須放在具有 runat=server 的窗體標記內
}