从datatable存储csv文件中的记录

时间:2010-05-01 06:51:37

标签: c# .net winforms csv datatable

我有数据表,我在datagridview中使用代码显示这些值:

   dataGridView1.ColumnCount = TableWithOnlyFixedColumns.Columns.Count;
   dataGridView1.RowCount = TableWithOnlyFixedColumns.Rows.Count;
   for (int i = 0; i < dataGridView1.RowCount; i++)
   {
       for (int j = 0; j < dataGridView1.ColumnCount; j++)
       {
           dataGridView1[j, i].Value = TableWithOnlyFixedColumns.Rows[i][j].ToString();
       }
   }
   TableExtractedFromFile.Clear();
   TableWithOnlyFixedColumns.Clear();

现在我想将记录保存在csv文件的数据表中。我该怎么做?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

// we'll use these to check for rows with nulls
var columns = yourTable.Columns
    .Cast<DataColumn>();

// say the column you want to sort by is called "Date"
var rows = yourTable.Select("", "Date ASC"); // or "Date DESC"

using (var writer = new StreamWriter(yourPath)) {
    for (int i = 0; i < rows.Length; i++) {
        DataRow row = rows[i];

        // check for any null cells
        if (columns.Any(column => row.IsNull(column)))
            continue;

        string[] textCells = row.ItemArray
            .Select(cell => cell.ToString()) // may need to pick a text qualifier here
            .ToArray();

        // check for non-null but EMPTY cells
        if (textCells.Any(text => string.IsNullOrEmpty(text)))
            continue;

        writer.WriteLine(string.Join(",", textCells));
    }
}