在Python中,你可以使用python-docx库来向Word文档中插入表格并设置表格边框。首先,确保你已经安装了python-docx库。如果没有,你可以使用pip来安装
pip install python-docx
以下代码是代码示例
from enum import Enum
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT
import json
class EnumTagType(Enum):
'''
报告标签类型
'''
# 图片
image = 0
# 文本
text = 1
# 表格
table = 2
class Report:
'''
报告数据类
'''
# 标签名称
tag_name = ''
tag_type = EnumTagType.text
# 值 文本时为 文本字符串,图片时为 图片绝对路径 表格时 为表格数据 json格式
tag_value = ''
def __init__(self):
self.tag_name = ''
self.tag_type = EnumTagType.text
self.tag_value = ''
def __init__(self,tag_name:str,tag_type:EnumTagType,tag_value:str):
self.tag_name = tag_name
self.tag_type = tag_type
self.tag_value = tag_value
class Reports:
'''
报告数据集合
'''
# Report类集合
tags = []
def __init__(self):
self.tags = []
def replace_tag_with_table(doc, tag, data):
'''
将word中的标签替换为表格
:param doc: 文档 Document
:param tag: 标签 string
:param data: 表格数据 第一个数组为表头 [['A', 'B', 'C'], ['见附件是垃圾', '2', '3'], ['4', '5', '6']]
:return: 无
'''
for paragraph in doc.paragraphs:
if tag in paragraph.text:
# 创建表格
table = doc.add_table(rows=len(data), cols=len(data))
for i, row in enumerate(data):
for j, cell in enumerate(row):
table.cell(i, j).text = cell
# 替换段落中的标签为表格
paragraph.text = ''
paragraph._p.addnext(table._tbl)
for i, row in enumerate(data):
for j, cell in enumerate(row):
cell_1 = table.cell(i, j)
# 设置段落居中
cell_1.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 设置文本居中
for paragraph in cell_1.paragraphs:
for run in paragraph.runs:
#run._element.rPr.rFonts.set(qn('w:eastAsia'), 'SimSun') # 设置中文字体为宋体,根据需要调整
run.font.bold = i == 0 # 只加粗表头
def replace_text_in_doc(doc, tag, new_text):
'''
将制定的标签替换为 制定文本,暂不支持多个段落
:param doc: 文档 Document
:param tag: 标签 string
:param new_text: 文本内容
:return: 无
'''
# 遍历文档中的每个段落
for para in doc.paragraphs:
# 如果段落中包含旧文本,则替换为新文本
if tag in para.text:
inline = para.runs
for i in range(len(inline)):
if tag in inline[i].text:
text = inline[i].text.replace(tag, new_text)
inline[i].text = text
def insert_image_at_tag(doc, tag, image_path):
'''
将word中 指定标签替换为制定路径的图片
:param doc:文档 Document
:param tag:标签 string
:param image_path: 图片路径 绝对路径
:return:
'''
# 标记是否找到标签
found_tag = False
# 遍历文档中的每个段落
for para in doc.paragraphs:
# 检查段落文本是否包含标签
if tag in para.text:
found_tag = True
para.text = ''
# 在标签的段落之后插入图片
run = para.add_run() # 创建一个新的run对象来添加图片
run.add_picture(image_path, width=Inches(1.25)) # 插入图片,并设置宽度
# 设置段落的对齐方式为居中
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 插入完成,退出循环
break
# 检查是否找到标签
if not found_tag:
print(f"标签 '{tag}' 在文档中未找到。")
return
def main_report(doc_path,reports,file_path):
'''
将word中的标签替换为指定 内容的主函数 目前支持 图片、文本(暂不支持一个标签替换多个段落)、表格
:param doc_path: word 模板文档路径
:param reports: 标签和要替换内容的集合 []
:param file_path: word保存之后的路径
:return: 是否成功
'''
if reports is None or len(reports) <=0:
return False,'标签集合为空'
try:
# 打开word
# 加载Word文档
doc = Document(doc_path)
# 循环所有标签
for report in reports:
if report.tag_type == EnumTagType.text:
replace_text_in_doc(doc,report.tag_name,report.tag_value)
elif report.tag_type == EnumTagType.image:
insert_image_at_tag(doc,report.tag_name,report.tag_value)
elif report.tag_type == EnumTagType.table:
tab_data = json.loads(report.tag_value)
replace_tag_with_table(doc,report.tag_name,tab_data)
doc.save('modified_' + file_path)
except Exception as ex:
return False,f'word替换标签失败:{ex.args}'
return True,'word生成成功'
reports = []
data = [['A', 'B', 'C'], ['见附件是垃圾', '2', '3'], ['4', '5', '6']]
datajson = json.dumps(data)
report = Report(tag_name="<<text>>",tag_type=EnumTagType.text,tag_value="这是一个软件说明文档")
report1 = Report(tag_name="<<table>>",tag_type=EnumTagType.table,tag_value=datajson)
report2 = Report(tag_name="<<image>>",tag_type=EnumTagType.image,tag_value='image.jpg')
reports.append(report)
reports.append(report1)
reports.append(report2)
print(main_report("your_file.docx",reports,"modified_your_file.docx"))
word中的标签内容如下图所示