Python-docx,修改word编辑时间总计、创建时间、上次修改时间、作者、上次修改者、备注

avatar
作者
猴君
阅读量:0

Python版本3.9,Python-docx版本1.1.2

修改下图中红框内的信息

创建时间、上次修改时间、作者、上次修改者、备注,这些都有接口,调用

import docx from docx import Document from docx.oxml.ns import qn from docx.shared import Inches, RGBColor, Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml.ns import nsdecls from docx.oxml import parse_xml from datetime import datetime  doc_1 = Document() doc_1.core_properties.author = 'Administrator' #作者 doc_1.core_properties.comments = '' #备注 doc_1.core_properties.last_modified_by = 'Administrator' #上次修改者 doc_1.core_properties.created = datetime(2024, 7, 10, 12, 0, 0) #创建时间 doc_1.core_properties.modified =datetime(2024, 5, 10, 12, 0, 0) #上次修改时间  doc_1.save(r'测试文件.docx')

只有编辑时间总计,需要更改word里面得app.xml文件,

<TotalTime>0</TotalTime>,这个是我原始的编辑时间总计,如果不是0的话可以考虑用正则匹配一下

<TotalTime>200</TotalTime>,中间这个200,就是修改成200分钟。

import os import zipfile import time from io import BytesIO  # 原始文件名 original_file = '测试文件.docx' # 临时文件名 temp_file = '测试文件.zip' # 新文件名 new_file = '测试文件.docx'  # 修改文件后缀名为 .zip os.rename(original_file, temp_file)  # 修改 app.xml 文件 with zipfile.ZipFile(temp_file, 'r') as zip_ref, zipfile.ZipFile(new_file, 'a') as new_zip_ref:     for item in zip_ref.infolist():         buffer = zip_ref.read(item.filename)         if item.filename == 'docProps/app.xml':             # 修改编辑时长             xml_str = buffer.decode('utf-8').replace('<TotalTime>0</TotalTime>', '<TotalTime>200</TotalTime>')             new_zip_ref.writestr(item, xml_str.encode('utf-8'))         else:             new_zip_ref.writestr(item, buffer)  # 关闭 zip 文件 zip_ref.close() new_zip_ref.close()  # 删除临时文件 os.remove(temp_file)  # 新文件名改回为原始文件名 os.rename(new_file, original_file)

打开测试文件,就可以看到已经成功了

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!