标签:docx p1 Word format python paragraph 设置 docment
用到的库
?
1
2
3
4
5
6
|
from docx import Document(文档读写)
from docx.shared import Pt,Cm,Inches (字体大小,不一定全用到)
from docx.oxml.ns import qn(设置字体格式,分栏等用到)
from docx.shared import RGBColor (设置字体颜色)
from docx.enum.text import WD_ALIGN_PARAGRAPH (设置对其方式)
from docx.enum.section import WD_ORIENTATION (纸张方向用到)
|
设置大致格式
这样设置完了之后有一个好处就是,后往里面写入文档的时候回自动按这个格式,如果有需要改动的再单独写入时改。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
docment = docx.Document(docx_tamplate)
docment.styles[ 'Normal' ].font.size = Pt( 16 )
docment.styles[ 'Normal' ].font.name = u '仿宋_GB2312'
docment.styles[ 'Normal' ]._element.rPr.rFonts. set (qn( 'w:eastAsia' ), u '仿宋_GB2312' )
docment.styles[ 'Normal' ].paragraph_format.line_spacing = Pt( 29 )
docment.styles[ 'Normal' ].paragraph_format.space_before = Pt( 0 )
docment.styles[ 'Normal' ].paragraph_format.space_after = Pt( 0 )
docment.styles[ 'Normal' ].paragraph_format.first_line_indent = 406400
docment.styles[ 'Normal' ].paragraph_format.widow_control = False
docment.sections[ 0 ].page_height = Cm( 29.7 )
docment.sections[ 0 ].page_width = Cm( 21 )
docment.sections[ 0 ].top_margin = Cm( 3.7 )
docment.sections[ 0 ].bottom_margin = Cm( 3.4 )
docment.sections[ 0 ].left_margin = Cm( 2.8 )
docment.sections[ 0 ].right_margin = Cm( 2.6 )
|
单独设置段格式
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
doc = Document()
p1 = doc.add_paragraph()
p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
p1.paragraph_format.line_spacing = 1.5
p1.paragraph_format.first_line_indent = Inches( 0.5 )
p1.paragraph_format.left_line_indent = Inches( 0.5 )
p1.paragraph_format.right_line_indent = Inches( 0.5 )
p1.paragraph_format.keep_together = False
p1.paragraph_format.keep_with_next = False
p1.paragraph_format.page_break_before = True
p1.paragraph_format.widow_control = False
p1.space_after = Pt( 5 )
p1.space_before = Pt( 5 )
run1 = p1.add_run( '你好' )
run1.font.size = Pt( 12 )
run1.font.bold = True
run1.italic = True
run1.font.underline = True
run1.font.color.rgb = RGBColor( 255 , 0 , 0 )
|
插入图片
?
1
2
|
doc.add_picture(r "图片路径" , width = Cm( 10 ))
|
插入表格
?
1
2
3
4
5
6
7
8
|
tab = doc.add_table(rows = 5 , cols = 8 , style = 'Table Grid' )
tab.cell( 0 , 0 ).text = '表角'
cell = tab.cell( 0 , 1 ).merge(tab.cell( 0 , 3 ))
p = cell.paragraphs[ 0 ]
run = p.add_run(‘合并 ') #在单元格内容创建一个段落,并写入‘合并' 文本
run.font.size = Pt( 10.5 )
run.bold = True
p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
|
原文链接:https://www.cnblogs.com/wenshi-jj/p/15389090.html
标签:docx,
p1,
Word,
format,
python,
paragraph,
设置,
docment
From: https://www.cnblogs.com/QQ-77Ly/p/17500652.html