将DataTable导出到csv

时间:2014-07-16 14:33:32

标签: c# csv datatable

我将DataTable行导出为csv文件格式应该像value,value2,value3等,但我的输出文件显示的值如“Value”,“value2”,“value3” 这是我的示例代码

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();

    }

2 个答案:

答案 0 :(得分:1)

这是因为您在值周围添加了引号:

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

在没有QuoteValue电话的情况下尝试:

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

然而,这个解决方案不是完美的解决方案,因为应引用某些值,您应该尝试使用第三方CSV编写器来处理所有情况。 (有关详细信息,请参阅此SO答案Good CSV Writer for C#?

答案 1 :(得分:0)

QuoteValue是一个自定义方法,用引号将值括起来,并将找到的任何引号加倍:

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

这有助于CSV解析器,以便不会创建额外的列:

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

没有报价处理就会发生这种情况:

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