【发布时间】:2020-06-29 14:33:56
【问题描述】:
当我导出我的 gridview 数据时,文本文件的顶部和底部似乎有一些随机的 HTML 代码。我删除了一些我认为可能是问题的代码,但没有任何效果。我根本不知道这个 HTML 是从哪里来的。这是我的c#导出方法
protected void ExportTextFile(object sender, EventArgs e) {
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "CreditFile.txt"));
Response.ContentType = "text/plain";
StringWriter sw = new StringWriter(); //need
HtmlTextWriter htw = new HtmlTextWriter(sw); //need
GridView4.AllowPaging = false; //okay
GridView4.HeaderRow.Style.Add("background-color", "#FFFFFF"); //okay
for (int a = 0; a < GridView4.HeaderRow.Cells.Count; a++) //okay
{
GridView4.HeaderRow.Cells[a].Style.Add("background-color", "#507CD1"); //okay
}
int j = 1;
foreach(GridViewRow gvrow in GridView4.Rows) //okay
{
gvrow.BackColor = Color.White;
if (j <= GridView4.Rows.Count) {
if (j % 2 != 0) {
for (int k = 0; k < gvrow.Cells.Count; k++) {
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
GridView4.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
这是显示在顶部的 HTML
<div>
<table cellspacing="0" cellpadding="3" rules="rows" id="GridView4" style="background-color:White;border-color:#E7E7FF;border-width:1px;border-style:None;border-collapse:collapse;">
<tr style="color:#F7F7F7;background-color:#4A3C8C;font-weight:bold;background-color:#FFFFFF;">
<th scope="col" style="background-color:#507CD1;">AppID</th>
<th scope="col" style="background-color:#507CD1;">Credit File</th>
<th scope="col" style="background-color:#507CD1;">CreationDate</th>
</tr>
<tr style="color:#4A3C8C;background-color:White;">
<td align="left" style="background-color:#EFF3FB;">1017</td>
<td align="left" style="background-color:#EFF3FB;">
<div style="width: 100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
<span id="GridView4_Label1_0">
和底部
</div>
</td>
<td align="left" style="background-color:#EFF3FB;">11/17/2016</td>
</tr>
<tr style="color:#4A3C8C;background-color:White;">
<td align="left">1017</td>
<td align="left">
<div style="width: 100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
<span id="GridView4_Label1_1">
【问题讨论】:
-
但是....这就是您的代码明确执行的操作。它使用
HtmlTextWriter创建一个 HTML 文件,其中包含一个从 GridView 生成的表格,其样式在其余代码中明确指定。如果有的话,内容类型应该是 HTML,而不是文本。你想生成什么? -
当我导出 gridview 时,我想将其导出为文本文件,它正在执行此操作,但是如何避免使用 HtmlTextWriter 而只导出 gridview 中的数据?
-
以什么形式导出?此外,网格视图没有数据。它使用列表、数据表等容器中的数据来生成 HTML 表。如果您想创建一个文本文件,只需创建一个文本文件,例如使用
File.CreateText并使用例如WriteLine写入它以写出单个元素或数据行。或者使用AppendLine和AppendFormat等StringBuilder的方法添加行,然后将字符串发送给客户端