ASP.NET导出Excel(含有网格)(二)

今天想写下实现该功能的另一种方式,废话不多说,直接上代码.

public static void ExportExcel(GridView gv)
        {
            //把数据导出到Excel中以备检查
            if (gv != null || gv.Rows.Count != 0)
            {

                System.IO.StringWriter swBody = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hwBody = new System.Web.UI.HtmlTextWriter(swBody);
                gv.RenderControl(hwBody);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Charset = "UTF-8";
                //System.Web.HttpContext.Current.Response.Charset = "GB2312";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.Write(swBody);
                swBody.Dispose();
                HttpContext.Current.Response.End();
            }
        }

        /// <summary>
        /// 将DataSet中的数据导出Execl
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="FileName"></param>
        /// <param name="Response"></param>
        public static void CreateExcel(DataSet ds, HttpResponse Response)
        {
            HttpResponse resp = Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
            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();
        }

以上是主要的实现导出方式。但是下面的代码是要必须注意的地方:

/// <summary>
    /// 导出Excel
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButton_export_Click(object sender, EventArgs e)
    {
        DataSet ds = BindGridView();
        ClassLibrary.pub.CreateExcel(ds, Page.Response);
    }
    /// <summary>
    /// 重写VerifyRenderingInServerForm 方法 避免报错
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
    }

后台代码中,一定注意写上面注释的“重写VerifyRenderingInServerForm 方法 避免报错”那个重写方法,另外一点,还需要在前台页面上加上一句:EnableEventValidation="false"  如下代码所示。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DayInOutDetails.aspx.cs" EnableEventValidation="false" Inherits="Finance_DayInOutDetails" %>

希望能起到抛砖引玉的作用,欢迎各位分享自己的想法。

posted @ 2012-08-25 16:11  枫上善若水  阅读(392)  评论(0编辑  收藏  举报