Python-docx


python-docx包可以用来创建docx文档,并对现有文档进行更改,包含段落、分页符、表格、图片、标题、样式等几乎所有的word文档中能常用的功能都包含了

只能解析docx文件,解析不了doc文件

官方文档:

https://python-docx.readthedocs.io/en/latest/user/text.html

https://python-docx.readthedocs.io/en/latest/index.html

from docx import Document #初始化对象
from docx.shared import Inches  #定义英尺
from docx.shared import Pt  #定义像素大小
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn #定义style的
from docx.shared import RGBColor

#打开docx文件
document = Document()

#增加一段
paragraph = document.add_paragraph('This is a demo.')

#在段落前直接插入一个新段落
prior_paragraph = paragraph.insert_paragraph_before('welcome!')

#这一类属性,每个有三种状态
#True 为使用属性;False 为不使用属性;None 默认属性继承自上一个字体
paragraph = document.add_paragraph()
paragraph.add_run('Lorem ipsum')
run = paragraph.add_run(' dolor')
run.bold = True
run.font.name=u'宋体'
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
paragraph.add_run(' hello').underline = True 
paragraph.add_run(u'斜体、').italic = True 
paragraph.add_run(u'设置中文字体,') 
paragraph.add_run(u'设置字号').font.size=Pt(24) 

#添加文本
p = document.add_paragraph('test')

#文本居中
#WD_ALIGN_PARAGRAPH 存储了多种对齐格式
#例如:WD_ALIGN_PARAGRAPH.LEFT,左对齐;WD_ALIGN_PARAGRAPH.RIGHT,右对齐
p.alignment = WD_ALIGN_PARAGRAPH.CENTER 

#左缩进
p.left_indent = Inches(0.3)

#首行缩进
p.first_line_indent = Inches(0.3)

#上行间距
p.space_before = Pt(18)

#下行间距
p.space_after = Pt(12)

#添加标题
document.add_heading('The REAL meaning of the universe')
document.add_heading('The role of dolphins', level = 2)

#添加引用
document.add_paragraph('Intese quote',style="Intense Quote")

#添加分页符
document.add_page_break()

#添加表
table = document.add_table(rows=2,cols=2)
cell = table.cell(0,0)
cell.text = 'cell_00'
table.cell(0,1).text = 'cell_01'
row = table.rows[1]
row.cells[0].text = 'cell_10'
row.cells[1].text = 'cell_11'

#行列计数
row_count = len(table.rows)
col_count = len(table.columns)

#添加图片
document.add_picture('1.png',width=Inches(1.25))

#应用字符样式
paragraph = document.add_paragraph('Normal text, ')
paragraph.add_run('text with emphasis','Emphasis')

#增加有序列表
document.add_paragraph(
    u'有序列表元素1',style='List Number'
)
document.add_paragraph(
    u'有序列表元素2',style='List Number'
)

#增加无序列表
document.add_paragraph(
    u'无序列表元素1',style='List Bullet'
)
document.add_paragraph(
    u'无序列表元素2',style='List Bullet'
)
#或者paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
#   paragraph.style = 'ListBullet'

document.save('test.docx')

结果截图如下:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM