Click here to Skip to main content
15,395,257 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'm trying to use the library csvhelper to export an existing datatable (not a dataset) called CHAIN to a csv file. It looks like I need to create a new datatable and load CHAIN into it, rather than just iterate over CHAIN, but I'm not sure how to do this. Please take a look at the code below and let me know what's wrong?

What I have tried:

C#
public void EXPORT_CSV()
        {
            using (var textWriter = File.CreateText(@"D:\Temp\NewCsv.csv"))
            using (var csv = new CsvWriter(textWriter))
            using (var DT = new DataTable())
            {
                //dt.Load(CHAIN); not sure how to do this

                // Write columns
                foreach (DataColumn column in DT.Columns)       //copy datatable CHAIN to DT, or just use CHAIN
                {
                    csv.WriteField(column.ColumnName);
                }
                csv.NextRecord();

                // Write row values
                foreach (DataRow row in DT.Rows)
                {
                    for (var i = 0; i < DT.Columns.Count; i++)
                    {
                        csv.WriteField(row[i]);
                    }
                    csv.NextRecord();
                }
            }
        }
Posted
Updated 14-Feb-20 15:12pm
v2
Comments
Richard MacCutchan 8-Jun-16 3:25am
   
let me know what's wrong?
You have not explained what the problem is.

Based on your code, it looks like you just need to remove the using (var DT = new DataTable()) line, and replace each reference to DT with CHAIN:
C#
public void EXPORT_CSV()
{
    using (var textWriter = File.CreateText(@"D:\Temp\NewCsv.csv"))
    using (var csv = new CsvWriter(textWriter))
    {
        // Write columns
        foreach (DataColumn column in CHAIN.Columns)
        {
            csv.WriteField(column.ColumnName);
        }
        csv.NextRecord();
 
        // Write row values
        foreach (DataRow row in CHAIN.Rows)
        {
            for (var i = 0; i < CHAIN.Columns.Count; i++)
            {
                csv.WriteField(row[i]);
            }
            csv.NextRecord();
        }
    }
}
   
This is in the documentation. CsvHelper[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900