开发者

Storing the records in csv file from datatable

I have datatable and I am displaying those values in the datagridview with the helping of code :

   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++)
    开发者_如何学Go   {
           dataGridView1[j, i].Value = TableWithOnlyFixedColumns.Rows[i][j].ToString();
       }
   }
   TableExtractedFromFile.Clear();
   TableWithOnlyFixedColumns.Clear();

Now I want to save the records in the datatable in csv file.How can I do that ?


You could do this:

// 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));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