python把结果保存到word

发布时间 2023-04-09 14:16:22作者: 技术改变命运Andy

开始

Python操作Word用到了模块python-docx,它把word分割成很多段落,如下结构:

document> paragraph / picture > run

其中document是整个文档对象,
paragraph是段落
run是段落下的按照样式来分割的小块,每块有独立的样式。

安装方式

pip install python-docx

示例

from docx import Document
from docx.shared import Inches

document = Document()
document.add_heading('添加标题,并设置级别,范围:0 至 9,默认为1', 0)
p = document.add_paragraph('添加段落,文本可以包含制表符(\\t)、换行符(\n)或回车符(\\r)等')
p.add_run('在段落后面追加文本,并可设置样式 加粗').bold = True
p.add_run(' 其他 ')
p.add_run('斜体。').italic = True

document.add_heading('头部,第一级', level=1)
document.add_paragraph('缩进引用', style='Intense Quote')
document.add_paragraph('第一个无序列表项', style='List Bullet')
document.add_paragraph('第二个无序列表项', style='List Bullet')
document.add_paragraph('第一个有序列表项', style='List Number')
document.add_paragraph('第二个有序列表项', style='List Number')
#添加图片
document.add_picture('1585616688980.jpg', width=Inches(1.25))

#添加表格:一行三列
records = (
    (3, '产品一', '产品一的描述'),
    (7, '产品二', '产品二的描述'),
    (4, '产品三', '产品三的描述')
)

# 表格样式参数可选:
# Normal Table
# Table Grid
# Light Shading、 Light Shading Accent 1 至 Light Shading Accent 6
# Light List、Light List Accent 1 至 Light List Accent 6
# Light Grid、Light Grid Accent 1 至 Light Grid Accent 6
table = document.add_table(rows=1, cols=3, style='Light Shading Accent 2')
#获取第一行的单元格列表
hdr_cells = table.rows[0].cells
#下面三行设置上面第一行的三个单元格的文本值
hdr_cells[0].text = 'ID'
hdr_cells[1].text = '产品'
hdr_cells[2].text = '描述'
for id, product, desc in records:
    #表格添加行,并返回行所在的单元格列表
    row_cells = table.add_row().cells
    row_cells[0].text = str(id)
    row_cells[1].text = product
    row_cells[2].text = desc

document.add_page_break()

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

python合并word

安装依赖包

pip install python-docx
pip install docxcompose

代码

from docx import Document
import os
from docxcompose.composer import Composer

# 合并word
def merge_word():
    merge_file = "./7h_merge_article/book1.docx"

    file_path = './7h_article/'
    files = os.listdir(file_path)[0:6]
    print(files)

    new_document = Document()
    composer = Composer(new_document)
    for file in files:
        composer.append(Document(file_path+file))
    composer.save(merge_file)