ASP.NET将GridView中的数据导出到Excel文件中(转载)
转帖:http://hi.baidu.com/ddlb/blog/item/c4df5790ea332a89a877a477.html
GridView导出到Excel代码
protected void Btdaochu_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
//网上下一句中"utf-7"为"utf-8",会出现中文为乱码现象。
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GV.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
需要重载一下以下,否则报错:
public override void VerifyRenderingInServerForm(Control control)
{
}
将数字转换为字符串问题:
在RowDataBound事件中添加
protected void GV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
}