我創建了一個函數來獲取查詢字符串並在.aspx
頁面中創建GridView
。這工作正常。我有一個導出到csv
函數返回一個空文件。當我使用自動化工具創建SQLDataSource
和GridView
時,我毫無問題地使用了該功能。我相信導出到csv
函數不會從網頁上的動態gridview
中獲取數據。我看不出我犯了什麼錯誤。我懷疑我的功能不好,因爲我沒有正確地返回GridView
的信息。手動GridView但無法將內容導出到CSV文件
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();
}
是否需要在'ExportToCsv()'中調用'grv.DataBind()'? –
我不知道。這適用於我在.aspx中使用SQLDataSource的頁面。我也嘗試刪除它,它並沒有幫助。 – user1981897