我正在使用 python-docx 库开发 Python 3 程序。它会打开现有的 .docx 文件并用列表中的值替换
[[FRUIT_ITEM]]
占位符。这可以是 1 到多个项目,每个项目都应该有自己的项目符号点(这意味着我必须为每个条目添加一个新段落,然后将其格式化为项目符号)。
结果有效,但由于某些奇怪的原因,模板中现有的项目符号点(通过单击“创建项目符号列表”按钮创建)比 python-docx 添加的项目符号点稍小。
2023年8月3日更新: 当我从模板中完全删除现有的第一个项目符号点,并让 python-docx 使用下面的
create_list
代码处理所有项目符号的创建时,也会发生同样的事情。第一个将比其余的小几个像素,这使得这更加奇怪!
原模板:
结果:
对于每个段落及其包含的文本“行”,我指定了文档其余部分使用的相同字体类型 (Arial) 和大小 (10Pt)。用于为段落对象创建列表的代码是:
def create_list(paragraph):
list_type = "1" # apparently the ID for unordered lists in Word?
p = paragraph._p
pPr = p.get_or_add_pPr()
numPr = OxmlElement('w:numPr')
numId = OxmlElement('w:numId')
numId.set(qn('w:val'), list_type)
numPr.append(numId)
pPr.append(numPr)
并将其插入到当前段落之后(请注意,我正在使用“列表段落”,因为由于某种原因,其他线程中建议的“列表项目符号”在我的文档样式中不存在):
def insert_paragraph_after(paragraph, text, style="List Paragraph"):
new_p = OxmlElement("w:p")
paragraph._p.addnext(new_p)
new_para = Paragraph(new_p, paragraph._parent)
if text:
new_para.add_run(text)
new_para.style = style
for run in new_para.runs:
run.font.size = Pt(10)
run.font.name = 'Arial'
return new_para
这是调用上述两者的代码:
template_variables = {
"[[FRUIT_ITEM]]": ['Apple', 'Banana', 'Pear', 'Pineapple'],
"[[CHEESE_TYPE]]": ['mild', 'sharp']
}
template_document = Document("my_word_file.docx")
for variable_key, variable_value in template_variables.items():
for paragraph in template_document.paragraphs:
if variable_key == "[[FRUIT_ITEM]]":
if variable_key in paragraph.text:
inline = paragraph.runs
for item in inline:
if variable_key in item.text:
# Replace the existing bullet point with the first fruit
item.text = item.text.replace(variable_key, variable_value[0])
# Add new lines for any remaining fruit in the list, skipping the first
if len(variable_value) > 1:
for fruit in variable_value[1:]:
new_bullet = insert_paragraph_after(paragraph, fruit)
create_list(new_bullet)
我相信解决方案在于新项目符号继承现有项目符号的风格,但我不知道格式差异源自何处。在 Word 中检查生成的文件时,两者的字体大小和项目符号样式相同,尽管它们在视觉上明显不同。
预先感谢您为挽救我的理智所做的任何尝试!