GridView.Columns[1].Visible = false;
GridView.Columns[2].Visible = false;
GridView.AllowPaging = false;//取消分页,便于导出所有数据,不然只能导出当前页面的几条数据
BindGrid();//数据绑定
GridView.DataBind();
//循环遍历GridView中的每一列
for (int i = 0; i < GridView.Columns.Count; i++) //设置每个单元格
{
GridView.Columns[i].ItemStyle.HorizontalAlign = HorizontalAlign.Left;
for (int j = 0; j < GridUser.Rows.Count; j++)
{
GridView.Rows[j].Cells[i].Attributes.Add ("style", "vnd.ms-excel.numberformat:@;");//**调整为文本格式**
}
}
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
这样导出的Excel如果某字段开头为0则不会被隐藏
//给导出后的Excel表命名,结合表的用途以及系统时间来命名
DateTime dt = DateTime.Now;
string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
Response.Clear();
Response.AddHeader(“Content-Disposition”, “attachment;filename=” + System.Web.HttpUtility.UrlEncode(“通讯录” + filename, System.Text.Encoding.UTF8) + “.xls”);//导出文件命名
//如果设置为"GB2312"则中文字符可能会乱码
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = “applicationshlnd.xls”;
//Response.ContentType = “application/vnd.ms-excel”;
//Response.ContentType = "vnd.ms-excel.numberformat:@ ";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView.RenderControl(oHtmlTextWriter);//Add the Panel into the output Stream.
Response.Write(oStringWriter.ToString());//Output the stream.
Response.Flush();
Response.End();