GridView导出Excel的代码如下:
if (this.GridView1.Rows.Count != 0)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); //这里是用日期做名称
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentType = "application/excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
this.GridView1.AllowPaging = false; //GridView不启用分页
GridView1.RenderControl(htmlWrite);
HttpContext.Current.Response.Write(stringWrite.ToString());
}
如果你的 GridView 中有 【身份证号】 那你就要注意喽!将身份证号那一列设置为以下这种格式,就OK拉!
for (int i = 1; i <= GridView1.Rows.Count; i++)
{
GridView1.Rows[i - 1].Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
GridView1.Rows[i - 1].Cells[18].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
我自己写的
private void ExportDataGrid(string FileType, string FileName)
{
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
mydiv.RenderControl(hw);
//用Repeater控件中的RenderControl()函数
Response.Write(tw.ToString());
Response.End();
}
//protected void printzjs_Click(object sender, EventArgs e)
//{
// this.Repeater2.DataSource = new zjsUserService().GetTable("", "where Audit=1 ", " order by ID asc");
// this.Repeater2.DataBind();
// ExportDataGrid("application/ms-word", "zjslist.xls"); //调用导出Word函数
//}
protected void printzjs_Click(object sender, EventArgs e)
{
this.GridView1.DataSource = new zjsUserService().GetTable("", "where Audit=1 ", " order by ID asc");
this.GridView1.DataBind();
for (int i = 1; i <= GridView1.Rows.Count; i++)
{
GridView1.Rows[i - 1].Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
ExportDataGrid("application/ms-word", "zjslist.xls"); //调用导出Word函数
}