In This article, I am going to explain how to read CSV files in asp.net using c# and vb.net as well as also explain how you can use file upload control in asp. no and how you can read CSV files and display records on data grid view in asp.net using c# and vb.net.
|
Read CSV File |
What is CSV File?
A 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 than one field separated by commas (,).
Requirement
1) Create a Web page.
2) Create a Web page design with various controls such as file upload Control, Data-grid, and Button.
3) Create a Method/function To Read Data From a CSV file
4) With the use of created Method/Function Read data from the CSV File and Display it in Data-grid.
Implementation
Here, first, we will create a simple web page on asp.net for demonstration.
So, first, we need an asp.net web page to archive our requirement so first, we will create a simple web page to create e simple web page please you can follow the given steps below.
Step 1: Open Visual Studio 2013.
Step 2: Click on the top menu "FILE" >> "NEW" >> "WEB SITE".
Step 3: Now you can see a popup window on your screen as shown below where you need to select your language C# or vb.net as per your requirement, here I choose 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 a web page to your project's root directory.
Step 4: Press your mouse and right-click on the name of the project. and click on "Add" >> "Add New Item".
|
Add Web Form |
Step 5: Select Web Form Give the name of your web page and press OK.
Now, It's time to design our web page as per our requirement so write the 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 complete 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 starting the actual code you need to follow the namespace first.
Namespaces
C#
using System.IO;
using System.Data;
VB.NET
Imports System.IO
Imports System.Data
Now, Write the following code to Read CSV File. Here you can create a Function/Method but as per my need, I directly create a click event and write this code in the click event then after I'll give this event name to the button "Read CSV" using the OnClick property of the 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, It's time to display records on grid view so I'll just give datatable to grid view as a data source.
Now I will run my web application.
Explanation
After running my application I will click on file upload control and select/browse the CSV file as input. Now when I click on the button "Read CSV" first my selected input CSV file will upload and then save within a created folder "Files" on my root directory of the project. Now the information/data of the CSV file is browsed into a String variable using the ReadAllText method.
Here I have formed/created/designed a datatable with columns the same as the destination table so data/information of the CSV file is split using the Comma (,) as well as new line (\n). And with the use of a loop simply all the information is saved into the data table.
And Now, Finally, I give that datatable data source to the data grid view control that populates the ASP.NET Grid View control.
Output
|
CSV |
Summary
This article explains how you can read CSV files using c# and vb.net in asp.net as well as how you can create a web form in asp.net core.
You May Like To Read
Tags:
read data from csv file in c#
c# read csv file line by line
upload and read csv file in asp.net c#
c# read csv file into datatable
best way to read csv file in c#
c# read csv file into list
read csv file in c# .net core