为避免出错的准备
出错1:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
解决方案:在后台文件中重载VerifyRenderingInServerForm方法,如:
public override void VerifyRenderingInServerForm(Control control)
{
}
出错2:只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render();
解决方案:在源中,添加红色部分<%@ Page Language="C#" EnableEventValidation = "false"CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>
另外,在使用时,把GRIDVIEW获取数据的方法getdata()写成public DataSet getdata(),return 一个DS,
调用事件里,实例化一个DATASET, 让它值等于DS,
例:事件{ DataSet ds = getdata();
CreateExcel(ds , "aa.xls");} 或者把数据绑定与获取DATASET分开
方法1简单:
public void ToExcel()//整个GRIDVIEW导出到EXCEL
{
string filename="网银终端" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
string style = @"<style> .text { mso-number-format:\@; } </script> "; //解决第一位字符为零时不显示的问题
this.GridView1.AllowPaging = false;
this.GridView1.DataBind();
filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);//解决导出EXCEL时乱码的问题
Response.ClearContent;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
System.IO.StringWriter sw = new System.IO.StringWriter();//定义一个字符串写入对象
HtmlTextWriter htw = new HtmlTextWriter(sw);//将html写到服务器控件输出流
this.GridView1.RenderControl(htw);//将控件GRIDVIEW中的内容输出到HTW中
Response.Write(style);
Response.Write(sw);
Response.End();
this.GridView1.AllowPaging = true;
}
方法2:粘帖直接用
public void CreateExcel(DataSet ds, string FileName)//整个GRIDVIEW导出到EXCEL.xls
{
FileName=HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);//解决导出时文件名汉字显示乱码的问题
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
string colHeaders = "", ls_item = "";
//定义表对象与行对象,同时用DataSet对其值进行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
ls_item += row[i].ToString() + "\n";
}
else
{
ls_item += row[i].ToString() + "\t";
}
}
resp.Write(ls_item);
ls_item = "";
}
resp.End();
}