将GridView导出为逗号分隔的.txt文件

时间:2016-02-29 12:04:01

标签: c# asp.net gridview

我将一些数据从GridView导出到.txt文件。 这是代码:

private void ExportGridToExcel()
{

    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    string FileName = "Export" + DateTime.Now + ".txt";
    StringBuilder strbldr = new StringBuilder();
    Response.ContentType = "application/text";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
    Response.ContentEncoding = System.Text.Encoding.Unicode;
    Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        //separting header columns text with comma operator
        strbldr.Append(GridView1.Columns[i].HeaderText + ',');
    }
    //appending new line for gridview header row
    strbldr.Append("\n");
    for (int j = 0; j < GridView1.Rows.Count; j++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //separating gridview columns with comma
            strbldr.Append(GridView1.Rows[j].Cells[k].Text + ',');
            strbldr.Replace("&lt;", "<");
            strbldr.Replace("&gt;", ">");
        }
        //appending new line for gridview rows
        strbldr.Append("\n");
    }
    GridView1.AllowPaging = false;
    Response.Output.Write(strbldr.ToString());
    Response.End();
}


protected void Button3_Click(object sender, EventArgs e)
{

    ExportGridToExcel();

}

这有效,但我需要删除导出中的所有html标记,因为上面的代码似乎将<p>标记添加到不同的列?有人知道我怎么做吗?

1 个答案:

答案 0 :(得分:0)

您可以使用基于正则表达式的实用程序功能来删除html标记:

public string RemoveHtmlTags(string source)
{
    return Regex.Replace(source, "<.*?>", "");
}

这将替换所有标签,例如&#34;&lt; b&gt;&#34;或&#34;&lt; span /&gt;&#34;用空字符串。