打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用python操作word

有两种方式:

  • 使用win32com
  • 使用docx

 

1.使用win32com扩展包

只对windows平台有效

代码:

# coding=utf-8import win32comfrom win32com.client import Dispatch, DispatchExword = Dispatch('Word.Application') # 打开word应用程序# word = DispatchEx('Word.Application') #启动独立的进程word.Visible = 0 # 后台运行,不显示word.DisplayAlerts = 0 # 不警告path = 'G:/WorkSpace/Python/tmp/test.docx' # word文件路径doc = word.Documents.Open(FileName=path, Encoding='gbk')# content = doc.Range(doc.Content.Start, doc.Content.End)# content = doc.Range()print '----------------'print '段落数: ', doc.Paragraphs.count# 利用下标遍历段落for i in range(len(doc.Paragraphs)): para = doc.Paragraphs[i] print para.Range.textprint '-------------------------'# 直接遍历段落for para in doc.paragraphs: print para.Range.text # print para #只能用于文档内容全英文的情况doc.Close() # 关闭word文档# word.Quit #关闭word程序

 

2.使用docx扩展包

优点:不依赖操作系统,跨平台

安装:

pip install python-docx

参考文档: https://python-docx.readthedocs.io/en/latest/index.html

代码:

import docxdef read_docx(file_name): doc = docx.Document(file_name) content = '\n'.join([para.text for para in doc.paragraphs]) return content

创建表格

# coding=utf-8import docxdoc = docx.Document()table = doc.add_table(rows=1, cols=3, style='Table Grid') #创建带边框的表格hdr_cells = table.rows[0].cells # 获取第0行所有所有单元格hdr_cells[0].text = 'Name'hdr_cells[1].text = 'Id'hdr_cells[2].text = 'Desc'# 添加三行数据data_lines = 3for i in range(data_lines): cells = table.add_row().cells cells[0].text = 'Name%s' % i cells[1].text = 'Id%s' % i cells[2].text = 'Desc%s' % irows = 2cols = 4table = doc.add_table(rows=rows, cols=cols)val = 1for i in range(rows): cells = table.rows[i].cells for j in range(cols): cells[j].text = str(val * 10) val += 1doc.save('tmp.docx')

读取表格

# coding=utf-8import docxdoc = docx.Document('tmp.docx')for table in doc.tables: # 遍历所有表格 print '----table------' for row in table.rows: # 遍历表格的所有行 # row_str = '\t'.join([cell.text for cell in row.cells]) # 一行数据 # print row_str for cell in row.cells: print cell.text, '\t', print

 相关样式参考: https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python自动化办公之Word文档的创建与生成
Python对word文档进行操作
POI读写Word docx文件
实例7:用Python操作Word批量生成合同
Word 神器 python-docx
Python|利用第三方库编辑word的基本操作
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服