Simplest code to export a datatable into .csv format

Introduction

Hello friends we all go for a complex coding for exporting the data into excel sheet. Some times we face a problem that we are not having the interop dll for export to excel. So here is a solution for all of us which will help in exporting the data into .csv format.

Using the code

Here is a simple code.

 Collapse | Copy Code
var lines = new List<string>();

string[] columnNames = dataTable.Columns.Cast<datacolumn>().
                                  Select(column => column.ColumnName).
                                  ToArray();

var header = string.Join(",", columnNames);
lines.Add(header);

var valueLines = dt.AsEnumerable()
                   .Select(row => string.Join(",", row.ItemArray));            
lines.AddRange(valueLines );

File.WriteAllLines("excel.csv",lines);</datacolumn></string>
Advertisements
By Sriramjithendra Posted in C#.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s