C# 将M数据表导出到csv

C# 将M数据表导出到csv,c#,csv,datatable,C#,Csv,Datatable,我正在将数据表行导出为csv文件格式,格式应类似于value、value2、value3等,但我的输出文件显示的值类似于“value”、“value2”、“value3” 这是我的示例代码 Utilities.WriteDataTable(TempTable, writer, true); public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders) {

我正在将数据表行导出为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();

    }
Utilities.WriteDataable(可诱惑,编写器,true);
public static void writedatable(DataTable sourceTable、TextWriter writer、bool includeHeaders)
{
//检查表是否有标题:
如果(包括领导)
{
//获取标题:
List headerValues=新列表();
foreach(sourceTable.Columns中的DataColumn列)
{
headerValue.Add(QuoteValue(column.ColumnName));
}
writer.WriteLine(String.Join(“,”,headerValue.ToArray());
}
//从DataTable中获取行并将其放入数组
字符串[]项=null;
foreach(sourceTable.Rows中的DataRow行)
{
items=row.ItemArray.Select(o=>QuoteValue(o.ToString()).ToArray();
writer.WriteLine(String.Join(“,”,items));
}
writer.Flush();
}

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

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

但是,此解决方案并不是完美的解决方案,因为应该引用某些值,您应该尝试使用第三方CSV编写器来处理所有情况。(有关更多详细信息,请参见此SO答案)

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" }

您似乎正在调用名为
QuoteValue
的方法来创建项目列表。显然这不是你的代码。要创建正确的CSV,您需要引号。如果数据中有逗号怎么办?
CSV file: one, t,wo, thr"ee 
C# Array: { "one", "t", "wo", "thr", "ee" }