SharePoint操作列表,视图

//SharePoint对象模型 加载复选框和下拉列表的值
                        using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                        {

                            using (SPWeb web = site.OpenWeb("站点"))
                            {

                                SPList list = web.Lists[ListTitle];
/*CAML 协作标记语言,查询
SPQuery query = new SPQuery();
                   
                    query.Query = "<Where><Eq><FieldRef Name='栏'/><Value Type='Text'>值</Value></Eq></Where>";
                    if (Lists.GetItems(query).Count > 0)
                    }
*/ SPFieldMultiChoice choice2
= list.Fields.GetFieldByInternalName("test1") as SPFieldMultiChoice;//多选,栏:数据库对应字段名 foreach (var val in choice2.Choices) { } SPFieldChoice choice = list.Fields.GetFieldByInternalName("test2") as SPFieldChoice;//下拉列表 } }
获取列表视图,更改视图条件 

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            bool unsafeUpdate = web.AllowUnsafeUpdates;
                            web.AllowUnsafeUpdates = true;
                            SPView hdbView = web.GetViewFromUrl(web.Url + "/Lists/" + SpList.Dzkq.strListStatistic + "/" + SpList.Dzkq.strViewHdkq + ".aspx");//活动表 最近活动 视图
                            //考勤为活动考勤的数据列
                            hdbView.Query = "<Where><And><Eq><FieldRef Name=\"" + SpList.Dzkq.strFieldKqlx + "\" /><Value Type=\"Text\">" + SpList.Dzkq.strFieldValueCFkqlx2 + "</Value></Eq><Eq><FieldRef Name='" + SpList.Dzkq.strFieldCFTheme + "'/><Value Type='Lookup'>" + this.ddlSelectAct.Text + "</Value></Eq></And></Where>";
                            hdbView.Update();
                            web.AllowUnsafeUpdates = unsafeUpdate;
                        }
                    }

 

 

 

 

//插入数据到列表
SPSecurity.RunWithElevatedPrivileges(delegate()//提高权限 { try { using (SPSite site = new SPSite(SPContext.Current.Web.Url))//重新实例化对象,才能提高权限 { using (web = site.OpenWeb(Request["WebUrl"])) { web.AllowUnsafeUpdates = true; SPList list = web.Lists[“列表”]; SPListItem listItem = list.Items.Add();
SPFieldLookupValue value = new SPFieldLookupValue(){LookupId=1};
                            order[lookupFld.Id] = value.ToString();//= new SPFieldLookupValue("行id", “value”);
listItem[“单选”] = this.rdoMale.Checked ? "男" : "女"; SPFieldMultiChoiceValue smcv = new SPFieldMultiChoiceValue(); smcvRoel.Add(“”); 
listItem[“栏”]
= smcvRoel; spListItem["BusinessPage"] = new SPFieldUrlValue() { Url = "http://zhaoliu.com", Description = "赵六的个人主页" };//url
  spListItem["CustomerType"] = "钻石";
  spListItem["Owner"] = new SPFieldUserValue(spWeb, user1.ID, user1.Name);
SPUser user1=web.EnsureUser(“loginname”)
  spListItem["Sharers"] = new SPFieldUserValueCollection //用户或用户组
  {
      new SPFieldUserValue(spWeb, user1.ID, user1.Name),
      new SPFieldUserValue(spWeb, user2.ID, user2.Name),
      new SPFieldUserValue(spWeb, group1.ID, group1.Name)
  };
SPUser user=web.EnsureUser(@"i:0#.w|zgjyzx\lisi");//
i:0#.f|forms|zhangsan

SPFieldUser userField = list.Fields.GetFieldByInternalName("Author") as SPFieldUser;
SPFieldUserValue userFieldValue = userField.GetFieldValue("17;#张三") as SPFieldUserValue;表单验证添加用户 web.AllowUnsafeUpdates
= false; } } });
      
