Excel数据导入到Sharepoint List
这个功能是从XML中读取需要导入到Sharepoint List的列名字,然后把Excel中对应的数据导入到Sharepoint List中。基本原理,把Excel中数据临时放到Datatable中,然后查看文件夹是否存在,如果要导入的文件夹已经存在,则清空当前文件夹,放到最新数据。如果没有,遍历Datatable,一次存放到导入的list中,顺便保存一份到本地。
1. 准备工具
服务器上需要安装Excel的组件AccessDatabaseEngine
http://www.microsoft.com/en-us/download/details.aspx?id=13255
2.代码
Common com = new Common(); public ImportExcelToList() { } private string _TelephoneList; [Personalizable(true)] [WebBrowsable(true)] [WebDisplayName("Telephone List Name")] [DefaultValue("Telephone")] public string TelephoneList { set { _TelephoneList = value; } get { return _TelephoneList; } } protected override void OnInit(EventArgs e) { base.OnInit(e); InitializeControl(); } protected void Page_Load(object sender, EventArgs e) { } protected void btn_upload_Click(object sender, EventArgs e) { try { if (this.upload_Excel.HasFile) { List<string> lis = com.getAppManager("Telephone"); string fileName = "Telephone_" + System.DateTime.Now.ToString("yyyyMMddhhmmss"); string destiation =Constants.file_TelephoneDestination + fileName + ".xlsx"; this.upload_Excel.SaveAs(destiation); ImportExcel(lis, destiation, TelephoneList); } else { lb_error.Text = "Please choose telephone excel file to upload, in sheet which name is 'Date'."; } } catch (Exception ex) { lb_error.Text = ex.Message; } } private void CreateFolderInList(string folderName, SPList list,SPWeb web) { try { //Check if the Folder is already available in the list SPQuery query = new SPQuery(); query.Query = "<Where><And><Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq><Eq><FieldRef Name='FSObjType'/><Value Type='Lookup'>1</Value></Eq></And></Where>"; query.ViewAttributes = "Scope=\"RecursiveAll\""; //Retrieve the items based on Query SPListItemCollection items = list.GetItems(query); //Item count is "0" if the folder does not exist if (items.Count == 0) { SPListItem folderItem = list.AddItem(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder); folderItem["Title"] = folderName; folderItem.Update(); //return folderItem.Url; } else { com.cleanListData(list, folderName,web); } } catch (Exception ex) { lb_error.Text = ex.Message; } } /// <summary> /// /// </summary> /// <param name="l">config file</param> /// <param name="filePath">Excel path</param> /// <param name="listName">list name</param> /// <param name="folder">list folder</param> private void ImportExcel(List<string> l, string filePath, string listName) { DataTable dt = ExcelToDS(filePath); string folder = dt.Rows[0]["Month"].ToString(); using (SPSite spSite =new SPSite(SPContext.Current.Web.Url)) { using (SPWeb spWeb = spSite.OpenWeb()) { spWeb.AllowUnsafeUpdates = true; SPList list = spWeb.Lists[listName]; CreateFolderInList(folder, list, spWeb); foreach (DataRow row in dt.AsEnumerable()) { //add item to list folder SPListItem spListItem = list.Items.Add(list.RootFolder.SubFolders[folder].ServerRelativeUrl, SPFileSystemObjectType.File); for (int i = 0; i < l.Count; i++) { string colName = l[i]; if (colName != "All") { spListItem[colName] = row[i]; } else { } } spListItem.Update(); } spWeb.AllowUnsafeUpdates = false; } } } /// <summary> /// get datatable from sheet Data /// </summary> /// <param name="Path"></param> /// <returns></returns> public DataTable ExcelToDS(string Path) { DataTable dt = new DataTable(); string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; /// strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'"; SPSecurity.RunWithElevatedPrivileges(delegate() { OleDbConnection conn = new OleDbConnection(strConn); try { if (conn.State != ConnectionState.Open) conn.Open(); string strExcel = "select * from [Data$] where `Line` Is Not Null"; OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, conn); adapter.Fill(dt); } catch (Exception ex) { lb_error.Text = ex.Message; } finally { if (conn.State != ConnectionState.Closed) conn.Close(); } }); return dt; }
Common中的方法
/// <summary> /// Get list from xml configuration /// </summary> /// <param name="strListId"></param> /// <returns></returns> public List<string> getAppManager(string strListId) { List<string> FieldList = new List<string>(); XElement root = XElement.Load(Constants.xml_ImportList); IEnumerable<XElement> address = from el in root.Elements("listId") where (string)el.Attribute("id").Value == strListId select el; foreach (XElement el in address) { foreach (XNode node in el.Nodes()) { XElement nod = (XElement)node; string FieldName = nod.Value; FieldList.Add(FieldName); } } return FieldList; } public void cleanListData(SPList list, string folderName, SPWeb web) { SPQuery query = new SPQuery(); query.Query = string.Format(@"<Where> </Where> "); query.ViewAttributes = "Scope=\"Recursive\""; if (!string.IsNullOrEmpty(folderName)) { SPFolder folder = list.RootFolder.SubFolders[folderName]; query.Folder = folder; } SPListItemCollection items = list.GetItems(query); StringBuilder sbDelete = new StringBuilder(); sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>"); foreach (SPListItem item in items) { sbDelete.Append("<Method>"); sbDelete.Append("<SetList Scope=\"Request\">" + list.ID + "</SetList>"); sbDelete.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>"); sbDelete.Append("<SetVar Name=\"Cmd\">Delete</SetVar>"); sbDelete.Append("</Method>"); } sbDelete.Append("</Batch>"); web.ProcessBatchData(sbDelete.ToString()); }
XML
<?xml version="1.0" encoding="utf-8"?> <lists> <listId id="Telephone"> <field>Month</field> <field>Line</field> <field>Phone Type</field> </listId> </lists>