今天推荐的库是python-docx库,能够对word的docx自动化处理,今天把常见用法示例演示给大家,有需要的收藏。
一、安装
# 处理docx格式文件
pip install python-docx
#仅限 windows 平台
pip install pywin32
大家会看到我在上面安装中包含了pywin32库。我装这个库的目的:2003版之前的doc文件,需要通过pywin32进行转换一下。
pywin32库自身也能处理docx文件,代码如下:
from win32com import client as wc
import os
from datetime import datetime
path = os.getcwd()
word = wc.Dispatch('Word.Application')
# 新建word文档
doc = word.Documents.Add()
# 当前word关联的编辑器
word.Visible = 1
# cur获得新建文档的光标焦点
cur = word.Selection
# 替换cur处代表的范围的文本
cur.Text = '输入内容'
filename = '{}.docx'.format(datetime.now().strftime('%Y%m%d%H%M%S'))
doc.SaveAs(os.path.join(path,filename),12)
doc.Close()
word.Quit()
打开一个关联word的软件程序,光标处、写入“输入内容”。
要处理doc文件,需要通过下面的方法转换为docx文件。
from win32com import client as wc
import os
path = os.getcwd()
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(os.path.join(path,'org.doc'))
doc.SaveAs(os.path.join(path,'neworg.docx'),12)
doc.Close()
word.Quit()
二、docx库使用
接下来才是重点,今天我们主要学习docx的基本使用。
读取上面生成newogr.docx文件,不能获取doc文件,否则报错
from docx import Document
document = Document('neworg.docx')
# 输出第一段内容
document.paragraphs[0].text
添加段落
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document()
# 添加一个段落
p = document.add_paragraph("这是个段落")
# 在p段落之前添加一个段落
p1 = p.insert_paragraph_before("第一个段落")
# 居左对齐
p1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
document.save('new.docx')
输出结果如下:
添加标题
from docx import Document
document = Document()
# 新增标题,Level有1-9种规格
# Level=0,新增的标题会有带下划线样式
document.add_heading("这是标题0",level=0)
document.add_heading("这是标题0",level=1)
document.add_heading("这是标题1",level=2)
document.add_heading("这是标题2",level=3)
document.add_heading("这是标题3",level=4)
document.add_heading("这是标题4",level=5)
document.add_heading("这是标题5",level=6)
document.add_heading("这是标题6",level=7)
document.add_heading("这是标题7",level=8)
document.add_heading("这是标题8",level=9)
document.save('new_h.docx')
输出文件内容如下:
添加分页符
from docx import Document
from docx.shared import Inches
# 注意Dcoument参数传递了new_h.docx文件
document = Document("new_h.docx")
# 新增分页符 --- 后面添加的内容会在新的一页中
document.add_page_break( )
p = document.add_paragraph("文本内容n")
# 加粗
p.add_run("具体内容n").bold = True
# 斜体
r = p.add_run("t你学会了吗n")
r.italic = True
r.font.name = '宋体' # 设置字体
r.font.size = Inches(20) # 设置字号
document.save("new_b.docx")
输出文件new_b.docx内容如下:
在第二页输出了段落。
添加图片
from docx import Document
from docx.shared import Inches
document = Document("new.docx")
# 添加图片并设置英寸宽度
document.add_picture("E:mm.png",width=Inches(1.25))
document.save("new_i.docx")
输出文件new_i.dox文件内容如下:
添加表格
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
document = Document("new.docx")
# 新增表格,5行5列表表格
table = document.add_table( rows=5,cols=5)
# 表格居中对齐
table.alignment = WD_TABLE_ALIGNMENT.CENTER
# 单个单元格操作
cell = table.cell(0,0)
cell.text = "第一行第一列"
# 取出第一行
row = table.rows[0]
row.cells[1].text = "第一行第二列"
row.cells[1].italic = True
row.cells[2].text = "第一行第三列"
row.cells[2].bold = True
document.save("new_tb.docx")
输入new_tb.docx文件内容如下:
在表格中添加图片
from docx import Document
document = Document("new.docx")
table = document.add_table( rows=2,cols=1)
# 标题
table.cell(0,0).text = "美女图片"
# 插入图片
p = table.cell(1,0).paragraphs[0]
r = p.add_run()
r.add_picture("E:mm.png",width=Inches(1.25))
document.save("new_tbc.docx")
生成的new_tac.docx文件内容如下:
读取内容
# 输出word信息
document = Document('new.docx')
for p1 in document.paragraphs:
print('所有内容',p1.text)
for p1 in document.paragraphs:
if(p1.style.name == 'Heading 1'):
print('一级标题',p1.text)
if(p1.style.name == 'Heading 2'):
print('二级标题',p1.text)
if(p1.style.name == 'Normal'):
print('正文',p1.text)
效果如下:
希望上面代码能帮助到您。官方API地址:https://python-docx.readthedocs.io/en/latest/index.html#
原文始发于微信公众号(程序员老朱):word文档处理库docx常见用法示例
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论