Monday, January 14, 2013

Helper function to Convert DataTable to CSV file using LINQ

Below Function takes input as DataTable and file path where CSV file is generated. LINQ approach is so fast that it convert a big DataTable to CSV file in few seconds.


public static void ConvertToCSV(DataTable dt, string strFilePath)
        {
            StreamWriter sw = new StreamWriter(strFilePath, false);
            StringBuilder sb = new StringBuilder();
            var columnNames = dt.Columns.Cast().Select(column => column.ColumnName.ToUpper()).ToArray();
            sb.AppendLine(string.Join(",", columnNames));
            foreach (DataRow row in dt.Rows)
            {
                var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
                sb.AppendLine(string.Join(",", fields));
            }         
            sw.Write(Convert.ToString(sb));
        }

~cheers...

No comments: