python往word文档中写入表格、段落、标题、图片…(超级全)

1、安装python-docx

我们使用python-docx来操作word文档,首先是安装:

pip install python-docx -i https://pypi.tuna.tsinghua.edu.cn/simple

然后放两个参考文档:

使用步骤

  • 步骤1 导入docx模块
  • 步骤2 创建或读取一个文档对象
  • 步骤3 向文档写入内容
  • 步骤4 生成docx文件

上代码:


from docx import Document

document = Document()

...

document.save("test.docx")

2、添加标题

要求:添加标题,能设置标题的字体、大小、颜色等

上代码:

from docx import Document
from docx.shared import Pt, RGBColor
from docx.oxml.ns import qn

d = Document()

d.add_heading("一级标题 hello world", level=0)

run = d.add_heading("", level=1).add_run("二级标题")

run.font.name = u'宋体'

run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

run.font.color.rgb = RGBColor(255, 55, 55)

run.font.size = Pt(30)

run.font.underline = True

run.font.strike = True

run.bold = True

run.italic = True

d.save("test.docx")

代码解释:

方法名描述 add_heading(text="", level=1)

写入标题,默认标题样式为level1,level范围为0-9 add_run(text=None, style=None)

可以添加文本(包括标题、正文、表格文字等),并且能为其设置字体格式、颜色、大小等属性

  • 设置字体有两种方式,一种是全局配置,但是只对正文起作用:
d = Document()
d.styles['Normal'].font.name = u'宋体'
d.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  • 但是上面这种方式无法对add_heading()起作用,需要对标题设置字体,需要使用下面这种方式:
run = d.add_heading("", level=3).add_run("三级标题")
run.font.name = u'宋体'
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  • 使用 run.font.size = Pt(30)设置字体大小,Pt表示磅,与字号对应关系如下: 号数磅值 (Pt)初号42小初36一号26小一24二号22小二18三号16小三15四号14小四12五号10.5小五9六号7.5小六6.5七号5.5八号5

3、添加段落

举例1:段落、分页、有序列表、无序列表、引用

上代码

from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn

d = Document()

d.styles['Normal'].font.size = Pt(20)
d.styles['Normal'].font.name = u'Times New Roman'
d.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')

p1 = d.add_paragraph("这是第一个段落:")

run = p1.add_run("段落中的文字")
run.font.size = Pt(10.5)
run.font.name = u'宋体'
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

d.add_paragraph("有序列表1111", style="List Number")
d.add_paragraph("有序列表2222", style="List Number")

d.add_paragraph("无序列表3333", style="List Bullet")
d.add_paragraph("无序列表4444", style="List Bullet")

d.add_paragraph("引用5555", style="Intense Quote")

p1.insert_paragraph_before("在段落p1前添加一个段落,我才是第一个段落")

d.add_page_break()

p2 = d.add_paragraph("我是新分页中的段落")

p2.paragraph_format.first_line_indent = Pt(20) * 2
d.save("1111.docx")

效果图:

python往word文档中写入表格、段落、标题、图片...(超级全)

代码解释:

方法名描述 add_paragraph(text="", style=None)

1、插入段落,通过style可以设置插入段落的类型

2、 List Number

表示有序段落

3、 List Bullet

表示无序段落

4、 Intense Quote

表示引用 insert_paragraph_before(text=None, style=)

插入段落到现有段落之前 add_page_break()

新增分页,后续的内容会出现在新的分页中

  • 字体效果:如果设置了全局的字体属性,那么所有正文都是那种字体,但是可以通过 add_run()对象设置新的字体
  • 首行缩进:通过设置 paragraph_format.first_line_indent属性可以设置缩进大小为当前字体大小的2倍

举例2:对齐、间距、行距

上代码

from docx import Document
from docx.shared import Pt, Inches
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

d = Document()
d.styles['Normal'].font.size = Pt(20)
d.styles['Normal'].font.name = u'Times New Roman'
d.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
p = d.add_paragraph("《静夜思》"
                 "床前明月光,"
                 "疑似地上霜。"
                 "举头望明月,"
                 "低头思故乡。")

p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT

d.add_paragraph("右缩进,0.5英寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸寸").paragraph_format.right_indent = Inches(0.5)
d.add_paragraph("左缩进,20磅").paragraph_format.left_indent = Pt(20)
d.add_paragraph("首行缩进2个字符").paragraph_format.first_line_indent = Pt(20) * 2

d.add_paragraph("line_spacing设置为浮点数,表示行间距为行高的倍数").paragraph_format.line_spacing = 1.5
d.add_paragraph("line_spacing设置为具体的长度值,表示绝对距离").paragraph_format.line_spacing = Pt(50)
d.add_paragraph("space_before表示段前间距").paragraph_format.space_before = Pt(100)
d.add_paragraph("space_after表示段后间距").paragraph_format.space_after = Pt(30)

p2 = d.add_paragraph("很长的段落很长的段落很长的段落很长的段落很长的段落很长的段落很长的段落很长的段落很长的段落很长的段落很长的段落")
p2.paragraph_format.keep_together = True
p2.paragraph_format.keep_with_next = True
p2.paragraph_format.page_break_before = True
p2.paragraph_format.widow_control = True
d.save("11111.docx")

效果图:

