使用 python 操作 Word文档
调用 docx 库,操作Word模板,进行修改调整。
将 dict 内容填充到 Word 中
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 15:01:43 2020
@author: dujidan
"""
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
from docx.shared import RGBColor
from docx.enum.style import WD_STYLE_TYPE
def dict2table(docx_file, table_num, data_select_dict, out_docx_file):
document = Document(docx_file)
# 第 num 个表格
table = document.tables[table_num]
# 删除 行
del_row = table.rows[2]
del_row._element.getparent().remove(del_row._element)
# 循环将字典中的值,取出再逐行添加到 Word 中的表中
for row in range(len(data_select_dict['s_name_CN'])):
add_row_cells = table.add_row().cells # 新添加 行
#获取 字典 中的内容
g_name_CN = data_select_dict['g_name_CN'][row]
s_new_est_reads = data_select_dict['s_new_est_reads'][row]
# 计算百分数
if data_select_dict['s_fraction_total_reads'][row] != '.':
s_fraction_total_reads = str(round(float(data_select_dict['s_fraction_total_reads'][row]) * 100, 2)) + '%'
else:
s_fraction_total_reads = '0'
# 跳过前 docx table 中的 前 2 行
row = row + 2
# 进行表格的填充
run = table.cell(row, 0).paragraphs[0].add_run(g_name_CN + '\n')
run = table.cell(row, 0).paragraphs[0].add_run(g_name)
run.italic = True #斜体
run.font.color.rgb = RGBColor(255, 0, 0) #红色
# 居中对齐
table.cell(row, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
table.cell(row, 0).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
table.cell(row, 4).text = s_fraction_total_reads
table.cell(row, 4).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
table.cell(row, 4).paragraphs[0].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 保存 Word
document.save(out_docx_file)
if __name__ == '__main__':
input_file = 'input.xls'
data_select_dict = {'A': A}
docx_file = 'input.docx'
table_num = 5
out_docx_file = docx_file.replace('docx','new.docx')
dict2table(docx_file, table_num, data_select_dict, out_docx_file)