Python教程

python2.7 生成word,内容为表格

本文主要是介绍python2.7 生成word,内容为表格,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

# coding=utf-8
#风险提示报告生成
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm,Pt
doc = docx.Document()
p = doc.add_paragraph(u'风险提示报告', style='Intense Quote')
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
table_title = [u'序号',u'名称',u'部门',u'状态',u'是/否存在风险',u'整改时间',u'整改计划',u'涉及系统及成员行']
# 添加三行数据
table_data = [
                {'num':'1','name':'name1','dept':'dept1','status':'1','risk':'1','timer':'2021-01-01','plan':'1','bank':'qoshang1'},
                {'num':'2','name':'name2','dept':'dept1','status':'1','risk':'1','timer':'2021-01-01','plan':'1','bank':'qoshang1'},
                {'num':'3','name':'name3','dept':'dept1','status':'1','risk':'1','timer':'2021-01-01','plan':'1','bank':'qoshang1'}
             ]
table = doc.add_table(rows=1,cols=len(table_title), style='Table Grid') #创建带边框的表格
table.style.font.size=Pt(8)
hdr_cells = table.rows[0].cells
for i in range(len(table_title)):
    hdr_cells[i].text = table_title[i]
for i in range(len(table_data)):
    cells = table.add_row().cells
    cells[0].text = table_data[i].get('num','')
    cells[1].text = table_data[i].get('name','')
    cells[2].text = table_data[i].get('dept','')
    cells[3].text = table_data[i].get('status','')
    cells[4].text = table_data[i].get('risk','')
    cells[5].text = table_data[i].get('timer','')
    cells[6].text = table_data[i].get('plan','')
    cells[7].text = table_data[i].get('bank','')

doc.save('D:\\tmp.docx')

效果如下:


这篇关于python2.7 生成word,内容为表格的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!