侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python使用python-docx读写word文档

Python  /  管理员 发布于 8年前   217

python-docx库可用于创建和编辑Microsoft Word(.docx)文件。

官方文档:链接地址

备注:

doc是微软的专有的文件格式,docx是Microsoft Office2007之后版本使用,其基于Office Open XML标准的压缩文件格式,比 doc文件所占用空间更小。docx格式的文件本质上是一个ZIP文件,所以其实也可以把.docx文件直接改成.zip,解压后,里面的 word/document.xml包含了Word文档的大部分内容,图片文件则保存在word/media里面。

python-docx不支持.doc文件,间接解决方法是在代码里面先把.doc转为.docx。

一、安装包

pip3 install python-docx

二、创建word文档

下面是在官文示例基础上对个别地方稍微修改,并加上函数的使用说明

from docx import Documentfrom docx.shared import Inches document = Document() #添加标题,并设置级别,范围:0 至 9,默认为1document.add_heading('Document Title', 0) #添加段落,文本可以包含制表符(\t)、换行符(\n)或回车符(\r)等p = document.add_paragraph('A plain paragraph having some ')#在段落后面追加文本,并可设置样式p.add_run('bold').bold = Truep.add_run(' and some ')p.add_run('italic.').italic = True document.add_heading('Heading, level 1', level=1)document.add_paragraph('Intense quote', style='Intense Quote') #添加项目列表(前面一个小圆点)document.add_paragraph( 'first item in unordered list', style='List Bullet')document.add_paragraph('second item in unordered list', style='List Bullet') #添加项目列表(前面数字)document.add_paragraph('first item in ordered list', style='List Number')document.add_paragraph('second item in ordered list', style='List Number') #添加图片document.add_picture('monty-truth.png', width=Inches(1.25)) records = ( (3, '101', 'Spam'), (7, '422', 'Eggs'), (4, '631', 'Spam, spam, eggs, and spam')) #添加表格:一行三列# 表格样式参数可选:# Normal Table# Table Grid# Light Shading、 Light Shading Accent 1 至 Light Shading Accent 6# Light List、Light List Accent 1 至 Light List Accent 6# Light Grid、Light Grid Accent 1 至 Light Grid Accent 6# 太多了其它省略...table = document.add_table(rows=1, cols=3, style='Light Shading Accent 2')#获取第一行的单元格列表hdr_cells = table.rows[0].cells#下面三行设置上面第一行的三个单元格的文本值hdr_cells[0].text = 'Qty'hdr_cells[1].text = 'Id'hdr_cells[2].text = 'Desc'for qty, id, desc in records: #表格添加行,并返回行所在的单元格列表 row_cells = table.add_row().cells row_cells[0].text = str(qty) row_cells[1].text = id row_cells[2].text = desc document.add_page_break() #保存.docx文档document.save('demo.docx')

创建的demo.docx内容如下:

 

三、读取word文档

from docx import Document doc = Document('demo.docx') #每一段的内容for para in doc.paragraphs: print(para.text) #每一段的编号、内容for i in range(len(doc.paragraphs)): print(str(i), doc.paragraphs[i].text) #表格tbs = doc.tablesfor tb in tbs: #行 for row in tb.rows:  #列  for cell in row.cells: print(cell.text) #也可以用下面方法 '''text = '' for p in cell.paragraphs: text += p.text print(text)'''

运行结果:

Document TitleA plain paragraph having some bold and some italic.Heading, level 1Intense quotefirst item in unordered listsecond item in unordered listfirst item in ordered listsecond item in ordered listDocument TitleA plain paragraph having some bold and some italic.Heading, level 1Intense quotefirst item in unordered listsecond item in unordered listfirst item in ordered listsecond item in ordered list   QtyIdDesc101Spam422Eggs631Spam, spam, eggs, and spam[Finished in 0.2s]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python 如何提高元组的可读性
    下一条:
    Python Subprocess模块原理及实例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • AI Agent
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • OpenAI GPT-5.5正式发布:更会编程和使用计算机的最强模型!(0个评论)
    • opencode AI智能体自主规划开发游戏:王者荣耀模拟战游戏初体验!英雄角色开发中...(0个评论)
    • opencode AI智能体自主规划开发游戏:王者荣耀模拟战游戏初体验!(0个评论)
    • opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus(0个评论)
    • Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用(0个评论)
    • Apifox桌面端被曝遭供应链投毒:CDN 脚本被篡改,窃取 SSH 密钥与 Git 凭证(0个评论)
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 近期评论
    • test1 在

      opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • Zita 在

      Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客