1 python-docx 是什么?
>python-docx is a Python library for creating and updating Microsoft Word (.docx) files.
它是一个python库,主要用来生成和修改word。这是一个很实用的库。
传送门:http://python-docx.readthedocs.org/en/latest/
2 安装
pip install python-docx
3 使用
3.1 创建或打开一个word
首先需要导入该模块:from docx import Document
创建:document = Document() # 这将生成一个新的word,通过document对象,可以进行该word的各种操作
打开:document = Document(‘word_name.doc’) # 打开已经存在的doc或docx文档
3.2 写
#向该word中写入一段文字,可以轻易的写入中文,返回的paragraph对象代表这段话的对象,可以用它进行追加
paragraph = document.add_paragraph(u’这是一段话’)
# 这段话后追加一段话
paragraph.add_run( u’这是追加的一句话’)
# 在这段话前加一段话
paragraph.text = u’这是前面的一句话’ + paragraph.text
# 在前面的paragraph前插入一个paragraph
paragraph.insert_paragraph_before(u’我在paragraph前面’)
# 这是第三段
document.add_paragraph(u’我是第三段’)
# 获得到第二段的对象
para = document.paragraphs[1]
# 在第二段之前插入一段
para.insert_paragraph_before(‘first’)
# 插入一个head
document.add_heading(u’我是一个heading’, level=2)
# 插入一个图片
from docx.shared import Inches
document.add_picture(‘a_pic.png’, width=Inches(1.25))
# 插入一个表格,插入一个2*2的表格
table = document.add_table(rows=2, cols=2)
cell0_0 = table.cell(0, 0)
cell0_0.text = ‘1chang’
cell0_1 = table.cell(0, 1)
cell0_1.text = ‘2jiang’
cell1_0 = table.cell(1, 0)
cell1_0.text = ‘3huang’
cell1_1 = table.cell(1, 1)
cell1_1.text = ‘4he’
# 强行换页
document.add_page_break()
3.3 生成文档
document.save(u’new_word_name.doc’) # 可以生成doc或者docx的文档,能够被word2007以及以后的版本打开
“””
document对象中有很多属性,在实际运用中可以多使用dir和help函数查看函数和说明文档,还可以去看官网说明文档,官网上的说明都非常清楚。
“””
作者:白熊花田
原文链接:https://blog.csdn.net/whiterbear/article/details/48474503
转载请注明:www.ainoob.cn » Python-docx简介