Sunday, 9 February 2020

Upload csv file in asp.net c#


Step 1: - Design

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplicationDemo.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Step 2: - Code

CSV file contain header.

using System;
using System.Data;
using System.IO;
using System.Linq;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!FileUpload1.HasFile || Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower() != ".csv")
            {
                Response.Write("Choose file to Upload. Only .CSV file allowed.");
                return;
            }
            else
            {
                DataTable dt = new DataTable("Table1");
                dt.Columns.Add("Column1", typeof(string));
                dt.Columns.Add("Column2", typeof(string));
                dt.Columns.Add("Column3", typeof(string));
                string[] validHeader = { "column1", "column2", "column3" };
                string inputContent;
                bool headerCheck = false;
                using (StreamReader inputStreamReader = new StreamReader(FileUpload1.PostedFile.InputStream))
                {
                    inputContent = inputStreamReader.ReadToEnd();
                    string[] stringSeparators = new string[] { "\r\n" };
                    foreach (var noOfRow in inputContent.Split(stringSeparators, StringSplitOptions.None))
                    {
                        if (!string.IsNullOrEmpty(noOfRow))
                        {
                            if (noOfRow.Split(',').Count() > dt.Columns.Count)
                            {
                                Response.Write("Only " + dt.Columns.Count + " columns allowed. Remove comma(,) at the end of each row.");
                                return;
                            }
                            else if (noOfRow.Split(',').Count() < dt.Columns.Count)
                            {
                                Response.Write("CSV file contain less than " + dt.Columns.Count + " columns. Upload CSV file with  " + dt.Columns.Count + " columns.");
                                return;
                            }
                            if (!headerCheck)
                            {
                                foreach (var row in noOfRow.Split(','))
                                {
                                    if (validHeader.Contains(row.ToLower()))
                                        headerCheck = true;
                                    else
                                    {
                                        Response.Write("CSV file contain invalid header.");
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                dt.Rows.Add();
                                int i = 0;
                                foreach (var row in noOfRow.Split(','))
                                {
                                    dt.Rows[dt.Rows.Count - 1][i] = row;
                                    i++;
                                }
                            }
                        }
                    }
                    if (dt.Rows.Count > 0)
                    {
                        //Add Code here
                    }
                    else
                    {
                        Response.Write("Atleast one record required to upload.");
                        return;
                    }
                }
            }
        }
    }
}

CSV file not contain header.

using System;
using System.Data;
using System.IO;
using System.Linq;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!FileUpload1.HasFile || Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower() != ".csv")
            {
                Response.Write("Choose file to Upload. Only .CSV file allowed.");
                return;
            }
            else
            {
                DataTable dt = new DataTable("Table1");
                dt.Columns.Add("Column1", typeof(string));
                dt.Columns.Add("Column2", typeof(string));
                dt.Columns.Add("Column3", typeof(string));
                string inputContent;
                using (StreamReader inputStreamReader = new StreamReader(FileUpload1.PostedFile.InputStream))
                {
                    inputContent = inputStreamReader.ReadToEnd();
                    string[] stringSeparators = new string[] { "\r\n" };
                    foreach (var noOfRow in inputContent.Split(stringSeparators, StringSplitOptions.None))
                    {
                        if (!string.IsNullOrEmpty(noOfRow))
                        {
                            if (noOfRow.Split(',').Count() > dt.Columns.Count)
                            {
                                Response.Write("Only " + dt.Columns.Count + " columns allowed. Remove comma(,) at the end of each row.");
                                return;
                            }
                            else if (noOfRow.Split(',').Count() < dt.Columns.Count)
                            {
                                Response.Write("CSV file contain less than " + dt.Columns.Count + " columns. Upload CSV file with  " + dt.Columns.Count + " columns.");
                                return;
                            }
                            else
                            {
                                dt.Rows.Add();
                                int i = 0;
                                foreach (var row in noOfRow.Split(','))
                                {
                                    dt.Rows[dt.Rows.Count - 1][i] = row;
                                    i++;
                                }
                            }
                        }
                    }
                    if (dt.Rows.Count > 0)
                    {
                        //Add Code here
                    }
                    else
                    {
                        Response.Write("Atleast one record required to upload.");
                        return;
                    }
                }
            }
        }
    }
}

No comments:

Post a Comment