如何让csvHelper将csv写为文本

时间:2017-09-20 17:22:29

标签: c# csvhelper csv-write-stream

我有以下代码

using (StreamWriter streamwriter = new StreamWriter(savetopath))
{
    using (CsvWriter csv = new CsvWriter(streamwriter))
    {
        List<string> columns = new List<string>();
        foreach (DataColumn column in shopifyDatatable.Columns)
            csv.WriteField(column.ColumnName.ToString());

        csv.NextRecord();

        foreach (DataRow row in shopifyDatatable.Rows)
        {
            for (var i = 0; i < shopifyDatatable.Columns.Count; i++)
            {
                csv.WriteField(row[i].ToString());
            }
            csv.NextRecord();
        }
    }
}

一切正常但现场017825892588最终为17825892588.

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

在我的机器上运行。完整MCVE

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string savetopath = @"C:\Users\myusername\Desktop\test.csv";
            DataTable table = new DataTable();
            table.Columns.Add("Column A", typeof(string));
            table.Rows.Add("056");

            using (StreamWriter streamwriter = new StreamWriter(savetopath))
            {
                using (CsvWriter csv = new CsvWriter(streamwriter))
                {
                    List<string> columns = new List<string>();
                    foreach (DataColumn column in table.Columns)
                        csv.WriteField(column.ColumnName.ToString());

                    csv.NextRecord();

                    foreach (DataRow row in table.Rows)
                    {
                        for (var i = 0; i < table.Columns.Count; i++)
                        {
                            csv.WriteField(row[i].ToString());
                        }
                        csv.NextRecord();
                    }
                }
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey(true);
        }
    }
}

输出:

Column A
056