Monday, July 9, 2012

Import Excell,csv file into Linq

I  have csv file with name infocontext,  having two fileds

1.Alies
2. ShortDesc

Now i  am  importing My Excel data from csv file to database using Linq  (Entity Framework in MVC3)

I  have table Infocontext

1. Create properties of class for Table

--->
 public class InfoContext
    {
                     public string Tag { get; set; }
                     public string Alias { get; set; }
     }

2.  Now Write this Method

 public ActionResult ImportCSV()
        {
          // Object of My Class
 InfoContext Dtinfo = new InfoContext();


           // Import  data  from csv file
 var dataImport = System.IO.File.ReadAllLines(Server.MapPath("~/Areas/Cataloging/infocontext.csv"));
            
            for(int i=0;i<=dataImport.Length;i++)
            {

             // Split data from Excel by  column
                string[] word = dataImport[i].Split(',');
                for(int k=0;k<=word.Length-1;i++)
                {


                    Dtinfo.Alias = word[0];
                    Dtinfo.ShortDesc = word[1];
                     db.InfoContext.Add(Dtinfo);  // Saving data  by  code  first tech. you can write your own method to save data

                    db.SaveChanges();
                }
            }

            return View();


        }


Data  is   Saved..

Happy Programing