手动GridView,但无法将内容导出为CSV文件
本文关键字:文件 CSV GridView 手动 | 更新日期: 2023-09-27 17:53:21
我创建了一个函数来获取查询字符串并在.aspx
页面中创建GridView
。这很好。我有一个出口到csv
函数,返回一个空文件。当我使用自动化工具创建SQLDataSource
和GridView
时,我使用这个函数没有问题。我认为,导出到csv
功能并没有从网页上的动态gridview
抓取数据。我看不出哪里出错了。我怀疑我的函数是坏的,我没有正确返回GridView
的信息。
protected void Page_Load(object sender, EventArgs e)
{
btnBack.Click += new EventHandler(btnBack_Click);
btnCSVDownload.Click += new EventHandler(btnCSVDownload_Click);
lblLabel.Text = "some text";
string selQuery = "SELECT * FROM Employees";
SqlSelect(selQuery);
}
public string SqlSelect(string selStatement)
{
lblSelectStatement.Text = selStatement;
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["datasource"].ConnectionString;
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = selStatement;
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = MyConnection;
DataTable MyTable = new DataTable();
SqlDataAdapter MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(MyTable);
GridView1.DataSource = MyTable.DefaultView;
GridView1.DataBind();
MyAdapter.Dispose();
MyCommand.Dispose();
MyConnection.Dispose();
return lblSelectStatement.Text;
}
protected void btnCSVDownload_Click(object sender, EventArgs e)
{
ExportToCsv(GridView1);
}
public void ExportToCsv(GridView grv)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=export.csv");
Response.Charset = "";
Response.ContentType = "application/text";
grv.AllowPaging = false;
grv.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < grv.Columns.Count; k++)
{
sb.Append(grv.Columns[k].HeaderText + ','); //add separator
}
sb.Append("'r'n"); //append new line
for (int i = 0; i < grv.Rows.Count; i++)
{
for (int k = 0; k < grv.Columns.Count; k++)
{
grv.Rows[i].Cells[k].Text = ('"' + grv.Rows[i].Cells[k].Text + '"'); //add separator
sb.Append(grv.Rows[i].Cells[k].Text + ',');
}
sb.Append("'r'n"); //append new line
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
确保你的gridview字段不是自动生成的,它们是绑定字段。