实现在页面中的Gridview中的数据以word或excel的格式导出

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// 实现在页面中的Gridview中的数据以word或excel的格式导出
/// </summary>
public partial class GridViewByWord : System.Web.UI.Page
{
    //数据库连接的字符串,由于是写在config文件中的,只需根据索引值获取即可
    string connStr = ConfigurationManager.AppSettings["connectionstring"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            fill();
    }
    /// <summary>
    /// 将数据绑定到gridview控件上
    /// </summary>
    private void fill()
    {
        string sqlStr = "select * from Test";
        SqlConnection mycon = new SqlConnection(connStr);
        mycon.Open();
        SqlDataAdapter da = new SqlDataAdapter(sqlStr, mycon);
        DataSet ds = new DataSet();
        da.Fill(ds, "Test");
        GridView1.DataSource = ds.Tables["Test"].DefaultView;
        GridView1.DataBind();
        mycon.Close();

    }
    /// <summary>
    /// 使用下拉列表来选择要导出的格式,是word还是excel
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {   //对输入的数据进行空格压缩并转换为小写
        string str = DropDownList1.SelectedValue.ToString().Trim().ToLower();
        if (str == "excel")
        {
           OutExcelFile();
        }
        if (str == "word")
        {
            OutWordFile();
        }
    }
    //以excel格式导出数据
    private void OutExcelFile()
    {  //清空缓存中的所有输出内容
        Response.Clear();
       // 添加输出流,要输出文件的名字
        Response.AddHeader("content-disposition", "attachment;filename=ExcelFile.xls");
        //设置输出的字体
        Response.Charset = "gb2312";
        //设置输出流的类型
        Response.ContentType = "application/ms.xls";
        //将信息写入字符串中
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        //将文本或标记写入到输出流中
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        //这是对gridview分页的操作
        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        //从新绑定数据
        fill();
        //将服务器的内容输入到提供的System.Web.UI.HtmlTextWriter 对象中
        GridView1.RenderControl(htmlWrite);
        //将字符串写入HTTP相应输出流
        Response.Write(stringWrite.ToString());
        //停止该页面的执行
        Response.End();
        GridView1.AllowPaging = true;
        GridView1.AllowSorting = true;
    }
    public void OutWordFile()
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=WordFile.doc");
        Response.Charset = "gb2312";
        Response.ContentType = "application/ms.doc";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        fill();
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
        GridView1.AllowPaging = true;
        GridView1.AllowSorting = true;
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
      
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        fill();
    }
    /// <summary>
    /// 在Gridview控件的一些操作其他的也可以与此类似
    /// 只是在RowDataBound事件中稍作更改。
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //鼠标停留时更改Gridview背景色
            e.Row.Attributes.Add("onmouseover", "color=color=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
            //鼠标移走时还原Gridview背景色
            e.Row.Attributes.Add("onmouseout", "color=this.style.backgroundColor=color");
        }
    }
}

posted @ 2012-05-20 12:07  独剑  阅读(203)  评论(0)    收藏  举报