2016-02-29 100 views
0

我正在將一些數據從GridView導出爲.txt文件。 這是代碼:將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>標籤添加到不同的列?有人知道我能做到這一點嗎?

+0

你不能使用Replace函數並用空白替換HTML嗎? strbldr.Replace(「HTML」,「」); – Computer

回答

0

你可以使用基於正則表達式的效用函數刪除HTML標籤:

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

這將空字符串替換所有的標籤,如「<b>」或「<跨度/ >」。

相關問題