python写word属性

1 如何使用python-docx 读取word文档属性的详细信息里面的公司或者是自定义属性,
核心属性里面没有这一项
CoreProperties' object has no attribute 'company'
2 如何使用python-docx 修改现有的自定义属性和word文档属性的详细信息里面的属性。

1、使用docx.opc.constants中的CUSTOM_PROPERTIES_NS_URI库,大概的代码如下(文档和库请您自行导入)

custom_properties = document.core_properties.custom_properties
for prop in custom_properties:
    print(prop.name, prop.value)

2、要修改现有的自定义属性,可以使用CustomPropertiesPart这个库,大概代码如下

from docx import Document
from docx.opc.constants import CUSTOM_PROPERTIES_NS_URI
from docx.oxml import parse_xml
from docx.oxml.ns import qn
from docx.opc.propertiess import CustomProperties
from docx.opc.part import PartFactory

def set_custom_property(document, name, value):
    custom_document_property = document.core_properties \
        .custom_properties \
        .property_of(name)
    if custom_document_property is None:
        # 属性不存在,则创建
        custom_document_property = document.core_properties.custom_properties \
            .add_property(name, value)

    # 设置属性值
    custom_document_property.value = value

path_to_word_file = 'path/to/word/file'
document = Document(path_to_word_file)

# 修改自定义属性
set_custom_property(document, 'my_property', 'new value')

# 保存修改后的文档
document.save('path/to/word/file')

要修改word文档属性的详细信息里面的属性,您可以使用DocumentProperties 类,代码如下

from docx import Document
from docx.opc.constants import CORE_PROPERTIES_NS_URI

def set_property(document, name, value):
    core_properties = document.core_properties
    setattr(core_properties, name, value)

path_to_word_file = 'path/to/word/file'
document = Document(path_to_word_file)

# 修改属性
set_property(document, 'company', 'new value')

# 保存修改后的文档
document.save('path/to/word/file')