How to Import CSV File and bind csv file data to gridview in asp.net using c#

I am going to demonstrate in this article about importing CSV file data into datatable and then bind that data to Asp.net gridview control. i have tried to make code simpler and less line of code.

I am assuming that you have saved the csv file to server by using fileupload control.


  • After that create function which returns string[]


private IEnumerable<string[]> GetAllDataFromCSVFile(string FileName)
        {
            string str;
            using (StreamReader rd=new StreamReader(FileName))
            {
                while ((str = rd.ReadLine()) != null)
                {
                    yield return str.Split(',');
                }
            }
        }


  • Create another function which returns final data-table with CSV File data


private DataTable GetCSVData(string FileName)
        {
            var values = GetAllDataFromCSVFile(FileName);
                DataTable dt = new DataTable();
                int j=0;
                foreach (var item in values.FirstOrDefault())
                {
                    if (!dt.Columns.Contains(item))
                     {
                          dt.Columns.Add(item.Replace("\"",""));
                       j++;
                      }
                }
                var allvalues=values.Skip(1).ToList();
                for (int i = 0; i < allvalues.Count; i++)
                {
                    dt.Rows.Add(allvalues[i].Take(dt.Columns.Count).ToArray());
                //remove double quote from data
                for(int co=0;co<j;co++)
                {
                    dt.Rows[i][co] = dt.Rows[i][co].ToString().Replace("\"","");

                }

                }
                return dt;
        }


  • Now call GetCSVData function from Submit event


  protected void submit_Click(object sender,EventArgs e)
        {
            string FileName = "";
        //your file upload logic

            DataTable dt = GetCSVData(FileName);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }


Comments

  1. I got a small bug on your code at GetCSVData method, the fix is:

    dt.Rows[i][co] = dt.Rows[i][co].ToString().Replace("\"", "");

    ReplyDelete
    Replies
    1. Thank you Marcelo for your warm reply, i will correct the bug shortly.

      Delete
  2. what about fields with a comma? I have such fields capped with quotes... example..."City, State Zip"

    ReplyDelete

Post a Comment