In this post we will see how to upload excel data(using oledb provider) into SharePoint 2007 / SharePoint 2010 Custom List from object model(c#)
What are the points that are covered
Upload excel data
The following code reads data from contacts.xls and inserts into SharePoint Custom List ContactList which I have created.
According to the schema of the ContactList, the method InsertIntoList() in the following code has relevant code.
You can modify according to the schema of your Custom List and Excel file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
using System.Data.OleDb;
using Microsoft.SharePoint;
namespace TestSharepointProject
{
public class UploadExcelData
{
public void LoadExcelData()
{
string fileName ="@"C:\AdisGroup\Contacts\contacts.xls";
//if you are using file upload control in sharepoint get the full path as follows assuming fileUpload1 is control instance
//string fileName = fileUpload1.PostedFile.FileName
string fileExtension = Path.GetExtension(fileName).ToUpper();
string connectionString ="";
if (fileExtension ==".XLS")
{
connectionString ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + fileName +"'; Extended Properties='Excel 8.0;HDR=YES;'";
}
else if (fileExtension ==".XLSX")
{
connectionString ="Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName +"';Extended Properties='Excel 12.0 Xml;HDR=YES;'";
}
if (!(string.IsNullOrEmpty(connectionString)))
{
string[] sheetNames = GetExcelSheetNames(connectionString);
if ((sheetNames !=null) && (sheetNames.Length > 0))
{
DataTable dt =null;
OleDbConnection con =newOleDbConnection(connectionString);
OleDbDataAdapter da =new OleDbDataAdapter("SELECT * FROM [" + sheetNames[0] +"]", con);
dt =new DataTable();
da.Fill(dt);
InsertIntoList(dt,"ContactList");
}
}
}
private string[] GetExcelSheetNames(string strConnection)
{
var connectionString = strConnection;
String[] excelSheets;
using (var connection =new OleDbConnection(connectionString))
{
connection.Open();
var dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
if (dt ==null)
{
return null;
}
excelSheets =new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow rowin dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
}
return excelSheets;
}
private void InsertIntoList(DataTable listTable,stringcontactListName)
{
SPWeb mySite =null;
try
{
mySite = SPContext.Current.Web;//create web object if context is null
mySite.AllowUnsafeUpdates =true;
SPList contactList = mySite.Lists[contactListName];
for (int iRow = 0; iRow < listTable.Rows.Count; iRow++)
{
SPListItem newContact = contactList.Items.Add();
newContact["FirstName"] = Convert.ToString(listTable.Rows[iRow][0]);
newContact["LastName"] = Convert.ToString(listTable.Rows[iRow][1]);
newContact["FullName"] = Convert.ToString(listTable.Rows[iRow][2]);
newContact["LoginID"] = Convert.ToString(listTable.Rows[iRow][3]);
newContact["EmailAddress"] = Convert.ToString(listTable.Rows[iRow][4]);
newContact["PhoneNumber"] = Convert.ToString(listTable.Rows[iRow][5]);
newContact["Company"] = Convert.ToString(listTable.Rows[iRow][6]);
newContact.Update();
}
mySite.AllowUnsafeUpdates =false;
}
catch (Exception ex)
{
//log exception
}
finally
{
if (mySite !=null)//don't dispose if the site is from SPContext
{
mySite.AllowUnsafeUpdates =false;
}
}
}
}
}
In the above code
LoadExcelData method takes data from first sheet name i.e sheetNames[0]. Change this if you want to load from another sheetName
InsertIntoList method uses SPContext to get the current web object. If you are using the above code where SPContext is not available then you have to create SPWeb object and dispose it in finally block