Read CSV File In ASP.NET With Example C# and VB.NET

watch_later Thursday, December 6, 2018
comment 2 Comments
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
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
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
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
Add Web Form

Step 5: Select Web page and Give name of your web page and press OK.
Web Form
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-familyArial;
            font-size10pt;
        }
        table
        {
            border1px solid #ccc;
            border-collapsecollapse;
            background-color#fff;
        }
        table th
        {
            background-color#ff0097;
            color#fff;
            font-weightbold;
        }
        table thtable td
        {
            padding5px;
            border1px solid #ccc;
        }
        tabletable table td
        {
            border0px solid #ccc;
        }
        .button {
    background-color#223c88/* Blue */
    bordernone;
    colorwhite;
    padding15px 32px;
    text-aligncenter;
    text-decorationnone;
    displayinline-block;
    font-size16px;
}
    </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-familyArial;
            font-size10pt;
        }
        table
        {
            border1px solid #ccc;
            border-collapsecollapse;
            background-color#fff;
        }
        table th
        {
            background-color#ff0097;
            color#fff;
            font-weightbold;
        }
        table thtable td
        {
            padding5px;
            border1px solid #ccc;
        }
        tabletable table td
        {
            border0px solid #ccc;
        }
        .button {
    background-color#223c88/* Blue */
    bordernone;
    colorwhite;
    padding15px 32px;
    text-aligncenter;
    text-decorationnone;
    displayinline-block;
    font-size16px;
}
    </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 datasource.

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
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


Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

avatar
Anonymous

Hi I'm confused about the use of the Gridview1 property, I can't access this from my C# code and I'm wondering where it's declared? Right now I'm getting an error underneath it

delete September 24, 2019 at 1:37 AM
avatar

Gridview1 is declared in CS.aspx.cs file. That is a aspx control written in the cs.aspx.cs file .

Make sure you have this code in your cs.aspx.cs file.

delete September 24, 2019 at 7:53 AM



sentiment_satisfied Emoticon