python读取word指定内容_python读取word 中指定位置的表格及表格数据
1.Word文檔如下:
2.代碼
# -*- coding: UTF-8 -*-
from docx import Document
def readSpecTable(filename, specText):
document = Document(filename)
paragraphs = document.paragraphs
allTables = document.tables
specText = specText.encode('utf-8').decode('utf-8')
for aPara in paragraphs:
if aPara.text == specText:
ele = aPara._p.getnext()
while (ele.tag != '' and ele.tag[-3:] != 'tbl'):
ele = ele.getnext()
if ele.tag != '':
for aTable in allTables:
if aTable._tbl == ele:
for i in range(len(aTable.rows)):
for j in range(len(aTable.columns)):
print(aTable.cell(i, j).text)
if __name__ == '__main__':
readSpecTable('test.docx', '符號約定')
3.結果
符號
符號
含義
數據域取值符號
M
必須填寫的域
數據域取值符號
C
某條件成立時必須填寫的域
數據域取值符號
O
可選,非必須填寫的域
數據域取值符號
←
必須與先前報文中對應域的值相同的域
數據域取值符號
-
必須去除的域
數據域屬性符號
基本數據域
數據域屬性符號
[]
標識為消息組件名稱數據域
數據域屬性符號
{}
標識為消息組件中重復的數據域
數據域屬性符號
→
標識為消息組件中包含的基礎數據域
數據域屬性符號
→[]
標識為消息組件中的子消息組件
數據域屬性符號
→{}
標識為子消息組件中重復的數據域塊
數據域屬性符號
→→
標識為子消息組件中包含的基礎數據域
PS:python讀取word文檔表格里的數據
首先需要安裝相應的支持庫:
直接在命令行執行pip install python-docx
示例代碼如下:
import docx
from docx import Document #導入庫
path = "E:\\python_data\\1234.docx" #文件路徑
document = Document(path) #讀入文件
tables = document.tables #獲取文件中的表格集
table = tables[0 ]#獲取文件中的第一個表格
for i in range(1,len(table.rows)):#從表格第二行開始循環讀取表格數據
result = table.cell(i,0).text + "" +table.cell(i,1).text+
table.cell(i,2).text + table.cell(i,3).text
#cell(i,0)表示第(i+1)行第1列數據,以此類推
print(result)
總結
以上所述是小編給大家介紹的python讀取word 中指定位置的表格及表格數據,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對我們網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
本文標題: python讀取word 中指定位置的表格及表格數據
本文地址: http://www.cppcns.com/jiaoben/python/281782.html
總結
以上是生活随笔為你收集整理的python读取word指定内容_python读取word 中指定位置的表格及表格数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天正双击墙体不能编辑_今日设计分享:CA
- 下一篇: python代码导出_代码生成 – Py