python 操作读取word

安装扩展

#pip install -i https://pypi.tuna.tsinghua.edu.cn/simpl python-docx

#pip install -i https://pypi.tuna.tsinghua.edu.cn/simpl pypiwin32

读取每一行【不能读取表格图片等信息】

import win32com.client as wc
import docx
from docx import Document

def doSaveAas():
    word = wc.Dispatch('Word.Application')
    doc = word.Documents.Open(r'api.doc')  # 目标路径下的文件
    doc.SaveAs(r'api.docx', 12, False, "", True, "", False, False, False, False)  # 
    doc.Close()
    word.Quit()
doSaveAas()# 先转换成 docx文件

path = r"api.docx"
document = Document(path)
i=0
for paragraph in document.paragraphs:
    print(paragraph.text)
    i=i+1
    if i>=10:
        break

读取表格数据

path = r"api.docx" #文件路径
document = Document(path)#读入文件
tables = document.tables#获取文件中的表格集
for k in range(len(tables)):
     if k<=0:#从第几个表格开始
         table = tables[k]#获取文件中的第一个表格
         for i in range(1,len(table.rows)):#从表格第二行开始循环读取表格数据
             if table.cell(i,0).text=="success":
                 break
             result = table.cell(i,0).text + "" +table.cell(i,1).text+table.cell(i,2).text + table.cell(i,3).text+ table.cell(i,4).text+ table.cell(i,5).text
             #cell(i,0)表示第(i+1)行第1列数据,以此类推
             print(result)
         len(table.rows)    #表格行数
         len(table.columns) #表格列数

猜你喜欢

转载自blog.csdn.net/zhang804633234/article/details/121232830