C#从SharePoint上获取列表数据,写个博客记录一下。
首先先下载一个U2UCaml工具,因为在SharePoint上获取数据时,要对数据进行筛选,需要用到Caml语句。如果会写Caml的可以不用管,不会的可以下载一个(https://www.u2u.be/software)
下载完成之后,先输入SharePoint的地址,然后第二个单选框选择第二个,然后输入账号密码登录就行了。
登录之后左边就是SharePoint的所有列表,找到自己需要查询的那个。右键new Query就行了。
从SharePoint上获取数据是需要使用webservice的,不知道为什么,以前没用webservice老是出问题,用了之后就没出过了。
创建一个webservice之后需要引用一个程序集(using Microsoft.SharePoint.Client;)
下图是我写的一个简单的例子,其中要注意SharePoint列表所在的url一定要对,然后账号密码要对。
caml语句可以用上面所说的工具去生成。
查出来的结果添加到dt里就行了。(demo比较简单就查询了一个字段)
ClientContext clientContext = new ClientContext("SharePoint列表的url");
string strPassWord = ConfigHelper.GetConfigStr("密码");
char[] pChar = strPassWord.ToCharArray();
SecureString password = new SecureString();
foreach (char c in pChar)
{
password.AppendChar(c);
}
clientContext.Credentials = new SharePointOnlineCredentials(ConfigHelper.GetConfigStr("账号"), password);
string ViewXml = string.Empty;
List a = clientContext.Web.Lists.GetByTitle("列表名");
CamlQuery camlQuery = new CamlQuery();
ViewXml = "caml语句";
camlQuery.ViewXml = ViewXml;
Microsoft.SharePoint.Client.ListItemCollection Listitems = a.GetItems(camlQuery);
clientContext.Load(
Listitems,
items => items
.Include(
item => item["Alias"] //需要查询的字段
));
clientContext.Load(Listitems);
clientContext.ExecuteQuery(); //执行查询
DataTable dt = new DataTable();
dt.Columns.Add("Alias", Type.GetType("System.String")); //创建datatable
foreach (Microsoft.SharePoint.Client.ListItem listItem in Listitems)
{
DataRow newRow;
newRow = dt.NewRow();
newRow["Alias"] = listItem["Alias"] ?? "";
dt.Rows.Add(newRow); //添加到dt里
}