Writing data into CSV file in C#

后端 未结 15 1384
清酒与你
清酒与你 2020-11-22 17:15

I am trying to write into a csv file row by row using C# language. Here is my function

string first = reader[0].ToString();
string second=image.         


        
15条回答
  •  面向向阳花
    2020-11-22 17:46

    Instead of reinventing the wheel a library could be used. CsvHelper is great for creating and reading csv files. It's read and write operations are stream based and therefore also support operations with a big amount of data.


    You can write your csv like the following.

    using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv"))
    {
        var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
        writer.Configuration.Delimiter = ",";
    
        foreach (var item in list)
        {
            writer.WriteField( "a" );
            writer.WriteField( 2 );
            writer.WriteField( true );
            writer.NextRecord();
        }
    }
    

    As the library is using reflection it will take any type and parse it directly.

    public class CsvRow
    {
        public string Column1 { get; set; }
        public bool Column2 { get; set; }
    
        public CsvRow(string column1, bool column2)
        {
            Column1 = column1;
            Column2 = column2;
        }
    }
    
    IEnumerable rows = new [] {
        new CsvRow("value1", true),
        new CsvRow("value2", false)
    };
    using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv")
    {
        var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
        writer.Configuration.Delimiter = ",";
        writer.WriteRecords(rows);
    }
    

    value1,true

    value2,false


    If you want to read more about the librarys configurations and possibilities you can do so here.

提交回复
热议问题