读取word中的表格
偶尔间需要从word中读取表格数据。差别于excel,word中表格的对象属性是Table。
示例文档如下:
读取效果:
- 行: 6 , 列: 3
- ['物料', '数量', '单价']
- ['车轮', '2', '100']
- ['坐垫', '1', '20']
- ['车把', '1', '5']
- ['车锁', '1', '13']
- ['总加', '138']
复制代码 注意到表格末了一行有合并的单元格,目前的读取方法对于合并的单元格按照1个列单元读取!
代码:
- [/code] [code]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中带有合并单元格的表格
- 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,碰到合并的单元格会报错。
运行结果:
- 有效单元格个数: 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文档中插入一个表格,并写入脚本的内容。
- [/code] [code]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
复制代码
插入第二个表格
- [/code] [code]#插入第二个表格
- 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
复制代码
插入效果:
第二个表格插入效果,看起来和第一个连在一起了
调解一下,在第二个表格背面插入一个新的空行,拉开一段的间隔。
- [/code] [code]#插入第二个表格
- 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
复制代码
遍历文档中的表格
- for table in doc.Tables:
- print(table.Row(1).Cells(1).Range.Text) # 打印每个表格中左上角单元格的内容
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |