python 读写word

'''
    #利用python读取word文档,先读取段落
    # pip install docx
    # pip3 install python-docx
'''
#导入所需库
from docx import Document
class docxOpraCls:
 myDoc = ''
 def openDoc(_self,path):
  #打开word文档
  document = Document(path)
  _self.myDoc = document
  #获取所有段落
  all_paragraphs = document.paragraphs
  #获取表格内容
  tables = document.tables
  #打印看看all_paragraphs是什么东西
  print(type(all_paragraphs)) #<class 'list'>,打印后发现是列表
  #是列表就开始循环读取
  #for paragraph in tables:
   #打印每一个段落的文字
   #print(paragraph.text)
  for table in tables[:]:
   for i, row in enumerate(table.rows[:]):  # 读每行
    row_content = []
    for cell in row.cells[:]:  # 读一行中的所有单元格
     c = cell.text
     row_content.append(c)
    print(row_content)  # 以列表形式导出每一行数据
 def writeContent(_self,systemName,ipAddress,level,note,changeNote,changeAuthor):
  tables = _self.myDoc.tables
  firstTab = tables[1]
  newRowsCells = firstTab.add_row().cells
  newRowsCells[0].text = systemName
  newRowsCells[1].text = ipAddress
  newRowsCells[2].text = level
  newRowsCells[3].text = note
  newRowsCells[4].text = changeNote
  newRowsCells[5].text = changeAuthor
  return
 def saveDoc(_self,path):
  _self.myDoc.save(path)
  return
原文地址:https://www.cnblogs.com/zf-crazy/p/14982905.html