• 将GridView中的数据导出到EXCEL


      在后台进行数据查询操作时,我们可能会使用GridView控件进行数据展示,有时需要将GridView控件中显示的数据导出到EXCEL文件中,通过调用GridView控件的RenderContol方法将数据导出到字符流中进行输出。
      首先为GridView控件设置数据源,并进行绑定操作,然后在导出按钮添加如下点击事件代码。
    protected void btnExport_Click(object sender, EventArgs e)
    {
    Response.Clear();
    Response.AppendHeader(
    "Content-Disposition", "attachment;filename=FileName.xls");
    //设置输出流为简体中文
    Response.Charset = "GB2312";
    Response.ContentEncoding
    = System.Text.Encoding.GetEncoding("GB2312");
    //设置输出文件类型为excel文件。
    Response.ContentType = "application/ms-excel";
    StringWriter sw
    = new StringWriter();
    HtmlTextWriter htw
    = new HtmlTextWriter(sw);
    GridView1.RenderControl(htw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
    }
      现在点击导出按钮页面会报错误,“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内”。 这个需要在页面中添加对VerifyRenderingInServerForm方法的重写,就可以成功导出数据了。
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
      当我们导出的数据为数字时,比如编号或者身份证号码,发现导出的数据中,编号前面的0没了,身份证号码变成了科学计数法。这个可以在GridView的RowDataBound事件处理函数中为导出的数字列添加一个样式就可以了。
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    //第二列为身份证号码
    e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
    }
    }
      当GridView存在分页时,这时候导出数据的时候页面也会报错,“只能在执行 Render() 的过程中调用 RegisterForEventValidation;” 。这个需要在<%@ Page   %>中设置EnableEventValidation="false"就可以了。
     
  • 相关阅读:
    !clrstack未显示任何方法名
    !dumpheap参数和SOS帮助系统的一些一般信息
    WinDbg Script---显示RCW对象引用的COM对象
    为什么不能将2个调试器附加到1个进程
    什么是互操作调试(Interop-Debugging)?
    为什么托管调试与本机调试不同?
    在WinDBG中管理源代码窗口
    如何从转储文件确定 /LARGEADDRESSAWARE
    Dump文件数据存储格式(九)
    Windbg命令系列---!cpuid(CPU信息)
  • 原文地址:https://www.cnblogs.com/hnsdwhl/p/2039213.html
Copyright © 2020-2023  润新知