简单实用的.net DataTable导出Execl

时间:2021-05-18

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 的窗体标记内
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章