根据所创建Item的title自动实现分配到不同的folder下

本文介绍了一个使用事件接收器实现的文件移动功能,该功能通过XML配置文件来判断并移动列表中的文件到指定目录下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

using System;

using System.Security.Permissions;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Security;

using Microsoft.SharePoint.Utilities;

using Microsoft.SharePoint.Workflow;

 

namespace EventReceiverForMoveItem

{

    /// <summary>

    /// List Item Events

    /// </summary>

    public class EventReceiver1 : SPItemEventReceiver

    {

        /// <summary>

        /// An item is being added.

        /// </summary>

        public override void ItemAdded(SPItemEventProperties properties)

        {

            SPSecurity.RunWithElevatedPrivileges(delegate

            {

//读取XML文件,可以通过配置来选择通过item的filed判断。//XML文件       <configs><Filed>oneChoice</Filed><SecondFiled>twoChoice</SecondFiled>

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                doc.Load(@"c:\AvePointEvent.config");

                System.Xml.XmlNode node = doc.SelectSingleNode("/configs/Filed");

                string filed = node.InnerText;

                System.Xml.XmlNode nodeSecond = doc.SelectSingleNode("/configs/SecondFiled");

                string filedSecond = nodeSecond.InnerText;

                SPWeb web = properties.Web;

                SPList list = properties.List;

                SPListItem item = properties.ListItem;

                SPFile file = web.GetFile(item.Url);

                string url = string.Empty;

                foreach (SPListItem folder in list.Folders)

                {

                    string tempItemFiled = item[filed].ToString().Replace("&", ""); 

                    if (folder.Name.Equals(tempItemFiled, StringComparison.CurrentCultureIgnoreCase))

                    {

                        if (!filedSecond.Equals(string.Empty))

                        {

                            string tempSecondFiled = item[filedSecond].ToString().Replace("&", "");

                            url = web.Url + "/" + folder.Url + "/" + tempSecondFiled + "/" + file.Name;

                            break;

                        }

                        else

                        {

                            url = web.Url + "/" + folder.Url + "/" + file.Name;                       

                            break;

                        }

                    }

                }

                try

                {

                    file.MoveTo(url, SPMoveOperations.Overwrite);

                }

                catch (Exception ex)

                {

                    url = web.Url + "/" + list.RootFolder.Url + "/UnMatch/" + file.Name;

                    file.MoveTo(url, SPMoveOperations.Overwrite);

                }

                web.Update();

                base.ItemAdded(properties);

            });

        }

 

    }

}

 

 


 

 

import tkinter as tk from tkinter import filedialog from pathlib import Path from docx import Document from openpyxl import Workbook from collections import OrderedDict def has_image(cell): """通过XML检查单元格是否包含图片(改进的XPath查询)""" xpath_expr = ( ".//*[local-name()='pic' and " "namespace-uri()='http://schemas.openxmlformats.org/drawingml/2006/picture']" ) pic_elements = cell._element.xpath(xpath_expr) return len(pic_elements) > 0 def process_table(table): """解析表格数据,按行顺序提取非空文本(跳过含图片单元格)""" data = [] for row in table.rows: for cell in row.cells: if has_image(cell): continue # 改进点1:删除所有空格(包含中间和首尾) text = cell.text.replace(" ", "").strip() # 先替换中间空格再去除首尾空白 if text: # 跳过空单元格 data.append(text) return data def save_to_excel(data, output_path): """保存数据到Excel,每行对应一个文件""" wb = Workbook() ws = wb.active for row_idx, row_data in enumerate(data, 1): for col_idx, value in enumerate(row_data, 1): ws.cell(row=row_idx, column=col_idx, value=value) wb.save(output_path) def process_docx_files(): root = tk.Tk() root.withdraw() folder_path = filedialog.askdirectory(title="请选择包含docx文件的文件夹") if not folder_path: print("操作已取消") return all_data = [] total_files = 0 processed_files = 0 # 按文件名排序处理文件 docx_files = sorted(Path(folder_path).glob("*.docx"), key=lambda x: x.name) for docx_path in docx_files: total_files += 1 file_data = [] try: doc = Document(docx_path) for table in doc.tables: table_data = process_table(table) file_data.extend(table_data) # 改进点2:行内数据去重(保持原始顺序) seen = set() unique_data = [] for item in file_data: if item not in seen: seen.add(item) unique_data.append(item) all_data.append(unique_data) processed_files += 1 print(f"已处理:{docx_path.name}") except Exception as e: print(f"处理失败:{docx_path.name} - {str(e)}") if not all_data: print("未找到有效数据") return output_path = Path(folder_path) / "表格数据汇总结果.xlsx" try: save_to_excel(all_data, output_path) print("\n处理完成!") print(f"总文件数:{total_files}") print(f"成功处理:{processed_files}") print(f"生成行数:{len(all_data)} 行") print(f"结果文件:{output_path}") except Exception as e: print(f"保存失败:{str(e)}") if __name__ == "__main__": process_docx_files() input("按回车键退出...")请继续改进代码,加上能够从docx单元格中获取图片并存入xlsx中的功能
03-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值