错误的写法:
if (this.GridView1.Rows.Count > 0)
{
string style = @"<style> .text { mso-number-format:\@; } </script> ";
string exportfile = "supp" + DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "");
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + exportfile + ".xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(style);
Response.Write("<META http-equiv=Content-Type content='text/html; charset=utf-8'>" + sw.ToString());
Response.End();
}
else
{
ShowMessageBox("无数据导出!");
}
此时会报出错误提示:
类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。
解决导出Excel问题 if (this.GridView1.Rows.Count > 0)
{
string style = @"<style> .text { mso-number-format:\@; } </script> ";
string exportfile = HttpUtility.UrlEncode("考核数据分析", System.Text.Encoding.UTF8) + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + System.DateTime.Now.ToString("hh-mm-ss").Replace("-", "");
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + exportfile + ".xls");
Response.ContentType = "application/excel";
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.Columns[GridView1.Columns.Count - 1].Visible = false;
GridView1.RenderControl(htw);
Response.Write(style);
Response.Write("<META http-equiv=Content-Type content='text/html; charset=gb2312'>" + sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}