python word表格一些操作

数据格式(datas): 列表套列表
aa =[ [1,2,3,4,5],[6,7,8,9],[]…]

import os
import requests
import json
import datetime
from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT


def create_insert_word_table(datas, stday, etday, s):
    """创建word表格以及插入数据"""
    doc = Document()

    doc.styles['Normal'].font.name = 'Calibri'  # 是用来设置当文字是西文时的字体,
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')  # 是用来设置当文字是中文时的字体
    # doc.styles['Normal'].font.size = Pt(14)  # 设置所有文字字体大小为14

    distance = Inches(0.5)
    sec = doc.sections[0]  # sections对应文档中的“节”
    sec.left_margin = distance  # 以下依次设置左、右、上、下页面边距
    sec.right_margin = distance
    sec.top_margin = distance
    sec.bottom_margin = distance
    sec.page_width = Inches(11.7)  # 设置页面宽度
    # sec.page_height = Inches(9) # 设置页面高度

    # doc.add_heading() #  设置标题,但是不符合我的条件,只能试用下方p.add_run('我是文字')
    p = doc.add_paragraph()  # 添加段落
    p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 设置中央对齐
    run = p.add_run('我是文字')
    run.font.size = Pt(22)

    doc.add_paragraph()  # 添加空段落

    # 添加表格
    table = doc.add_table(rows=1, cols=10, style='Table Grid')
    table.style.name = 'Table Grid'
    table.style.font.size = Pt(14)
    table.rows[0].height = Cm(20)
    title = table.rows[0].cells
    title[0].text = '姓名'
    title[1].text = '1'
    title[2].text = '2'
    title[3].text = '3'
    title[4].text = '4'
    title[5].text = '5'
    title[6].text = '6 '
    title[7].text = '7'
    title[8].text = '8'
    title[9].text = '9'
    for i in range(len(datas)):
        cels = table.add_row().cells
        for j in range(len(datas[i])):
            # cels[j].text = str(datas[i][j])
            p = cels[j].paragraphs[0]
            p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 设置中央对齐
            p.add_run(str(datas[i][j]))
            ph_format = p.paragraph_format
            # ph_format.space_before = Pt(10)  # 设置段前间距
            # ph_format.space_after = Pt(12)  # 设置段后间距
            ph_format.line_spacing = Pt(40)  # 设置行间距
    doc.save('./files/项目总结.docx')

生成示例
在这里插入图片描述
可能出现的错误,[Errno 13] Permission denied: ‘./files/项目进展总结.docx’

是因为你打开文件未关闭,操作不了,关闭他就好了

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值