2013-01-15 42 views
1

我創建了一個函數來獲取查詢字符串並在.aspx頁面中創建GridView。這工作正常。我有一個導出到csv函數返回一個空文件。當我使用自動化工具創建SQLDataSourceGridView時,我毫無問題地使用了該功能。我相信導出到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(); 
} 
+0

是否需要在'ExportToCsv()'中調用'grv.DataBind()'? –

+0

我不知道。這適用於我在.aspx中使用SQLDataSource的頁面。我也嘗試刪除它,它並沒有幫助。 – user1981897

回答

0

請確保您的gridview字段不是自動生成的,並且它們是綁定字段。

+0

大家的看法在這裏都是通過聲望來尊重的,你的回答質量很低,注意提供細節,代碼或者閱讀[FAQ](http://stackoverflow.com/faq) –

+0

有沒有辦法導出爲CSV使用自動生成的列? – user1981897

+0

從我的經驗來看,沒有。我試圖尋找一種方法來做到這一點,但不得不將我的列定義爲綁定字段才能使其工作 –