ASP.NET导出到Excel,导出的Excel带网格。。。。

这几天一直在做ASP.NET的Excel导出,试了好多方式,要么报“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内!”(解决方式:重写VerifyRenderingInServerForm()方法,该方法写在CS后台。但是该方法导出的Excel没有网格。这样不太好。)

public override void VerifyRenderingInServerForm(Control control)
    { 

    } 

  下面介绍一种可以导出网格的Excel并且不用重写方法的解决方式:

废话不多说,直接上代码。

/// <summary>
    /// 导出到Excel 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbtToExcel_Click(object sender, EventArgs e)
    {
        ToExcel();
    }
    /// <summary>
    /// 导出到Excel
    /// </summary>
    protected void ToExcel()
    {
        //新建一个Gridview,原因:避免当前窗口GridView外层没有直接跟form标签,从而避免“gridview1未包含在run='server'”的错误。
        GridView gvOrders = new GridView();
        System.IO.StringWriter sw = new System.IO.StringWriter();
        //定义页面输出格式。
        Response.Write("<meta http-equiv=Content-Type content=\"ms-excel; charset=utf-8\">");
        //定义文件名称
        string fileName = System.Web.HttpUtility.UrlEncode(Session["filename"] + DateTime.Now.ToString("_yyyyMMddHHmm"), Encoding.UTF8);
        //取得数据源
        DataSet ds = GetDataSet(Session["sqlhs2"].ToString());
        //设置Excel网格(注意XML内容,定义Sheet工作簿名称和网格线)
        if (ds.Tables[0] != null)
        {

            sw.WriteLine("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
            sw.WriteLine("<head>");
            sw.WriteLine("<!--[if gte mso 9]>");
            sw.WriteLine("<xml>");
            sw.WriteLine(" <x:ExcelWorkbook>");
            sw.WriteLine("  <x:ExcelWorksheets>");
            sw.WriteLine("   <x:ExcelWorksheet>");
            sw.WriteLine("    <x:Name>" + fileName + "</x:Name>");
            sw.WriteLine("    <x:WorksheetOptions>");
            sw.WriteLine("      <x:Print>");
            sw.WriteLine("       <x:ValidPrinterInfo />");
            sw.WriteLine("      </x:Print>");
            sw.WriteLine("    </x:WorksheetOptions>");
            sw.WriteLine("   </x:ExcelWorksheet>");
            sw.WriteLine("  </x:ExcelWorksheets>");
            sw.WriteLine("</x:ExcelWorkbook>");
            sw.WriteLine("</xml>");
            sw.WriteLine("<![endif]-->");
            sw.WriteLine("</head>");
            sw.WriteLine("<body>");
            sw.WriteLine("<table>");
            sw.WriteLine(" <tr>");
            //根据数据库表 生成列标题
            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                sw.WriteLine("  <td>" + ds.Tables[0].Columns[i]+ "</td>");
            }
            sw.WriteLine(" </tr>");
            //根据数据库表 生成列数据
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                sw.WriteLine(" <tr>");
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    sw.WriteLine("  <td>" + ds.Tables[0].Rows[i][j] + "</td>");
                }
                sw.WriteLine(" </tr>");
            }
            sw.WriteLine("</table>");
            sw.WriteLine("</body>");
            sw.WriteLine("</html>");

            
            Response.Clear();
            //应用缓存
            Response.Buffer = true;

            Response.Charset = "utf-8";
            //设置  文件的名称
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            //设置  内容格式。
            Response.ContentType = "application/ms-excel";
            //设置  输出编码
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            this.EnableViewState = false;
            
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            //不允许翻页
            gvOrders.AllowPaging = false;
            //不允许排序
            gvOrders.AllowSorting = false;
            //绑定数据源
            gvOrders.DataSource = ds.Tables[0];
            gvOrders.DataBind();
            //写入HtmlTextWriter
            gvOrders.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();
        }
    }
作者:枫上善若水
出处:http://www.cnblogs.com/xilipu31/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!
原文地址:https://www.cnblogs.com/xilipu31/p/2643442.html