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 =
new
OleDbConnection(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 row
in
dt.Rows)
{
excelSheets[i] = row[
"TABLE_NAME"
].ToString();
i++;
}
}
return
excelSheets;
}
private
void
InsertIntoList(DataTable listTable,
string
contactListName)
{
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
;
}
}
No comments:
Post a Comment