Read/Import CSV File'c Content

Lakhangarg
Posted by Lakhangarg under C# category on | Views : 4081
Read the CSV Data and Save the Data in DataSet.

Connection string = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Lakhan\Projects\Testweb\Test\;Extended Properties=""text;HDR=Yes;FMT=Delimited"""


if you want to consider first row as column then mention HDR=Yes otherwise no.
using System.Data.OleDb;

for(Int32 i=0; i
{
Response.Write(dataSetFromCSV.Tables[0].Columns[i].ColumnName + "<br/>");
}

this code is used to print all the column names

using System.Data.OleDb;
private void ReadCSVFile()
{
string cnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Lakhan\Projects\Testweb\Test\;Extended Properties=""text;HDR=Yes;FMT=Delimited""";
OleDbConnection ExcelConnection = new OleDbConnection(cnStr);
OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM [test.csv]", ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();

DataSet dataSetFromCSV = new DataSet();
ExcelAdapter.Fill(dataSetFromCSV);
ExcelConnection.Close();

for(Int32 i=0; i
{
Response.Write(dataSetFromCSV.Tables[0].Columns[i].ColumnName + "<br/>");
}


CSV File's Content:
Customer Number,Last Name,First Name,Address,City,Province,Postal Code,Balance
10001,Smith,Dave,123 Parkside Ave.,London,ON,N6J 4G6,125.35
10002,Pearson,Anne,44 Northside Road,Toronto,ON,N0M 5L8,38.12
10003,Carson,Ronald,12 Talbot Road,London,ON,N6U 3G8,1024.56
10006,Davis,Albert,19 Southam Road,Ajax,ON,N7J 5H7,-8.55
10007,Anderson,Theresa,118 Sarnia Road,London,ON,N6G 5C6,1181.12
10009,Jones,Jason,1008 Carver Place,Ottawa,ON,N8K 8H4,0.00

Comments or Responses

Login to post response