2010-07-18 111 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(); 

这个代码肯定会有进一步的优化和改进。我对写出行的代码不满意。