将DataGrid数据输出到Excel文件
方法还是有很多的,这里主要推荐一下本人比较常用的方法,比较简单,写一下方法调用一下就好了。
要是各位大佬还有更好的方法,不妨在评论区留个言或链接,供各位技术大佬参考并使用^_^ !
导出数据关键代码:
private void Export()
{
System.Web.UI.WebControls.DataGrid dataGrid = new System.Web.UI.WebControls.DataGrid();
//循环DateGrid里的数据
for (int i = 0; i < DataGrid_Approve.Columns.Count; i++)
{
dataGrid.Columns.Add(DataGrid_Approve.Columns[i]);
}
dataGrid.AllowPaging = false;
dataGrid.AutoGenerateColumns = false;
dataGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
dataGrid.HeaderStyle.ForeColor = System.Drawing.Color.Black;
dataGrid.HeaderStyle.Font.Bold = true;
//DataTable dt = mydb.ExecSQL(ViewState["Sql"].ToString());
DataTable dt = (DataTable)Session["DataDt"];//存放要导出的数据
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["ID"] = dt.Rows[i]["ID"].ToString().Replace("<br/>", "");
}
dataGrid.DataSource = dt;
dataGrid.DataBind();
Response.Clear();
Response.Buffer = false;
Response.Charset = "UTF-8";
//存放的文件名及格式
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("****.xls", System.Text.Encoding.UTF8) + ";charset=UTF-8"); //filename="*.xls";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter();
tw.WriteLine("<html><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8'></head><body>");
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dataGrid.RenderControl(hw);
tw.WriteLine("</body></html>");
Response.Write(tw.ToString());
Response.End();
}
调用:
//点击事件
protected void Button_Out_Click(object sender, EventArgs e)
{
//调用
Export();
}
PS:效果图的话这里就不提供了,因为种种原因(懒得截图)。大家可以自己写个Demo试试,嘻嘻嘻。
内容简洁,后续更新!