//上传图片
string filetoupload = this.fileuploadpictest.postedfile.filename; string url = string.empty; string documentlibraryname = "图库"; try { spsecurity.runwithelevatedprivileges(delegate() { using (spsite osite = new spsite(spcontext.current.web.url))// { using (spweb oweb = osite.openweb(request["站点"])) { oweb.allowunsafeupdates = true; if (!system.io.file.exists(filetoupload)) return; string extension = system.io.path.getextension(filetoupload); spdocumentlibrary mylibrary = oweb.lists[documentlibraryname] as spdocumentlibrary; boolean replaceexistingfiles = true; filestream filestream = file.openread(filetoupload); url = oweb.url.tostring() + "/" + myLibrary.EntityTypeName + "/" + datetime.now.tostring().replace("/", "").replace(":", "").replace(" ", "") + "." + extension; spfile spfile = mylibrary.rootfolder.files.add(url, filestream, replaceexistingfiles); spfile.update(); mylibrary.update(); oweb.update(); oweb.allowunsafeupdates = false; } }

 

如何给文档库创建文件夹和上传文件呢?
string title = @"我的文档库";
  SPList spList = spWeb.Lists[title];
  //创建一个文件夹的SPListItem对象
  SPListItem folderListItem = spList.AddItem(spList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "文件夹2");
  folderListItem.Update();
  //找到网站对应文件夹SPFolder对象
  SPFolder spFolder = spList.ParentWeb.GetFolder(folderListItem.UniqueId);
  bool allowUnsafeUpdates = spWeb.AllowUnsafeUpdates;//如果AllowUnsafeUpdates是False可能下面操作会有异常
  spWeb.AllowUnsafeUpdates = true;
  //在指定文件夹下添加文件
  spFolder.Files.Add(Path.GetFileName(@"C:\1.txt"), File.ReadAllBytes(@"C:\1.txt"));
  spWeb.AllowUnsafeUpdates = allowUnsafeUpdates;

 

要高效的批量执行增删改操作还是需要SPWeb对象的ProcessBatchData方法。命令语法请参考: http://msdn.microsoft.com/zh-CN/library/ms455433(v=office.12).aspx 、 http://msdn.microsoft.com/zh-cn/library/microsoft.sharepoint.spweb.processbatchdata.aspx 、 http://msdn.microsoft.com/zh-cn/library/cc404818.aspx 。下面代码是插入、修改和删除的例子,对于多个用户和组、超链接或图片还是使用的字符串拼接(用户和组用“;#”连接ID和显示名称,超链接或图片用空格+逗号+空格连接URL和描述),还有时间类型字段,要转换为ISO8601格式,可以调用SPUtility类的CreateISO8601DateTimeFromSystemDateTime方法创建( http://msdn.microsoft.com/zh-cn/library/ms197282(v=office.14).aspx )。

SPUser user1 = spWeb.EnsureUser(loginName1);
  SPUser user2 = spWeb.EnsureUser(loginName2);
  SPGroup group1 = spWeb.Groups[loginName3];
  string listId = @"3824b091-c7b8-409c-bcc0-7cce487d6b49";
  StringBuilder strBatchData = new StringBuilder(@"<?xml version=""1.0"" encoding=""UTF-8""?><Batch>");
  //命令头:
  string setListText = string.Format(@"<SetList Scope=""Request"">{0}</SetList>", listId);
  //插入数据:
  strBatchData.AppendFormat(@"<Method ID=""Insert,1"">{0}<SetVar Name=""ID"">New</SetVar><SetVar Name=""Cmd"">Save</SetVar>", setListText);
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "CustomerName", "蒋九");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "Gender", "男");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "EMail", "jiujiang@contoso.com");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "CellPhone", "13656435678");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "WorkAddress", "菜市口");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "Recency", SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddDays(-1)));
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "Frequency", "0.3");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "Monetary", "30000");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "BusinessPage", string.Format(@"{0} , {1}", "http://jiangjiu.com", "蒋九的个人主页"));
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "CustomerType", "青铜");
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "Owner", string.Format(@"{0};#{1}", user2.ID.ToString(), user2.Name));
  strBatchData.AppendFormat(@"<SetVar Name=""urn:schemas-microsoft-com:office:office#{0}"">{1}</SetVar>", "Sharers", string.Join(@";#", user1.ID.ToString(), user1.Name, user2.ID.ToString(), user2.Name, group1.ID.ToString(), group1.Name));
  strBatchData.Append("</Method>");
  //修改数据:
  string updateItemId = "2";
  strBatchData.AppendFormat(@"<Method ID=""Update,1"">{0}<SetVar Name=""ID"">{1}</SetVar><SetVar Name=""Cmd"">Save</SetVar><SetVar Name=""urn:schemas-microsoft-com:office:office#{2}"">{3}</SetVar></Method>", setListText, updateItemId, "CustomerName", "李四四");
  //删除数据:
  string deleteItemId = "3";
  strBatchData.AppendFormat(@"<Method ID=""Delete,1"">{0}<SetVar Name=""ID"">{1}</SetVar><SetVar Name=""Cmd"">Delete</SetVar></Method>", setListText, deleteItemId);
  //命令尾:
  strBatchData.Append(@"</Batch>");
  //执行:
  Console.WriteLine(spWeb.ProcessBatchData(strBatchData.ToString()));

 参考: http://www.tuicool.com/articles/ArUJbmN

posted on 2015-04-12 22:02  !无名之辈  阅读(261)  评论(0)    收藏  举报