python往word文档中写入表格、段落、标题、图片...(超级全)
代码解释:
  • 段落对齐格式 WD_PARAGRAPH_ALIGNMENT有多个可选项
  • LEFT 表示左对齐
  • CENTER 表示居中对齐
  • RIGHT 表示右对齐
  • JUSTIFY 表示两端对齐
  • DISTRIBUTE 表示散列对齐
  • add_paragraph()对象可以设置 paragraph_format的多种属性,包括:
  • 对齐方式 alignment
  • 段落缩进 right_indent left_indent first_line_indent
  • 段落间距 space_before space_after
  • 行间距 line_spacing
  • 分页设置 keep_together keep_with_next page_break_before widow_control
  • 分页设置的属性说明:
  • keep_together 段中不分页
  • keep_with_next 与下段同页
  • page_break_before 在段落前增加分页符
  • widow_control 孤行控制,控制页面的孤行和孤立行

3、添加表格

举例1:获取单元格、获取行、获取列、新增行、新增列

上代码:

from docx import Document

d = Document()
t = d.add_table(rows=6, cols=4, style="Table Grid")

cell = t.cell(0, 0)
cell.text = "第1行第1列"

rows = t.rows[1]
for cell in rows.cells:
    cell.text = f"第2行第..列"

cols = t.columns[2]
for cell in cols.cells:
    cell.text = f"第3列第..行"

for cell in t.add_row().cells:
    cell.text = "新增行"
t.add_column(cell.width)
d.save("ttt.docx")

效果图:

python往word文档中写入表格、段落、标题、图片...(超级全)

代码解释:

方法名描述 add_row()

新增1行 add_column(width)

新增1列,width列宽必须指定 add_table(rows, cols, style=None)

添加表格的方法,rows、cols为必填,style表示表格的样式,常用 Table Grid

,未赋值情况下表格为虚线,其他style样式如下:

python往word文档中写入表格、段落、标题、图片...(超级全)
  • style可以为:可以查看此博文https://blog.csdn.net/qq_45464895/article/details/123173742
  • 两种方式可以获取单元格
  • 方式一:通过 t.cell(row, col)获取具体的单元格,索引从0开始
  • 方式二:通过 rows = t.rows[0]columns = t.colums[0]获取行或列,然后通过获取到的行 rows.cells[0]或列 columns.cells[0]获取具体的单元格
  • 注意:设置单元格内容时,如果如果是int类型,需要转换成str: cell.text = str(i) i表示数字

举例2:首行设置背景色,合并单元格、表格文字居中

上代码:

from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT

d = Document()
t = d.add_table(rows=5, cols=6, style="Table Grid")

rows = t.rows[0]
for cell in rows.cells:
    shading_elm = parse_xml(r''.format(nsdecls('w')))
    cell._tc.get_or_add_tcPr().append(shading_elm)

a = t.cell(1, 0)
a.text = '111'
b = t.cell(2, 1)
b.text = '222'
b.merge(a)

e = t.cell(3, 3)
f = t.cell(4, 4)
e.merge(f)
cell = t.cell(3, 4)
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
cell.paragraphs[0].add_run("合并单元格写入")
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
d.save("tttt.docx")

效果图:

python往word文档中写入表格、段落、标题、图片...(超级全)

代码解释:

  • 首行设置背景色:固定写法。 fill="D9D9D9"可以在http://tool.chinaz.com/Tools/PageColor.aspx中找你需要的颜色进行替换
  • 合并后的单元格写入,可以使用它所包含的所有单元格来定位,比如:合并 (3, 3)(4, 4)之间的单元格,那么可以通过 (3, 3)(3, 4)(4, 3)(4, 4)定位这个合并后的单元格
  • 单元格中设置居中方式: WD_CELL_VERTICAL_ALIGNMENT可以设置为如下几种:
  • TOP 文本与单元格的上边框对齐
  • CENTER 文本与单元格的中心对齐
  • BOTTOM 文本与单元格的底部边框对齐
cell = t.cell(3, 4)
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
cell.paragraphs[0].add_run("合并单元格写入")
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

4、添加图片

上代码:

from docx import Document
from docx.shared import Pt, Inches
d = Document()
d.add_picture("test.png", Inches(5))
d.add_picture("test.png", Pt(200))
d.save("ppp.docx")

代码解释:

方法名描述 add_picture(image_path_or_stream, width=None, height=None)

添加图片函数,如果没有指定width和height,会将原图添加到文档中。有指定则会按比例缩放。

5、添加页眉页脚

暂时没用到,需要可以参考下面的文章

参考文章:

  • 这个很全:https://blog.csdn.net/qq_45464895/article/details/123173742
  • https://blog.csdn.net/hihell/article/details/121966945
  • https://www.cnblogs.com/1gaoyu/p/12656003.html
  • https://www.5axxw.com/wiki/content/kbhv5m
  • https://www.5axxw.com/wiki/topic/l8oj0b
  • https://www.5axxw.com/wiki/content/qa5cih
  • https://www.cnblogs.com/wangyueping/p/16018206.html
  • https://blog.csdn.net/weixin_47383889/article/details/119847787
  • https://blog.csdn.net/u012034742/article/details/106022019/
  • https://blog.csdn.net/qq_27017791/article/details/108897521
  • http://tool.chinaz.com/Tools/PageColor.aspx
  • https://www.zhihu.com/question/511536143/answer/2313422603

Original: https://blog.csdn.net/ben_na_/article/details/124240275
Author: zzzxydq
Title: python往word文档中写入表格、段落、标题、图片…(超级全)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/670208/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球