使用 python 操作 Word文档

使用 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值