asp.net – Gridview导出到文本txt,可自定义分隔符,UTF8格式,防止文本框如繁体字乱码

有的时候数据很大,导出到excel格式很慢, 你可以先将GridView 数据导出到txt, 再将txt导入到excel做分析。

asp.net 建立一个button,名称为btnToTxt,

1.先建立一个类如EBSOBC,里面放导出txt的方法:

 /// <summary>
    /// 把datatable 导出到txt
    /// </summary>
    /// <param name="pDt">datatable</param>
    /// <param name="pPage">本页面</param>
    /// <param name="pSplit">分割符号</param>
    /// <param name="pTxtName">导出的txt名称</param>
    /// <returns></returns>
    public static void ExportToTxtUnicode(DataTable pDt, Page pPage, String pSplit,String pTxtName)
    {
        int dtRowCounts = pDt.Rows.Count;
        int dtColCounts = pDt.Columns.Count;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (dtRowCounts > 0)
        {
            int i = 0;
            for (int n = 0; n < dtRowCounts; n++)
            {
                for (int m = 0; m < dtColCounts; m++)
                {
                    sb.Append(pDt.Rows[n][m].ToString());
                    bool flag = m + 1 < pDt.Columns.Count;
                    if (flag)
                    {
                        sb.Append(pSplit);
                    }
                    else
                    { break; }
                    i++;
                }
                sb.Append("\r\n");
            }

            pPage.Response.Clear();
            pPage.Response.AddHeader("Content-Disposition", "attachment;filename=" + pTxtName + ".txt");
            pPage.Response.ContentType = "text/plain";
            pPage.Response.ContentEncoding = System.Text.Encoding.UTF8;
            pPage.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
            System.IO.StringWriter sw = new System.IO.StringWriter();
            pPage.Response.Write(sb.ToString());
            pPage.Response.End();
        }
    }

2.按钮后台cs的click事件如下:

 protected void btnToText_Click(object sender, EventArgs e)
    {
        GV_PO.AllowPaging = false;
        databind(); //自定义的查询数据,显示在gridview上
        if (GV_PO.Rows.Count > 0)
        {
            DataTable dt = new DataTable("Table1");
            //填充表头
            for (int i = 0; i < GV_PO.Rows[0].Cells.Count; i++)
            {
                dt.Columns.Add(GV_PO.HeaderRow.Cells[i].Text, typeof(String));
            }
            //填充数据
            for (int i = 0; i < GV_PO.Rows.Count; i++)
            {
                string[] data = new string[GV_PO.Rows[0].Cells.Count];
                for (int j = 0; j < GV_PO.Rows[0].Cells.Count; j++)
                {
                    data[j] = GV_PO.Rows[i].Cells[j].Text == "&nbsp;" ? "" : GV_PO.Rows[i].Cells[j].Text;
                }
                dt.Rows.Add(data);
            }

            EBSOBC.ExportToTxtUnicode(dt, this, "^^", "Report" + DateAndTime.Now.ToString("yyyyMMddhhmm"));

        }
    }

3.导出 txt后, ^^ 为分隔符,你可以将该txt放到excel中去进一步分析

 

----欢迎转载----
THE END
分享
二维码
< <上一篇
下一篇>>