Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Import Data from CSV in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 567
    Comment on it

    How to import data from CSV to Database

    Use the function below to import the data from excel to the database connected

    public void importdatafromexcel(string excelfilepath)
        {
        try
        {
        DataTable tblReadCSV= new DataTable();
        tblReadCSV.Columns.Add("ID");
        tblReadCSV.Columns.Add("Name");
        Microsoft.VisualBasic.FileIO.TextFieldParser csvParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(excelfilepath);
       csvParser.Delimiters = new string[] { "," };
       csvParser.TrimWhiteSpace = true;
       csvParser.ReadLine();
       while (!(csvParser.EndOfData == true))
       {
       tblReadCSV.Rows.Add(csvParser.ReadFields());
       }
     SqlConnection cnn = new  SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
      SqlCommand cmd = new SqlCommand();
      cnn.Open();
      for (int i = 0; i < tblReadCSV.Rows.Count; i++)
      {
      cmd = new SqlCommand("Insert into Tests (ID,Name) Values ('" + tblReadCSV.Rows[i]["ID"] + "','" +  tblReadCSV.Rows[i]["Name"] + "')", cnn);
     cmd.ExecuteNonQuery();
      }
    cnn.Close();
      }
      catch (Exception ex)
      {
      }
      }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: