Thursday, June 05, 2014

Write DataTable as CSV Text File Using C#

Find below the code that write data from DataTable as a CSV text file

 

Using Section

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

 

Methods for Writing data to CSV

public static DataTable WriteCSV(String filename, DataTable table) {
    var csvData = new DataTable();
    StreamWriter csvFile = null;
    try {
        csvFile = new StreamWriter(filename);

        // Write header
        csvFile.WriteLine(
                String.Join(",",
                    from DataColumn dc in table.Columns
                    select dc.ColumnName)
            );

        foreach (DataRow dr in table.Rows) {
            csvFile.WriteLine(
                    String.Join(",",
                        from DataColumn dc in table.Columns
                        select dr[dc])
                );
        }
    }
    finally {
        if (csvFile != null)
            csvFile.Close();
    }

    return csvData;
}
private static String CsvValue(Object obj) {
    if (obj == null)
        return "";
    else if (obj.GetType() == typeof(String) || obj.GetType() == typeof(DateTime))
        return "\"" + obj.ToString() + "\"";
    else
        return obj.ToString();
}

No comments:

Post a Comment