简体   繁体   中英

Write csv file using CsvHelper, from excel in a dynamic way c#

I'm trying to generate a CSV file from excel files. I have different Excel files and I would like to read them and generate a CSV file. I imagine it must be quite easy, but I'm having some trouble.

This is the library I'm supposed to use

https://www.nuget.org/packages/CsvHelper/ .

I would appreciate any tutorial or anything on how I can approach this matter. The idea is to read the first row of my Excel files like headers and then the other rows as values, so I can write the CSV.

public class Program
{
    public static void Main()
    {
        string filePath = "C:\\Users\\{User}\\Desktop\\sample.xlsx";
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        List<List<object>> rows = new List<List<object>>();
        List<object> row = new List<object>();
        // Excel Reader
        using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
        {
            using (var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration
            {
                FallbackEncoding = Encoding.GetEncoding(1252),

            }))
            {
                do
                {
                    while (reader.Read())
                    {
                        row.Clear();
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            var field = reader.GetValue(i);
                            if (field is int valueInt)
                            {
                                row.Add(valueInt);
                            }
                            else if (field is bool valueBool)
                            {
                                row.Add(valueBool);
                            }
                            else if (field is DateTime valueDate)
                            {
                                //row.Add(valueDate); You can write any condition there
                                row.Add(valueDate.Year);
                            }
                            else if (field is TimeSpan valueTime)
                            {
                                row.Add(valueTime);
                            }
                            else if (field is string valueString)
                            {
                                row.Add(valueString);
                            }
                            else if (field is null)
                            {
                                row.Add(field);
                            }
                        }
                        if (row.Any())
                        {
                            rows.Add(row);
                        }
                    }
                } while (reader.NextResult());

            }
        }
        // CSV Writer
        using (var writer = new StreamWriter("C:\\Users\\{User}\\Desktop\\sample.csv"))
        using (var csv = new CsvWriter(writer))
        {
            foreach (var i in rows)
            {
                foreach (var field in i)
                {
                    csv.WriteField(field);
                }
                csv.NextRecord();
            }
        }
    }

}

This program convert Excel (sample.xlsx) file to CSV(sample.csv) File.

Dependencies :

Create a class file that would contain attributes which are same to that of your excel columns. Parse through your excel files and load it into the instance of your class. Write a simple program as follows

void Main()
{
    var records = new List<Foo>
    {
        new Foo { Id = 1, Name = "one" },
    };

    using (var writer = new StreamWriter("path\\to\\file.csv"))
    using (var csv = new CsvWriter(writer))
    {
        csv.WriteRecords(records);
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Where Foo is the class file. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM