Upload Excel data into SharePoint List using C#

Method to read file from upload control.

  1. if (fuExcelUpload.HasFile) {  
  2.     string strPath = "C:\\UploadExcel";  
  3.     string SheetName = "Upload";  
  4.     Directory.CreateDirectory(strPath);  
  5.     strPath = strPath + "\\";  
  6.     fuExcelUpload.SaveAs(strPath + fuExcelUpload.FileName);  
  7.     strPath = strPath + fuExcelUpload.FileName;  
  8.     DataSet ds = LoadExcel(strPath, SheetName);  
  9.     DataTable dt = ds.Tables[0];  
  10.     InsertIntoList(dt);  
  11. }  
Method to insert excel data into SharePoint List.
  1. private void InsertIntoList(DataTable listTable) {  
  2.     try {  
  3.         SPSecurity.RunWithElevatedPrivileges(delegate() {  
  4.             using(SPSite site = new SPSite(SPContext.Current.Web.Url)) {  
  5.                 site.AllowUnsafeUpdates = true;  
  6.                 using(SPWeb web = site.OpenWeb()) {  
  7.                     web.AllowUnsafeUpdates = true;  
  8.                     SPList lstRMD = web.Lists["Your List Name"];  
  9.   
  10.                     for (int iRow = 0; iRow < listTable.Rows.Count; iRow++) {  
  11.                         SPListItem revItem1 = lstRMD.Items.Add();  
  12.                         revItem1["Field1"] = Convert.ToString(listTable.Rows[iRow][0]);  
  13.                         revItem1["Field2"] = Convert.ToString(listTable.Rows[iRow][1]);  
  14.                         revItem1.Update();  
  15.                     }  
  16.                     web.AllowUnsafeUpdates = false;  
  17.                 }  
  18.                 site.AllowUnsafeUpdates = false;  
  19.             }  
  20.   
  21.         });  
  22.   
  23.     } catch (Exception ex) {}  
  24.   
  25. }