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', '符號(hào)約定')
3.結(jié)果
符號(hào)
符號(hào)
含義
數(shù)據(jù)域取值符號(hào)
M
必須填寫的域
數(shù)據(jù)域取值符號(hào)
C
某條件成立時(shí)必須填寫的域
數(shù)據(jù)域取值符號(hào)
O
可選,非必須填寫的域
數(shù)據(jù)域取值符號(hào)
←
必須與先前報(bào)文中對(duì)應(yīng)域的值相同的域
數(shù)據(jù)域取值符號(hào)
-
必須去除的域
數(shù)據(jù)域?qū)傩苑?hào)
基本數(shù)據(jù)域
數(shù)據(jù)域?qū)傩苑?hào)
[]
標(biāo)識(shí)為消息組件名稱數(shù)據(jù)域
數(shù)據(jù)域?qū)傩苑?hào)
{}
標(biāo)識(shí)為消息組件中重復(fù)的數(shù)據(jù)域
數(shù)據(jù)域?qū)傩苑?hào)
→
標(biāo)識(shí)為消息組件中包含的基礎(chǔ)數(shù)據(jù)域
數(shù)據(jù)域?qū)傩苑?hào)
→[]
標(biāo)識(shí)為消息組件中的子消息組件
數(shù)據(jù)域?qū)傩苑?hào)
→{}
標(biāo)識(shí)為子消息組件中重復(fù)的數(shù)據(jù)域塊
數(shù)據(jù)域?qū)傩苑?hào)
→→
標(biāo)識(shí)為子消息組件中包含的基礎(chǔ)數(shù)據(jù)域
PS:python讀取word文檔表格里的數(shù)據(jù)
首先需要安裝相應(yīng)的支持庫:
直接在命令行執(zhí)行pip install python-docx
示例代碼如下:
import docx
from docx import Document #導(dǎo)入庫
path = "E:\\python_data\\1234.docx" #文件路徑
document = Document(path) #讀入文件
tables = document.tables #獲取文件中的表格集
table = tables[0 ]#獲取文件中的第一個(gè)表格
for i in range(1,len(table.rows)):#從表格第二行開始循環(huán)讀取表格數(shù)據(jù)
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列數(shù)據(jù),以此類推
print(result)
總結(jié)
以上所述是小編給大家介紹的python讀取word 中指定位置的表格及表格數(shù)據(jù),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)我們網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
本文標(biāo)題: python讀取word 中指定位置的表格及表格數(shù)據(jù)
本文地址: http://www.cppcns.com/jiaoben/python/281782.html
總結(jié)
以上是生活随笔為你收集整理的python读取word指定内容_python读取word 中指定位置的表格及表格数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天正双击墙体不能编辑_今日设计分享:CA
- 下一篇: python代码导出_代码生成 – Py