Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

DataTable to CSV File and CSV file to Dataset in

Posted by Viral Sarvaiya on April 21, 2011


here i give you 2 simple function for the export Datatable/Dataset to CSV file format and import CSV file to dataset/DataTable.

1. DataTable/DataSet to CSV file

private void DataTableToCSVFile(string filename)
HttpContext context = HttpContext.Current;
foreach (DataColumn column in dtExcelUpdown.Columns)
context.Response.Write(column.ColumnName + ",");
foreach (DataRow row in dtExcelUpdown.Rows)
for (int i = 0; i < dtExcelUpdown.Columns.Count; i++)
context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");

2. CSV file to DataSet/DataTable

from the upload control you have to save to directory and then this path and file name give as a parameter of the function.

private DataSet GetCVSFile(string pathName, string fileName)
OleDbConnection ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties=Text;");
OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM " + fileName, ExcelConnection);

OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);


DataSet ExcelDataSet = new DataSet();

return ExcelDataSet;


enjoy coding…..


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: