2014-06-27 17 views
-1

我試圖從SQL Server從查詢中導出csv文件。導出到csv具有對象引用未設置爲對象的實例

,我發現了錯誤對象引用不設置到對象的實例就行

foreach (DataColumn dc in dt.Columns) 
{ 
} 

這裏是我這運行的代碼。

private DataTable GetData() 
{ 
    SqlConnection sqlCon = new SqlConnection("..."); 
    SqlCommand sqlCmd = new SqlCommand(); 
    sqlCmd.CommandText = "SELECT top 10 * from products.products"; 
    sqlCmd.Connection = sqlCon; 

    sqlCon.Open(); 
    sqlCmd.ExecuteScalar(); 
    sqlCon.Close(); 
    return dt; 
} 

protected void Button3_Click(object sender, EventArgs e) 
{ 
    DataTable dt = GetData(); 

    string attachment = "attachment; filename=DataTable.xls"; 

    Response.ClearContent(); 
    Response.AddHeader("content-disposition", attachment); 
    Response.ContentType = "application/vnd.ms-excel"; 

    string tab = ""; 
    foreach (DataColumn dc in dt.Columns) 
    { 
     Response.Write(tab + dc.ColumnName); 
     tab = "\t"; 
    } 

    Response.Write("\n"); 

    foreach (DataRow dr in dt.Rows) 
    { 
     tab = ""; 

     for (int i = 0; i < dt.Columns.Count; i++) 
     { 
      Response.Write(tab + dr[i].ToString()); 
      tab = "\t"; 
     } 

     Response.Write("\n"); 
    } 

    Response.End(); 
} 

我不知道該怎麼辦。

+0

是什麼在dt.Columns?你調試過了嗎? –

+0

它編譯沒有錯誤? ** DataTable GetData()**沒有dt聲明。 ExecuteScalar返回一個...標量不表;) – EKOlog

+0

是沒有編譯錯誤 – user3784679

回答

3

你有什麼東西能夠讓你的DataTable

private DataTable GetData() 
{ 
    DataTable dt = new DataTable(); 

    SqlConnection sqlCon = new SqlConnection("..."); 
    SqlCommand sqlCmd = new SqlCommand(); 
    sqlCmd.CommandText = "SELECT top 10 * from products.products"; 
    sqlCmd.Connection = sqlCon; 

    sqlCon.Open(); 
    dt.Load(sqlCmd.ExecuteReader()); 
    sqlCon.Close(); 

    return dt; 
} 
+0

我在dt.Load(sqlCmd.ExecuteReader())上得到一個錯誤; - 你調用的對象是空的。 – user3784679

+0

DataTable dt = new DataTable()我確實在方法中錯過了:)。往上看! – Fals

+0

非常感謝! :)我會在2分鐘內讓我選擇答案。 – user3784679

0

試試這個:

private DataTable GetData() 
{ 
DataTable dt; 
     string connectionString = ConfigurationManager.ConnectionStrings["yourConnection"].ConnectionString; 
     // 
     // In a using statement, acquire the SqlConnection as a resource. 
     // 
     using (SqlConnection con = new SqlConnection(connectionString)) 
     { 
      // 
      // Open the SqlConnection. 
      // 
      con.Open(); 
      // 
      // The following code uses an SqlCommand based on the SqlConnection. 
      // 
      using (SqlCommand command = new SqlCommand("SELECT top 10 * from products.products", con)) 
      { 
       //use SqlDataAdapter to fill the dataTable 
       using (SqlDataAdapter a = new SqlDataAdapter(command)) 
       { 
        dt = new DataTable(); 
        a.Fill(dt); 
       } 

      } 
     } 
     return dt; 
    } 
相關問題