Mike
Mike

Reputation: 219

How to convert a single datatable column to csv?

How to convert a single datatable column to csv? I have a datatable that have two columns (Id,name) , how can I convert Id column to csv string?

Upvotes: 6

Views: 4502

Answers (3)

Arion
Arion

Reputation: 31239

If you want to write to a file you can do this:

var dt=new DataTable();
    dt.Columns.Add("Id",typeof(int));
    dt.Columns.Add("name",typeof(string));

    dt.Rows.Add(1,"test");

    File.WriteAllLines("C:\\test\\test.csv",
        dt.AsEnumerable()
            .Select(d =>
                string.Format("{0},{1}",d.Field<int>("Id"),d.Field<string>("name")))
        );

Upvotes: 2

codediesel
codediesel

Reputation: 63

you can export using Toad Mysql Or Oracle.

Also you can do this using PHP but this is depending in what you are after.

you can look into this PHP to csv

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

What is the expected result? A string where each id is separated by comma or a string where the id is separated by new-line characters?

However, you can use String.Join + LINQ:

string result = String.Join(
    Environment.NewLine, // replace with "," if desired
    table.AsEnumerable().Select(row => row.Field<int>("ID")));

Upvotes: 11

Related Questions