C# Code Snippets

Submit a Comment

Data to CSV

Armando

A simple method to write data in a DataTable or DataView format in C# to a CSV file.

Platform: .NET Framework 2.0

using System;
using System.Data;
using System.Windows.Forms;
using System.IO;

private void ExportDatatviewToCsv(string iFilename, DataView dv)
{
    // Open output stream
    StreamWriter swFile = new StreamWriter(iFilename);

    // Header
    string[] colLbls = new string[dv.Table.Columns.Count];
    for (int i = 0; i < dv.Table.Columns.Count; i++)
    {
        colLbls[i] = dv.Table.Columns[i].ColumnName;
        colLbls[i] = GetWriteableValueForCsv(colLbls[i]);
    }

    // Write labels
    swFile.WriteLine(string.Join(",", colLbls));

    // Rows of Data
    foreach (DataRowView rowData in dv)
    {
        string[] colData = new string[dv.Table.Columns.Count];
        for (int i = 0; i < dv.Table.Columns.Count; i++)
        {
            object obj = rowData[i];
            colData[i] = GetWriteableValueForCsv(obj);
        }

        // Write data in row
        swFile.WriteLine(string.Join(",", colData));
    }

    // Close output stream
    swFile.Close();
}

private void ExportDatatableToCsv(string iFilename, DataTable dt)
{
    // Open output stream
    StreamWriter swFile = new StreamWriter(iFilename);

    // Header
    string[] colLbls = new string[dt.Columns.Count];

    for (int i = 0; i < dt.Columns.Count; i++)
    {
        colLbls[i] = dt.Columns[i].ColumnName;
        colLbls[i] = GetWriteableValueForCsv(colLbls[i]);
    }

    // Write labels
    swFile.WriteLine(string.Join(",", colLbls));

    // Rows of Data
    foreach (DataRow rowData in dt.Rows)
    {
        string[] colData = new string[dt.Columns.Count];

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            object obj = rowData[i];
            colData[i] = GetWriteableValueForCsv(obj);
        }

        // Write data in row
        swFile.WriteLine(string.Join(",", colData));
    }

    // Close output stream
    swFile.Close();
}

public static string GetWriteableValueForCsv(object obj)
{
    // Nullable types to blank
    if (obj == null || obj == Convert.DBNull)
        return "";

    // if string has no ','
    if (obj.ToString().IndexOf(",") == -1)
        return obj.ToString();

    // remove backslahes
    return "\"" + obj.ToString() + "\"";
}

Back to C# Code Snippet List

Other C# Articles
Visual C# Kicks Newsletter
Visual C# Kicks RSS Feed