How to read CSV file data and display it in gridview?


In this article I have explained in detail about how to read data from CSV file and bind it into grid view control using OLEDB concept and Stream Reader Concept. This code snippet is help you in your development.

Description


For an example we have lots of data in csv file. Sometimes we need to read that data and bind it into gridview. I have explained in detail about that concept in two methods

1) Using OLEDB concept to read CSV file data and bind it in gridview.
2) Using Stream Reader to read CSV file data and bind it in gridview

CSV file Data



eno, empname,sal
101, Ravi,25000
102, James,18000
103, Allen,23000
104, Mike,21000
105, Arun,45000
106, Vinay,35000
107, Karthik,12000
108, John,10000
109, Joseph,9000
110, Miky,5000

Client side:


Just I placed two buttons to user select which method user want to read CSV file.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" width="800" align="center">
<tr>
<td height="60">
<b>Read CSV file using Oledb Command Stream Reader</b>
</td>
</tr>
<tr>
<td height="30" align="center">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td height="50" align="center">
<asp:Button ID="Button1" runat="server" Text="Read CSV using OleDbCommand" OnClick="Button1_Click" /> <asp:Button
ID="Button2" runat="server" Text="Read CSV using Stream Reader"
onclick="Button2_Click" />
</td>
</tr>
<tr>
<td align="center">
<asp:GridView ID="GridView1" runat="server" Width="400">
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Server side



sing System.Data.OleDb;
using System.Data;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
}

//First method read CSV file using oledb command
protected void Button1_Click(object sender, EventArgs e)
{
//create instance foe oledb connection class
OleDbConnection con = new OleDbConnection();

//Your datasource Location path currently i placed csv file in server location
string dsource = Server.MapPath("") + "\\";

//Put your datasource path in the connection string for example if you have csv files in C:\ directory change datasource= C:\
string constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dsource + ";Extended Properties='text;HDR=Yes;FMT=Delimited';";

try
{
con.ConnectionString = constr;

//create instance for command object
OleDbCommand cmd = new OleDbCommand();

cmd.Connection = con;

// set your file name in the below query
cmd.CommandText = "select * from [test.csv]";

//Open Oledb Connection to read CSV file
con.Open();

//Create one datatable to store data from CSV file
DataTable dt = new DataTable();

// Load Data into the datatable
dt.Load(cmd.ExecuteReader());

//Bind data in the Gridview
GridView1.DataSource = dt;
GridView1.DataBind();

}
catch (Exception ex)
{
Label1.Text="Error while reading" + ex.ToString();
}
finally
{
con.Close();
}
}

//Second method read CSV file using reader concept
protected void Button2_Click(object sender, EventArgs e)
{
StreamReader sr=null;
DataTable dt = new DataTable();
DataRow dr;
string column1 = "";
string column2="";
string column3="";

try
{
sr = new StreamReader(Server.MapPath("test.csv"));
string eachline = "";
string[] colval = null;
int i = 0;
while (!sr.EndOfStream)
{
//Read line by line
eachline = sr.ReadLine();
colval = eachline.Split(',');

//Check reader read first line first line header is available so create column header text in datatable
if (i == 0)
{
column1 = colval[0];
column2 = colval[1];
column3 = colval[2];
dt.Columns.Add(column1);
dt.Columns.Add(column2);
dt.Columns.Add(column3);
i = i + 1;
}
//Add values in the datatable columns
else
{
dr = dt.NewRow();
dr[column1] = colval[0];
dr[column2] = colval[1];
dr[column3] = colval[2];
dt.Rows.Add(dr);
}
}
sr.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{

}
finally
{

}
}
}

Output


The output look like this screen shot after read CSV Read
Output

Source Code Detail:
Here with I have attached source code of CSV File read concept download it and try it.

Front End : ASP.NET
Code Behind : C#

Conclusion:
I hope this article help you to know about CSV read process.


Attachments

  • Source_code (43692-251132-CSVRead.rar)
  • Comments

    Guest Author: penolakan02 May 2012

    Some months ago I had a lot of cotrupred excel files and I didn't know what to do,but in some time to me recommended-,and tool helped me,as far as I remember it has free status and has no one feature,utility can try Excel repairs manually, by retyping all documents, but it is time consuming, you can spend many days for this purpose, when Excel file has cotrupred,tool for Excel repairing is very easy to use, when Excel file cotrupred, it has only several buttons and functions for Excel document repair: open file, start its analysis, preview of recovered contents and export of recovered data into a new document in Microsoft Excel format,allows to perform all steps and take a look into recovered contents of this file.

    Guest Author: Deepti08 Sep 2012

    It really works..thank you so much for the code..



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: