How to store sorted records in csv file ?

Posted by Harikrishna on Stack Overflow See other posts from Stack Overflow or by Harikrishna
Published on 2010-05-05T09:25:30Z Indexed on 2010/05/05 9:28 UTC
Read the original article Hit count: 240

Filed under:
|
|
|

I sort the records of the datatable datewise with the column TradingDate which is type of datetime.

TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";

Now I want to display these sorted records into csv file but it does not display records sorted by date.

TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";TableWithOnlyFixedColumns.Columns["TradingDate"].ColumnName + "] asc";
            DataTable newTable = TableWithOnlyFixedColumns.Clone();
            newTable.DefaultView.Sort = TableWithOnlyFixedColumns.DefaultView.Sort;
            foreach (DataRow oldRow in TableWithOnlyFixedColumns.Rows)
            {
                newTable.ImportRow(oldRow);
            }
            // we'll use these to check for rows with nulls
            var columns = newTable.DefaultView.Table.Columns.Cast<DataColumn>();

            using (var writer = new StreamWriter(@"C:\Documents and Settings\Administrator\Desktop\New Text Document (3).csv"))
            {
                for (int i = 0; i < newTable.DefaultView.Table.Rows.Count; i++)
                {
                    DataRow row = newTable.DefaultView.Table.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));
                }
            }

So how to store sorted records in csv file ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms