博客园  :: 联系 :: 管理

【转】Web页面导出标准的Excel/Word/txt的代码实现

Posted on 2011-01-25 12:36  独孤雁  阅读(430)  评论(0编辑  收藏  举报

最近有时间把一些关于GridView集合里的数据导出到Excel或Word文件的代码实现。为了方便以后查阅和学习。

1.导出Excel:

    public void Export()
    {

        string FileName="文件名称";
        System.Web.HttpResponse httpResponse = Page.Response;

        httpResponse.AppendHeader("Content-Disposition", "attachment;filename="+     HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));         httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        httpResponse.ContentType = "application/ms-excel";
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

        this.GridView_selec.AllowPaging = false;
        if (ViewState["ds"] != null)
        {
            GridView_selec.DataSource = ViewState["ds"];
            GridView_selec.DataBind();

            if (GridView_selec.Rows.Count > 0)
            {

                if (GridView_selec.HeaderRow != null)
                {
                    this.GridView_selec.HeaderRow.Cells.RemoveAt(GridView_selec.HeaderRow.Cells.Count - 1);
                    this.GridView_selec.HeaderRow.Cells.RemoveAt(GridView_selec.HeaderRow.Cells.Count - 1);
                    for (int i = 0; i < GridView_selec.Rows.Count; i++)
                    {
                        GridView_selec.Rows[i].Cells.RemoveAt(GridView_selec.Rows[i].Cells.Count - 1);
                        GridView_selec.Rows[i].Cells.RemoveAt(GridView_selec.Rows[i].Cells.Count - 1);
                    }

                }
            }
        }

        GridView_selec.RenderControl(hw);

        string filePath = page.Server.MapPath("..") + "\\Temp\\" + FileName;
        System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
        sw.Write(tw.ToString());
        sw.Close();

        DownFile(httpResponse, FileName, filePath);

        httpResponse.End();

        GridView_selec.AllowPaging = true;

        GridView_selec.DataSource = ViewState["ds"];
        GridView_selec.DataBind();
    }
    private static bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath)
    {
        try
        {
            Response.ContentType = "application/octet-stream";

            Response.AppendHeader("Content-Disposition", "attachment;filename=" +
            HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
            System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
            long fLen = fs.Length;
            int size = 102400;
            byte[] readData = new byte[size];//指定缓冲区的大小
            if (size > fLen) size = Convert.ToInt32(fLen);
            long fPos = 0;
            bool isEnd = false;
            while (!isEnd)
            {
                if ((fPos + size) > fLen)
                {
                    size = Convert.ToInt32(fLen - fPos);
                    readData = new byte[size];
                    isEnd = true;
                }
                fs.Read(readData, 0, size);
                Response.BinaryWrite(readData);
                fPos += size;
            }
            fs.Close();
            System.IO.File.Delete(fullPath);
            return true;
        }
        catch
        {
            return false;
        }
    }

 

2.导出Word:

把以下代码修改一下,便可以使用:httpResponse.ContentType = "application/ms-excel";

改为:httpResponse.ContentType = "application/ms-word";

 

3.导出txt纯文本格式:

public void ExportTxt()
    {
        string fileName = "temp";
        Response.Clear();
        Response.Buffer = false;
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(fileName) + ".txt");
        Response.ContentType = "text/plain";
        this.EnableViewState = false;

        string str = "";

        //需要把一个数据集合迭代,然后存入字符串变量
        if (ViewState["ds"] != null)
        {
            DataSet ds = (DataSet)ViewState["ds"];
            for (int m = 0; m < ds.Tables[0].Columns.Count; m++)
            {
                str += ds.Tables[0].Columns[m].ColumnName + "\t";
            }

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    str += ds.Tables[0].Rows[i][j].ToString() + "\t";
                }
                str += "\r\n";
            }
        }

        Response.Write(str);
        Response.End();

    }

 

最后提示:如果导出数据有以0开头的字符串,需要做如下设置
    protected void GridView_selec_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            //这里GridView1的第0列是需要保护的字符串
            e.Row.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

        }
    }

如果导出数据的页面放在母版页里或嵌套在其他框架之下,需要重写下面的方法

导出Excel时重写方法

    public override void VerifyRenderingInServerForm(Control control)
    {
    }

注:部分代码网上搜索而得