web页面导出标准word/excel/txt文件

本文介绍了如何将GridView中的数据导出为Excel、Word和TXT文件。通过设置HttpResponse对象的Header和ContentType,结合HtmlTextWriter将GridView渲染成字符串,然后保存为文件并提供下载。同时,针对以0开头的字符串问题,提供了保护格式的解决方案,并讨论了在框架内导出的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近有时间把一些关于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)
    {
    }

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值