700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python往word文档中写入表格 段落 标题 图片...(超级全)

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

时间:2023-02-09 04:12:41

相关推荐

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

1、安装python-docx

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

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

然后放两个参考文档:

官方手册:https://python-docx.readthedocs.io/en/latest/index.htmlpypi官方地址:/project/python-docx/

使用步骤

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

上代码:

# 步骤1from docx import Document# 步骤2document = Document() # 新建文档对象# document = Document("test.docx") # 读取现有word文档,建立文档对象# 步骤3...# 步骤4document.save("test.docx") # 保存文档

2、添加标题

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

上代码:

from docx import Documentfrom docx.shared import Pt, RGBColorfrom docx.oxml.ns import qnd = 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")

代码解释:

设置字体有两种方式,一种是全局配置,但是只对正文起作用:

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表示磅,与字号对应关系如下:

3、添加段落

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

上代码

from docx import Documentfrom docx.shared import Ptfrom docx.oxml.ns import qnd = 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前添加一个段落p1.insert_paragraph_before("在段落p1前添加一个段落,我才是第一个段落")# 增加分页d.add_page_break()# 添加一个段落p2 = d.add_paragraph("我是新分页中的段落")# 新分页中文字首行缩进两个字p2.paragraph_format.first_line_indent = Pt(20) * 2d.save("1111.docx")

效果图:

代码解释:

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

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

上代码

from docx import Documentfrom docx.shared import Pt, Inchesfrom docx.oxml.ns import qnfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENTd = 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("《静夜思》""床前明月光,""疑似地上霜。""举头望明月,""低头思故乡。")# 设置对齐格式# 可选项有LEFT、CENTER、RIGHT、JUSTIFY、DISTRIBUTE等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# 设置段落间距 1.5倍行间距 1.5, 单倍行间距 1.0d.add_paragraph("line_spacing设置为浮点数,表示行间距为行高的倍数").paragraph_format.line_spacing = 1.5d.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")

效果图:

代码解释:

段落对齐格式WD_PARAGRAPH_ALIGNMENT有多个可选项LEFT表示左对齐CENTER表示居中对齐RIGHT表示右对齐JUSTIFY表示两端对齐DISTRIBUTE表示散列对齐add_paragraph()对象可以设置paragraph_format的多种属性,包括: 对齐方式alignment段落缩进right_indentleft_indentfirst_line_indent段落间距space_beforespace_after行间距line_spacing分页设置keep_togetherkeep_with_nextpage_break_beforewidow_control分页设置的属性说明:keep_together段中不分页keep_with_next与下段同页page_break_before在段落前增加分页符widow_control孤行控制,控制页面的孤行和孤立行

3、添加表格

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

上代码:

from docx import Documentd = Document()t = d.add_table(rows=6, cols=4, style="Table Grid")# 通过行、列来确定单元格,索引从0开始cell = t.cell(0, 0)cell.text = "第1行第1列"# 获取第2行rows = t.rows[1]for cell in rows.cells:cell.text = f"第2行第..列"# 获取第3列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")

效果图:

代码解释:

style可以为:可以查看此博文/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 Documentfrom docx.oxml.ns import nsdeclsfrom docx.oxml import parse_xmlfrom docx.enum.table import WD_CELL_VERTICAL_ALIGNMENTd = 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'<w:shd {} w:fill="D9D9D9"/>'.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")

效果图:

代码解释:

首行设置背景色:固定写法。fill="D9D9D9"可以在/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 Documentfrom docx.shared import Pt, Inchesd = Document()d.add_picture("test.png", Inches(5))d.add_picture("test.png", Pt(200))d.save("ppp.docx")

代码解释:

5、添加页眉页脚

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

参考文章:

这个很全:/qq_45464895/article/details/123173742/hihell/article/details/121966945/1gaoyu/p/12656003.html/wiki/content/kbhv5m/wiki/topic/l8oj0b/wiki/content/qa5cih/wangyueping/p/16018206.html/weixin_47383889/article/details/119847787/u012034742/article/details/10602//qq_27017791/article/details/108897521/Tools/PageColor.aspx/question/511536143/answer/2313422603

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。