In This article I am going to explain how to read csv file in asp.net using c# and vb.net as well as also explain how you can use file upload control in asp.ne and how you can read csv file and display records on data grid view in asp.net using c# and vb.net.
 |
Read CSV File |
What is CSV File ?
CSV file is a file that contains comma-separated (,) Values. CSV file stores the data/information in tabular format in form of plain text where each and every line of this file is data/information where each and every data/record consists of one or more then one fields separated by commas (,).
Requirement
1) Create a Web page.
2) Create Web page design with various different controls such as file upload Control, Data-grid and Button.
3) Create a Method/function To Read Data From CSV file
4) With use of created Method/Function Read data from CSV File and Display in Data-grid.
Implementation
Here, first we will create a simple web page in asp.net for demonstration.
So, first we need a asp.net web page to archive our requirement so first we will create a simple web page and to create simple web page please you can follow given steps below.
Step 1: Open Visual Studio 2013.
Step 2: Click on top menu "FILE" >> "NEW" >> "WEB SITE".
 |
Create Website in Visual Studio |
Step 3: Now you can see popup window on your screen as shown as below where you need to select your language C# or vb.net as per your requirement, here I chooses c#.
 |
Empty Web Site |
Now, select "ASP.NET Empty Web Site" and then choose your project path where you wanna save your files and folders of your website and then click ok and you have created your empty website.
Now you need to add web page on your root directory of project.
Step 4: Press your mouse right click on your name of project. and click on "Add" >> "Add New Item".
 |
Add Web Form |
Step 5: Select Web page and Give name of your web page and press OK.
 |
Web Form |
Now, It's time to design our web page as per our requirement so write following css before your </head> tag.
CSS
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th
{
background-color: #ff0097;
color: #fff;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
}
table, table table td
{
border: 0px solid #ccc;
}
.button {
background-color: #223c88; /* Blue */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
</style>
Now, add other controls such as grid-view, file-upload control, button etc and your full html code look like as shown below.
HTML CODE
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
<!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>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th
{
background-color: #ff0097;
color: #fff;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
}
table, table table td
{
border: 0px solid #ccc;
}
.button {
background-color: #223c88; /* Blue */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnRead" CssClass="button" runat="server" Text="Import" OnClick="ReadCSV" />
<hr />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>
Before Start actual code you need following namespace first.
Namespaces
C#
using System.IO;
using System.Data;
VB.NET
Imports System.IO
Imports System.Data
Now, Write following code to Read CSV File. Hear you can create Function/Method but as per my need i directly create click event and write this code in click event then after i'll give this event name to button "Read CSV" using OnClick property of button.
C#
protected void ReadCSV(object sender, EventArgs e)
{
//Upload and save the file
string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(csvPath);
//Create a DataTable.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[6] { new DataColumn("Id", typeof(int)),
new DataColumn("CustomerName", typeof(string)),
new DataColumn("Item", typeof(string)),
new DataColumn("Qty", typeof(Int32)),
new DataColumn("Price", typeof(Decimal)),
new DataColumn("Amount",typeof(Decimal)) });
//Read the contents of CSV file.
string csvData = File.ReadAllText(csvPath);
//Execute a loop over the rows.
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
//Execute a loop over the columns.
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
//Bind the DataTable.
GridView1.DataSource = dt;
GridView1.DataBind();
}
VB.NET
Protected Sub ReadCSV(sender As Object, e As EventArgs)
'Upload and save the file
Dim csvPath As String = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName)
FileUpload1.SaveAs(csvPath)
'Create a DataTable.
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(5) {New DataColumn("Id", GetType(Integer)), New DataColumn("CustomerName", GetType(String)), New DataColumn("Item", GetType(String)), New DataColumn("Qty", GetType(Int32)), New DataColumn("Price", GetType(Decimal)), New DataColumn("Amount", GetType(Decimal))})
'Read the contents of CSV file.
Dim csvData As String = File.ReadAllText(csvPath)
'Execute a loop over the rows.
For Each row As String In csvData.Split(ControlChars.Lf)
If Not String.IsNullOrEmpty(row) Then
dt.Rows.Add()
Dim i As Integer = 0
'Execute a loop over the columns.
For Each cell As String In row.Split(","c)
dt.Rows(dt.Rows.Count - 1)(i) = cell
i += 1
Next
End If
Next
'Bind the DataTable.
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Now, Its time to display record on grid view so I'll just give datatable to grid view as data source.
Now i will run my web application.
Explanation
After run my application i will click on file upload control and select/browse csv file as input. Now when i click on button "Read CSV" first my selected input csv file will upload and then saved within a created folder "Files" on my root directory of project. Now the information/data of csv file is browsed into a String variable with using the ReadAllText method.
Hear i have formed/created/designed a datatable with columns same as destination table so data/information of csv file is split using the Comma (,) as well as new line (\n). And with use of loop simply all the information is saved into the data table.
And Now, Finally i gives that datatable data source to data grid view control populate the ASP.NET grid View control.
Output
 |
CSV |
Summary
This article explain how you can read csv file using c# and vb.net in asp.net as well as how you can create web form in asp.net core.
You May Like To Read