Import CSV File

15:58

Introduction

In this article I show how to import a csv file and view in a gridview.

Create Simple Application

Go to Visual Studio > File > New > Project > Web > Asp.Net Empty Web Application
The solution name is AspNETImportCsvFile the Ok
Now right click on the References click Add Reference... like below image:


In the Framework section, check Microsoft.VisualBasic and click Ok


Now create a new page name Test.aspx
Test.aspx code is below:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="AspNETImportCsvFile.Test" %>

<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style>
        table {
            /*border: 1px solid blue;*/
            padding: 1px;
            overflow:scroll;
        }
        table tbody tr th {
            font-size: 18px;
            background-color: brown;
            color: #fff;
            padding: 2px;
            text-align: center;
        }
        table tbody tr td { font-size:14px; color:#000; padding:2px; text-align:center; border: 1px solid #808080; }
        .head{background-color:#9f4b4b;color:#fff;font-size:50px;padding:5px;}
        body{font-family:Verdana;}
    </style>
</head>
<body>
    <form id="form1" runat="server" style="background-color:eeeeef;">
        <div style="margin-left: 35%; margin-top: 10%;">
            <table>
                <tr>
                    <td class="head">
                            Import CSV File
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:GridView ID="gvDetails" runat="server" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="506px" Height="183px">
                            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
                            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
                            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
                            <RowStyle BackColor="White" ForeColor="#003399" />
                            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
                            <SortedAscendingCellStyle BackColor="#EDF6F6" />
                            <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
                            <SortedDescendingCellStyle BackColor="#D6DFDF" />
                            <SortedDescendingHeaderStyle BackColor="#002876" />
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
Test.aspx.cs code:
Add namespace Microsoft.VisualBasic.FileIO
using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AspNETImportCsvFile
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string filename = FileUpload1.FileName.ToString();

                string path = Server.MapPath("~/Document/" + filename);
                FileUpload1.PostedFile.SaveAs(path);
                FetchData(path);
            }
        }

        protected void FetchData(string filepath)
        {
            DataTable dt = new DataTable();
            bool IsFirstRowHeader = true;
            string[] columnf = new string[] { "" };
            using (TextFieldParser parser = new TextFieldParser(filepath))
            {
                parser.TrimWhiteSpace = true;
                parser.TextFieldType = FieldType.Delimited;

                parser.SetDelimiters(",");

                if (IsFirstRowHeader)
                {
                    columnf = parser.ReadFields();

                    foreach (string sds in columnf)
                    {
                        DataColumn year = new DataColumn(sds.Trim().ToLower(), Type.GetType("System.String"));
                        dt.Columns.Add(year);
                    }
                }
                while (true)
                {
                    if (IsFirstRowHeader == false)
                    {
                        string[] parts = parser.ReadFields();

                        if (parts == null)
                        {
                            break;
                        }

                        dt.Rows.Add(parts);
                    }
                    IsFirstRowHeader = false;
                }
            }

            gvDetails.DataSource = dt;
            gvDetails.DataBind();
        }
    }
}
Run the application and we can see the below screen:


Now choose csv file under the project Document folder Book.csv and click Submit
All the data will show in the grid view, we can see the screen below:


Download

You can download application zip file here - 25.6 KB

Conclusion

Hei, I think it is very easy to import any csv file :)

You Might Also Like

0 comments