1 如何使用python-docx 读取word文档属性的详细信息里面的公司或者是自定义属性,核心属性里面没有这一项
2 如何使用python-docx 修改现有的自定义属性。
读取Word文档属性
from docx import Document
# 打开Word文档
doc = Document('your_document.docx')
# 读取核心属性
core_props = doc.core_properties
company = core_props.company # 公司属性
custom_props = core_props.custom_properties # 自定义属性
# 输出属性值
print("公司属性:", company)
print("自定义属性:")
for prop in custom_props:
print(prop)
# 关闭文档
doc.close()
修改现有的自定义属性
from docx import Document
from docx.oxml import ns
from docx.oxml import register_element
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
# 定义自定义属性的XML命名空间
CUSTOM_NAMESPACE = "{custom_namespace_uri}"
# 注册自定义属性的XML元素
register_element("custom-properties", CUSTOM_NAMESPACE)
register_element("property", CUSTOM_NAMESPACE)
# 打开Word文档
doc = Document('your_document.docx')
# 获取或创建自定义属性的XML元素
custom_properties_elm = doc.core_properties.element.get_or_add_custom_properties()
# 修改现有的自定义属性
for prop in custom_properties_elm:
if prop.attrib.get(ns.qn('name')) == "Your_Property_Name":
prop.attrib[ns.qn('value')] = "New_Property_Value"
# 保存修改后的文档
doc.save('modified_document.docx')
# 关闭文档
doc.close()
楼上,不好使啊,core_props里面没有company 啊,CoreProperties' object has no attribute 'company'
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')
document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'first item in ordered list', style='List Number'
)
document.add_picture('monty-truth.png', width=Inches(1.25))
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
document.add_page_break()
document.save('demo.docx')