python读word中的表格和插入表格

读取word中的表格

有时候需要从word中读取表格数据。不同于excel,word中表格的对象属性是Table。

示例文档如下:

读取效果:

复制代码
行: 6 , 列: 3
['物料', '数量', '单价']
['车轮', '2', '100']
['坐垫', '1', '20']
['车把', '1', '5']
['车锁', '1', '13']
['总加', '138']

注意到表格最后一行有合并的单元格,目前的读取方法对于合并的单元格按照1个列单元读取!

代码:

复制代码
python 复制代码
import win32com.client as win32
from win32com.client import constants
import os

doc_app = win32.gencache.EnsureDispatch('Word.Application')#打开word应用程序
doc_app.Visible = True
curr_path = os.getcwd()
file_path = r'%s\带表格文档.docx'%curr_path
doc = doc_app.Documents.Open(file_path)

table = doc.Tables(1)
print('行:',table.Rows.Count, ', 列:', table.Columns.Count)
for row in table.Rows:#遍历表格每行
	info = []
	for cell in row.Cells:#遍历每行中的表格,即有效列
		info.append(cell.Range.Text[:-2])
	print(info)

读取word中带有合并单元格的表格

python 复制代码
print('有效单元格个数:',table.Range.Cells.Count)
for cell in table.Range.Cells:
	print(cell.RowIndex, ',', cell.ColumnIndex,',',cell.Range.Text[:-2])

word的对象中,无法直接判断单元格是否列合并或者行合并的。可以间接通过table.Cells来访问有效的单元格。如果访问cell.Row或者cell.Column,遇到合并的单元格会报错。

运行结果:

python 复制代码
有效单元格个数: 20
1 , 1 , 
1 , 2 , 物料
1 , 3 , 数量
1 , 4 , 单价
2 , 1 , 零件
2 , 2 , 车轮
2 , 3 , 2
2 , 4 , 100
3 , 2 , 坐垫
3 , 3 , 1
3 , 4 , 20
4 , 2 , 车把
4 , 3 , 1
4 , 4 , 5
5 , 2 , 车锁
5 , 3 , 1
5 , 4 , 13
6 , 1 , 
6 , 2 , 总加
6 , 3 , 138

在word中插入表格

脚本效果:

脚本实现的内容:在新的word文档中插入一个表格,并写入脚本的内容。

复制代码
python 复制代码
import win32com.client as win32
from win32com.client import constants
import os

doc_app = win32.gencache.EnsureDispatch('Word.Application')#打开word应用程序
doc = doc_app.Documents.Add()
doc_app.Visible = True

last_parag = doc.Paragraphs.Last
# 创建新的表格
table = doc.Tables.Add(Range=last_parag.Range, NumRows=3, NumColumns=4)
# 设置表格边框内外线
table.Borders.InsideLineStyle = constants.wdLineStyleSingle 
table.Borders.OutsideLineStyle = constants.wdLineStyleDouble 

#写入表格
cnt=0
for row in table.Rows:#遍历表格每行
	for cell in row.Cells:#遍历每行中的表格,即有效列
		cell.Range.Text = cnt
		cnt += 1 

插入第二个表格

复制代码
python 复制代码
#插入第二个表格
last_parag = doc.Paragraphs.Last
table2 = doc.Tables.Add(Range=last_parag.Range, NumRows=3, NumColumns=4)
table2.Borders.InsideLineStyle = constants.wdLineStyleSingle 
table2.Borders.OutsideLineStyle = constants.wdLineStyleDouble 

插入效果:

第二个表格插入效果,看起来和第一个连在一起了

调整一下,在第二个表格后面插入一个新的空行,拉开一段的距离。

复制代码
python 复制代码
#插入第二个表格
doc.Paragraphs.Add()# 插入新的一行
last_parag = doc.Paragraphs.Last #指向最后一行(刚插入的那一行)
table2 = doc.Tables.Add(Range=last_parag.Range, NumRows=3, NumColumns=4)
table2.Borders.InsideLineStyle = constants.wdLineStyleSingle 
table2.Borders.OutsideLineStyle = constants.wdLineStyleDouble 

遍历文档中的表格

python 复制代码
for table in doc.Tables:
    print(table.Row(1).Cells(1).Range.Text) # 打印每个表格中左上角单元格的内容
相关推荐
AI探索者7 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者7 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh9 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅9 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽10 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时13 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿16 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python