.net
How to import Sharepoint list in c sharp
A
Desh-Duniya Team
Author
Please install nuget package :
Microsoft.SharePoint.Client
Microsoft.SharePoint.Client.Online.CSOM
Microsoft.Sharepoint.Client.Runtime
SharePoint.Client.Office.Tools
Please use caml for Recursive list:
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Geq><FieldRef Name='ID'/>" +
"<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>3000</RowLimit></View>";
protected DataTable ImportListFromSharepoint()
{
DataTable dtsharepoint = new DataTable();
string username = "your user name";
string password = "your password";
string siteUrl = "your sharepoint url/_layouts/15/viewlsts.aspx";
SP.ClientContext clientContext = new SP.ClientContext(siteUrl);
SecureString securePassword = new SecureString();
foreach (var item in password.ToCharArray())
{
securePassword.AppendChar(item);
}
clientContext.Credentials = new SP.SharePointOnlineCredentials(username, securePassword);
SP.List oList = clientContext.Web.Lists.GetByTitle("list name");
SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
"<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>15000</RowLimit></View>";
SP.ListItemCollection collListItem = oList.GetItems(camlQuery);
SP.FieldCollection oFields = oList.Fields;
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
dtsharepoint.Columns.AddRange(new DataColumn[]
{
new DataColumn("ID"),
new DataColumn("your share point column"),
});
foreach (ListItem oListItem in collListItem)
{
ID = "";
your sharepoint column= "";
DataRow dataRow = dtsharepoint.NewRow();
foreach (var fieldValue in oListItem.FieldValues)
{
var da = oListItem.FieldValues[fieldValue.Key];
if (da is Microsoft.SharePoint.Client.FieldUserValue[])
{
foreach (var d in ((Microsoft.SharePoint.Client.FieldUserValue[])da))
{
if (dtsharepoint.Columns.Contains(fieldValue.Key) == false)
{
dtsharepoint.Columns.Add(fieldValue.Key);
}
dataRow[fieldValue.Key] = dataRow[fieldValue.Key] + "," + d.LookupValue;
}
}
else if (da is Microsoft.SharePoint.Client.FieldUserValue)
{
if (dtsharepoint.Columns.Contains(fieldValue.Key) == false)
{
dtsharepoint.Columns.Add(fieldValue.Key);
}
dataRow[fieldValue.Key] = ((Microsoft.SharePoint.Client.FieldLookupValue)da).LookupValue;
}
}
dataRow["ID"] = ID;
dataRow["your sharepoint column"] = your sharepoint column;
}
dt = dtsharepoint;
return dt;
}