【发布时间】:2015-11-25 01:56:18
【问题描述】:
过去 2 天我一直在试图弄清楚为什么我无法将非常简单的 gridview 导出到 Excel 文件或 CSV 文件中。当我单击导出按钮时,什么也没有发生,我没有收到任何错误。起初我尝试了一个导出到 excel 但没有工作的代码,现在我正在尝试这个导出到 csv 文件的代码,它也不起作用。有人可以帮忙吗?谢谢: 这是标记:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="GroupCategory" HeaderText="GroupCategory"
SortExpression="GroupCategory" />
<asp:BoundField DataField="TotalCount" HeaderText="TotalCount"
SortExpression="TotalCount" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
下面是代码:
public void BindData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT [GroupCategory], [TotalCount] FROM [Test] ", con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
// GV_InlineEditing.DataBind();
this.GridView1.DataBind();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
【问题讨论】:
-
看来您需要在导出前再次调用
BindData()。 -
在您的导出代码中,将
GridView1.DataBind();替换为BindData(); -
EJC,我做到了,它没有导出任何东西。当我单击按钮时,它什么也不做。我看到页面在闪烁,但没有其他内容
-
现在挖掘一些代码。