直接代码:
public static void ExportExcel(GridView gv, HttpContext context)
{
gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 0); //rgb(243, 243, 243)
for (int i = 0; i < gv.Rows.Count; i++)
{
for (int j = 0; j < gv.Rows[i].Cells.Count; j++)
{
gv.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
}
HttpResponse resp = context.Response;
resp.Charset = "GB2312";
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
string fileName = "ExportData.xls";
if (string.IsNullOrEmpty(gv.ToolTip) == false) fileName = gv.ToolTip+".xls";
resp.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
resp.ContentType = "application/ms-excel";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
gv.RenderControl(hw); //输出结构
string content = "<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\">";
content += tw.ToString();
content += "</body></html>";
resp.Output.Write(content);
resp.Flush();
resp.End();
}
{
gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(255, 255, 0); //rgb(243, 243, 243)
for (int i = 0; i < gv.Rows.Count; i++)
{
for (int j = 0; j < gv.Rows[i].Cells.Count; j++)
{
gv.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
}
HttpResponse resp = context.Response;
resp.Charset = "GB2312";
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
string fileName = "ExportData.xls";
if (string.IsNullOrEmpty(gv.ToolTip) == false) fileName = gv.ToolTip+".xls";
resp.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
resp.ContentType = "application/ms-excel";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
gv.RenderControl(hw); //输出结构
string content = "<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\">";
content += tw.ToString();
content += "</body></html>";
resp.Output.Write(content);
resp.Flush();
resp.End();
}