python-docx基础(一)

python-docx基础(一)

打开一个文档

from docx import Document

创建一个空白文档作为文档对象

document = Document()
print(document)
<docx.document.Document object at 0x000001A1BCBC0E10>

打开一个现有文档作为文档对象

document2 = Document("test.docx")
print(document2)
<docx.document.Document object at 0x000001A1BCA95BD0>

段落

直接追加段落到文档末尾

paragraph = document.add_paragraph("使用python-docx写word!")
print(paragraph)

paragraph2 = document2.add_paragraph("使用python-docx写word!")
print(paragraph2)
<docx.text.paragraph.Paragraph object at 0x000001A1BD1E01D0>
<docx.text.paragraph.Paragraph object at 0x000001A1BD1E0EB8>

注意这样的插入并不是真的写到文档里了,而是写在了文档对象中。只有保存了才可以将文档对象转换成文档文件。

document.save("test.docx")
document2.save("test2.docx")

在这里插入图片描述
在这里插入图片描述

通过段落游标插入段落

insert_paragh = paragraph.insert_paragraph_before("插入paragraph的上方!")

insert_paragh2 = paragraph2.insert_paragraph_before("插入在paragraph2的上方!")

print(insert_paragh)
print(insert_paragh2)
<docx.text.paragraph.Paragraph object at 0x000001A1BD694908>
<docx.text.paragraph.Paragraph object at 0x000001A1BD694860>

这是用段落对象(作为游标)插入段落到游标段的上方!并且返回的仍然是一个段落对象。

标题

默认是以及标题,加上level参数可以指定几级标题。

head1 = document.add_heading("标题")
p1 = document.add_paragraph("sagfjoagjawog")
head2 = document.add_heading("第二个标题")
head3 = document.add_heading("二级标题", level=2)
document.save("test.docx")
print(head1, head2, head3)
<docx.text.paragraph.Paragraph object at 0x0000021791B6E978> <docx.text.paragraph.Paragraph object at 0x0000021791B6E4E0> <docx.text.paragraph.Paragraph object at 0x0000021791AD7160>

可见标题也是一个段落对象
在这里插入图片描述

分页

page_break = document.add_page_break()
p2 = document.add_paragraph("xxxxxxx")
document.save('test.docx')

在这里插入图片描述

可以看到它强制分页了!

表格

表格的创建与使用

table = document.add_table(rows=2, cols=3)
print("table:", table)
print("======================")

# 获取行列长度,可见他们是迭代器类型
num_row = len(table.rows)
num_col = len(table.columns)
print(num_row, num_col)
print("======================")

# 使用下面cell访问单元格
cell = table.cell(0, 0)
cell.text = "列1"

# 获取行对象并访问行的单元格
row = table.rows[1]
for cell in row.cells:
    cell.text = "abc"
for cell in row.cells:
    print(cell.text)
print("=====================")
table: <docx.table.Table object at 0x0000021791AB7F98>
======================
2 3
======================
abc
abc
abc
=====================

从上述可见表格是一个迭代器,所以可以使用for对表格进行迭代!

# 所以可以通过for迭代表格
for row in table.rows:
    for cell in row.cells:
        print(cell.text)
列1


abc
abc
abc

空的两列是第0行的两列,没有值所以空着。
在这里插入图片描述

可以看到使用这样的表格是没有样式的表格。如果需要加上边框需要使用样式!

已有表格,向表格中插入行

one_row = table.add_row()

使用这样方式,默认列数是表格的列数。然后可以迭代行,向行中插入值。

使用样式

在这里展示一种样式:

table = document.add_table(rows=2, cols=3)
table.style = 'LightShading-Accent1'

在这里插入图片描述

图片

pic = document.add_picture("实验一图片.jpg")
print(pic)
<docx.shape.InlineShape object at 0x000001C4B0F27160>

这是按照原大小添加图片的,但是有时候图片大小会非常大。所以我们可以指定英寸进行导入。

from docx.shared import Inches
pic = document.add_picture("实验一图片.jpg", width=Inches(5.0))

在这里插入图片描述

样式

段落的样式

在创建段落的时候使用style属性进行样式的添加。

p = document.add_paragraph("xxx", sytle="sytlename")

# 或使用
p = document.add_paragraph()
p.style = "stylename"

或将样式作为一个对象出来:

import docx
document = docx.Document()
styles = document.styles.element.xpath('.//w:style[@w:type="paragraph"]/@w:styleId')

doc=Document()#创建一个空白文档
p=doc.add_paragraph()#给文档增加一个段落
p.paragraph_format.space_before=Pt(0)#设置段落 段前 0 磅
p.paragraph_format.space_after=Pt(0) #设置段落   段后 0 磅
p.paragraph_format.line_spacing=1.5  #设置该段落 行间距为 1.5倍
#p.paragraph_format.first_line_indent=Inches(0.5) #段落首行缩进为 0.5英寸
p.paragraph_format.first_line_indent=Inches(0.3346457)#相当于小四两个字符的缩进
p.paragraph_format.left_indent=Inches(0)#设置左缩进 1英寸
p.paragraph_format.right_indent=Inches(0)#设置右缩进 0.5 英寸

#给段落增加一段文字
r=p.add_run("违反接收到了附近双龙夺凤塑料袋积分上岛咖啡山东矿机发双龙夺凤"\
            +"水电费水电费水电费电饭锅电饭锅让大哥大纲很多个人盯人电饭锅"\
            +"如果电饭锅电饭锅让大哥的防滑大纲而二哥电饭锅仍大纲二个电饭锅"\
            +"尔特人二柔荑花任天野儿童问题5人员柔荑花土样任天野儿童儿童而已")
r.font.name=u'宋体'    #设置为宋体
r._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')#设置为宋体,和上边的一起使用
r.font.size=Pt(12)  #设置字体大小为12磅 相当于 小四
r.font.color.rgb=RGBColor(0,0,0)#设置颜色为黑色

这样设置段落样式对于每一段都需要进行设置段落,所以我们可以将常用样式设置为文档样式。对不常用的样式将其封装成一个类进行样式的附加。

add_run可以向段落中追加一段文字。所以我们可以使用add_run对段落中间的一部分文字进行单独的样式添加!

paragraph = document.add_paragraph('这是一个 ')
# 给 加粗 这两个字加上 强调样式
run = paragraph.add_run('加粗', 'Emphasis')
# 或 run.styl = 'Emphasis'
run.bold = True
paragraph.add_run(' 文本')

这样,这个文本中就只有加粗这两个字是加粗的,其他都是文档样式。

文档样式

import docx
from docx import Document   #用来建立一个word对象
from docx.shared import Pt  #用来设置字体的大小
from docx.shared import Inches
from docx.oxml.ns import qn  #设置字体
from docx.shared import RGBColor  #设置字体的颜色
from docx.enum.text import WD_ALIGN_PARAGRAPH  #设置对其方式

#创建一个空白的word文档
doc=Document()
doc.styles["Normal"].font.name=u"宋体"  #设置全局字体
doc.styles["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
doc.styles["Normal"].font.color.rgb=RGBColor(255,0,0)#设置正文全局颜色为红色
doc.styles["Normal"].font.size=Pt(29)#设置正文全局大小为29
doc.styles["Heading 2"].font.size=Pt(29)#设置全局2级标题的字体大小为29

p=doc.add_paragraph()
r=p.add_run("违反接收")#这个段落使用的是Normal的样式

para_heading=doc.add_heading('',level=2)#返回1级标题段落对象,标题也相当于一个段落
run=para_heading.add_run(u"前言")#这个使用的是"Heading 2" 的样式

doc.save("特殊字体.docx")
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值