DataTable to CSV File and CSV file to Dataset in asp.net
Posted by Viral Sarvaiya on April 21, 2011
Hi,
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;
context.Response.Clear();
foreach (DataColumn column in dtExcelUpdown.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
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.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
context.Response.End();
}
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);
ExcelConnection.Open();
DataSet ExcelDataSet = new DataSet();
ExcelAdapter.Fill(ExcelDataSet);
ExcelConnection.Close();
return ExcelDataSet;
}
thanks…
enjoy coding…..


