AI教程网 - 未来以来,拥抱AI;新手入门,从AI教程网开始......

Python-docx操作集合

python-docx AI君 52℃

Python-docx是使用Python操作word文档的开源包,非常好用,详细操作参考官方文档

1.安装

pip install python-docx
#或者
easy_install python-docx
#或者
tar xvzf python-docx-{version}.tar.gz
cd python-docx-{version}
python setup.py install

2.使用

import os
from docx import Document #初始化对象
from docx.shared import Pt #定义像素大小
from docx.shared import Inches #定义英尺
from docx.oxml.ns import qn #定义style的

import cv2
import numpy as np
import io
import time



document = Document()
#插入标题
document.add_heading('Document Title', 0)
#自定义插入文字
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

#自定义字体类型和大小
paragraph = document.add_paragraph(line, style='Body Text 3')
document.styles['Body Text 3'].font.name = u'宋体'
document.styles['Body Text 3']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
paragraph.paragraph_format.line_spacing = Pt(12)

#其他类型
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

#插入图片-按照绝对路径
document.add_picture('monty-truth.png', width=Inches(1.25))

#插入图片 按照OpenCV读取的矩阵并转成的流

img=cv2.imread('logo.jpg')#假设img是从别的地方传来的矩阵类型图像

#将矩阵图像编码
img_encode = cv2.imencode('.jpg', img)[1]
#转为十六进制码
str_encode = data_encode.tostring()
#转为二进制流
cc = io.BytesIO(str_encode)
#直接添加进去
document.add_picture(cc,width=Inches(2.25))



#图表操作
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item.qty)
    row_cells[1].text = str(item.id)
    row_cells[2].text = item.desc
#下一页,相当于敲了Enter
document.add_page_break()

#保存文档
document.save('demo.docx')

作者:loovelj
原文链接:https://blog.csdn.net/loovelj/article/details/81225426

转载请注明:www.ainoob.cn » Python-docx操作集合

喜欢 (0)or分享 (0)