python-docx是python编程语言的一个库,可以对docx文档进行读,同时也可以进行生成docx文档,这篇文档主要是讲生成docx文档。
# coding:utf-8
from docx import Document
document = Document()
document.save('1.docx')
# coding:utf-8
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
document = Document()
p = document.add_paragraph(style=None)
p.paragraph_format.line_spacing = 1.0
run = p.add_run('生成docx文档') # 往word中添加文字
run.font.size = Pt(20) # 设置文字的字体大小
run.font.name = u'等线(正文)' # 设置文字的字体
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'等线(正文)')
document.save('1.docx')
生成的结果如下所示:
生成2行3列,靠右对齐,只对第1行进行了行高的设置
# coding:utf-8
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.shared import Inches
from docx.enum.table import WD_TABLE_ALIGNMENT
document = Document()
p = document.add_paragraph(style=None)
p.paragraph_format.line_spacing = 1.0
run = p.add_run('生成docx文档') # 往word中添加文字
run.font.size = Pt(20) # 设置文字的字体大小
run.font.name = u'等线(正文)' # 设置文字的字体
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'等线(正文)')
# 添加表格
table = document.add_table(rows=2, cols=3, style='Table Grid')
table.cell(0, 0).width = Inches(6)
table.rows[0].height = Inches(0.8)
table.alignment = WD_TABLE_ALIGNMENT.RIGHT
document.save('1.docx')
运行结果如下所示:
# coding:utf-8
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.shared import Inches
from docx.enum.table import WD_TABLE_ALIGNMENT
document = Document()
p = document.add_paragraph(style=None)
p.paragraph_format.line_spacing = 1.0
run = p.add_run('生成docx文档') # 往word中添加文字
run.font.size = Pt(20) # 设置文字的字体大小
run.font.name = u'等线(正文)' # 设置文字的字体
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'等线(正文)')
# 添加表格
table = document.add_table(rows=2, cols=3, style='Table Grid')
table.cell(0, 0).width = Inches(6)
table.rows[0].height = Inches(0.8)
table.alignment = WD_TABLE_ALIGNMENT.RIGHT
# 页边距的设置
sec = document.sections[0] # sections对应文档中的“节”
sec.left_margin = Inches(0.2) # 以下依次设置左、右、上、下页面边距
sec.right_margin = Inches(0.3)
sec.top_margin = Inches(0.2)
sec.bottom_margin = Inches(0.2)
sec.page_width = Inches(8.27) # 设置页面宽度
sec.page_height = Inches(11.69) # 设置页面高度
document.save('1.docx')
设置纸张的大小为A4纸的大小
运行的结果如下所示:
注意:在运行代码时,一定要将生成的docx关掉,否则运行会出现错误