word文档处理库docx常见用法示例

今天推荐的库是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')

效果如下:
在这里插入图片描述
添加分页符

rom 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")

在这里插入图片描述
添加表格


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")

读取内容


# 输出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)

在这里插入图片描述

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老朱2000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值