asp.net2.0 导出成为Excel


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Business;
using CommonTool;
public partial class BindGridView : System.Web.UI.Page
{
    BFUser myBFUser = new BFUser();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridViewInfo();
        }
    }
    protected void BindGridViewInfo()
    {
        DataTable dt = new DataTable();
        dt = myBFUser.GetAllFlatInfo();
        this.gridviewinfomation.DataSource = dt;
        this.gridviewinfomation.DataBind();
    }
    #region 导出成为Excel
    protected void btnExcel_Click(object sender, EventArgs e)
    {
        Tools.ExportExcel(gridviewinfomation, 2, "人员总数: ");
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    #endregion




//----------------------------------------------------------------
//  <copyright file="Tools.cs" company="Saga Technologies">
//  Project: FlyOA
//  Copyright (C) Saga Technologies, 2005.  All rights reserved.
//  </copyright>
//  Creator: <Jack zhang>
//  Created Date: [12-12-2006]
//----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web;
using System.IO;
using System.Web.UI;
namespace CommonTool
{
    public class Tools
    {
        /// <summary>
        /// 导出Elcel
        /// </summary>
        /// <param name="exportTargetGridView">目标GridView</param>
        /// <param name="visibleNum">隐藏的列数</param>
        /// <param name="content">说明内容</param>
        public static void ExportExcel(GridView exportTargetGridView, int visibleNum, string content)
        {
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            HttpContext.Current.Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            for (int i = 0; i < visibleNum; i++)
            {
                exportTargetGridView.Columns[exportTargetGridView.Columns.Count - (i + 1)].Visible = false;
            }
            exportTargetGridView.RenderControl(htw);
            sw.WriteLine(content + exportTargetGridView.Rows.Count.ToString());
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }
    }
}

转自: http://bbs.51aspx.com/showtopic-146.html
posted @ 2007-06-10 19:22  海浪~~  阅读(299)  评论(0)    收藏  举报