手动GridView但无法将内容导出到CSV文件

时间:2013-01-15 22:57:42

标签: c# .net function gridview

我创建了一个函数来获取查询字符串并在GridView页面中创建.aspx。这很好用。我有一个导出到csv函数返回一个空文件。当我使用自动化工具创建SQLDataSourceGridView时,我使用此功能时没有问题。我认为导出到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();
}

1 个答案:

答案 0 :(得分:0)

确保您的gridview字段不是自动生成的,并且它们是绑定字段。