Python 在Word中创建表格并填入数据、图片

在Word中,表格是一个强大的工具,它可以帮助你更好地组织、呈现和分析信息。本文将介绍如何使用Python在Word中创建表格并填入数据、图片,以及设置表格样式等。

Python Word库:

要使用Python在Word中创建或操作表格,需要先将Spire.Doc for Python这个第三方库安装到项目中.

复制代码
pip install Spire.Doc

示例代码1:使用Python在Word中创建表格并填充数据

复制代码
import math
from spire.doc import *
from spire.doc.common import *
 
# 创建Document对象
doc = Document()
 
# 添加一节
section = doc.AddSection()
 
# 创建一个表格
table = section.AddTable()
 
# 指定表格数据
header_data = ["商品名称", "单位", "数量", "单价"]
row_data = [ ["底板-1","件","20946","2.9"], 
                ["定位板-2","张","38931","1.5"], 
                ["整平模具-3","组","32478","1.1"], 
                ["后壳FD1042-4","组","21162","0.6"], 
                ["棍子-5","组","66517","1.2"]]
                
# 设置表格的行数和列数
table.ResetCells(len(row_data) + 1, len(header_data))
 
# 设置表格自适应窗口
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
 
# 设置标题行
headerRow = table.Rows[0]
headerRow.IsHeader = True
headerRow.Height = 23
headerRow.RowFormat.BackColor = Color.get_Orange()
 
# 在标题行填充数据并设置文本格式
i = 0
while i < len(header_data):
    headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    paragraph = headerRow.Cells[i].AddParagraph()
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    txtRange = paragraph.AppendText(header_data[i])
    txtRange.CharacterFormat.Bold = True
    txtRange.CharacterFormat.FontSize = 12
    i += 1
 
# 将数据填入其余各行并设置文本格式
r = 0
while r < len(row_data):
    dataRow = table.Rows[r + 1]
    dataRow.Height = 20
    dataRow.HeightType = TableRowHeightType.Exactly
    c = 0
    while c < len(row_data[r]):
        dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = dataRow.Cells[c].AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        txtRange =  paragraph.AppendText(row_data[r][c])
        txtRange.CharacterFormat.FontSize = 11
        c += 1
    r += 1
 
# 设置交替行颜色
for j in range(1, table.Rows.Count):
    if math.fmod(j, 2) == 0:
        row2 = table.Rows[j]
        for f in range(row2.Cells.Count):
            row2.Cells[f].CellFormat.BackColor = Color.get_LightGray()
 
# 保存文件
doc.SaveToFile("Word表格.docx", FileFormat.Docx2016)

以下示例通过Section.AddTable() 方法在Word文档中添加了一个表格,然后将列表中的数据填充到了指定的单元格。此外Spire.Doc for Python库还提供了接口设置单元格样式等。

输出结果:

代码示例2:使用Python在Word表格中插入图片

复制代码
from spire.doc import *
from spire.doc.common import *
 
inputFile = "表格示例.docx"
outputFile = "插入图片到表格.docx"
 
# 创建Document对象
doc = Document()
 
# 加载Word文档
doc.LoadFromFile(inputFile)
 
# 获取文档中第一个表格
table = doc.Sections[0].Tables[0]
 
# 将图片添加到指定单元格并设置图片大小
cell = table.Rows[1].Cells[1]
picture = cell.Paragraphs[0].AppendPicture("python.png")
picture.Width = 80
picture.Height = 80
 
cell = table.Rows[2].Cells[1]
picture = cell.Paragraphs[0].AppendPicture("java.jpg")
picture.Width = 80
picture.Height = 80
 
# 保存结果文件
doc.SaveToFile(outputFile, FileFormat.Docx)
doc.Close()
 

从以上代码可以看出,要在Word表格中插入图片,需要先获取指定的单元格,然后使用**TableCell.Paragraphs[index].AppendPicture()**方法插入图片。

输出结果:


Spire.Doc for Python库还支持对Word中的表格进行其他操作,如添加、删除复制行或列、合并或拆分单元格等。更多示例demo可查看:

https://www.e-iceblue.cn/docforpython/spire-doc-for-python-program-guide-content.html

对于水印问题,可以点击申请临时授权移除,或者发送邮件到sales@e-iceblue.com。

相关推荐
B站计算机毕业设计之家7 分钟前
AI大模型:基于大数据动漫数据分析可视化系统 漫画 番剧 知音漫客 Django框架 requests爬虫 大数据毕业设计(建议收藏)✅
大数据·人工智能·爬虫·python·数据分析·django·动漫
七夜zippoe15 分钟前
设计模式在Python中的优雅实现:从新手到专家的进阶指南
开发语言·python·设计模式·性能优化·pythonic
有味道的男人17 分钟前
京东关键词搜索商品列表的Python爬虫实战
开发语言·爬虫·python
YJlio22 分钟前
PsPing 学习笔记(14.10):常见错误与排错思路——从“不可达”到“端口拒绝”
开发语言·笔记·python·学习·django·pdf·pygame
Mr.Lee jack37 分钟前
【torch.compile】PyTorch FX IR 与 Inductor IR 融合策略深度剖析
人工智能·pytorch·python
Rabbit_QL44 分钟前
【Pytorch使用】Sequential、ModuleList 与 ModuleDict 的设计与取舍
人工智能·pytorch·python
Data_agent1 小时前
HOOBUY 模式淘宝 1688 代购系统搭建指南
大数据·python
AAA简单玩转程序设计1 小时前
Python 数据类型 “冷知识”:这些坑你踩过几个?
python
Zoey的笔记本1 小时前
安全、可控、可定制:构建企业级知识库,开源在线协作文档的深度应用
java·python·低代码
纪伊路上盛名在1 小时前
Chap1:Neural Networks with NumPy(手搓神经网络理解原理)
python·深度学习·神经网络·机器学习·numpy·计算生物学·蛋白质