Dev
Dev

Reputation: 317

Exportingm DataTable to csv

I am exporting DataTable rows to csv file format should be like value, value2, value3 , and so on but my output file shows values like this "Value", "value2", "value3" Here is my sample code

Utilities.WriteDataTable(TempTable, writer, true);
public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
    {
        //Checking if Table has headers :
        if (includeHeaders)
        {
            //Getting Headers:
            List<string> headerValues = new List<string>();
            foreach (DataColumn column in sourceTable.Columns)
            {
                headerValues.Add(QuoteValue(column.ColumnName));
            }

            writer.WriteLine(String.Join(",", headerValues.ToArray()));
        }
        //fetching rows from DataTable and Putting it in Array 
        string[] items = null;
        foreach (DataRow row in sourceTable.Rows)
        {
            items = row.ItemArray.Select(o => QuoteValue(o.ToString())).ToArray();
            writer.WriteLine(String.Join(",", items));
        }

        writer.Flush();

    }

Upvotes: 0

Views: 358

Answers (2)

Will
Will

Reputation: 1098

QuoteValue is a custom method to enclose the value with quotation marks and doubling any quotes found:

    private static string QuoteValue(string value)
    {
        return String.Concat("\"", value.Replace("\"", "\"\""), "\"");
    }

This helps CSV parsers so that extra columns aren't created:

CSV file: "one", "t,wo", "thr""ee"
C# Array: { "one", "t,wo", "thr\"ee" }

This would happen without quote handling:

CSV file: one, t,wo, thr"ee 
C# Array: { "one", "t", "wo", "thr", "ee" }

Upvotes: 0

Bun
Bun

Reputation: 1495

It's because you are adding quotes around the values:

List<string> headerValues = new List<string>();
foreach (DataColumn column in sourceTable.Columns)
{
     headerValues.Add(QuoteValue(column.ColumnName));
}

Try without the QuoteValue call:

List<string> headerValues = new List<string>();
foreach (DataColumn column in sourceTable.Columns)
{
     headerValues.Add(column.ColumnName);
}

This solution is however not the perfect fix since some values should be quoted, you should try using a third-party CSV writer that will handle all cases for you. (See this SO answer for more details Good CSV Writer for C#?)

Upvotes: 1

Related Questions