2010-07-18 32 views

回答

1

沒有什麼內置的,但它是相當直接的做你自己。

// Create the CSV file to which grid data will be exported. 
StreamWriter sw = new StreamWriter("~/GridData.txt", false); 

DataTable dt = GetDataTable(); // Pseudo code 

// First we will write the headers. 
List<string> columnNames = new List<string>(); 
foreach (DataColumn column in dt.Columns) 
{ 
    columnNames.Add(column.ColumnName); 
} 
sw.WriteLine(string.Join(",", columnNames.ToArray())); 

// Now write all the rows. 
int iColCount = dt.Columns.Count; 
foreach (DataRow dr in dt.Rows) 
{ 
    List<string> columnData = new List<string>(); 
    for (int i = 0; i < iColCount; i++) 
    { 
     if (!Convert.IsDBNull(dr[i])) 
     { 
      columnData.Add(dr[i].ToString()); 
     } 
    } 
    sw.WriteLine(string.Join(",", columnData.ToArray())); 
} 

sw.Close(); 

這個代碼肯定會有進一步的優化和改進。我對寫出行的代碼不滿意。