使用python写docx文档
需要使用python-docx
(1)安装
python -m pip install python-docx
(2)新建空白文档
from docx import Document document = Document() document.save('../data/123.docx')
(3)插入段落
add_paragraph()插入段落
from docx import Document from docx.shared import RGBColor from docx.shared import Pt from docx.oxml import OxmlElement from docx.oxml.ns import qn from docx.shared import Inches from docx.shared import Cm from docx.enum.text import WD_PARAGRAPH_ALIGNMENT document = Document() #设置字体 document.styles['Normal'].font.name = u'黑体' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体') #段落 pCharacter = document.add_paragraph() run = pCharacter.add_run("你好啊") run.bold = True run.font.color.rgb = RGBColor(0, 0, 0) run.font.size = Pt(18) pCharacter1 = document.add_paragraph() run1 = pCharacter1.add_run("你好啊") run1.italic = True run1.font.color.rgb = RGBColor(255, 0, 0) run1.font.size = Pt(12) # 设置对齐 ,LEFT: 左对齐,CENTER: 居中对齐,RIGHT: 右对齐 pCharacter1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER document.save('../data/123.docx')
说明:
Paragraph(段落对象):每段内容以换行符结尾
Run(文字块对象):颜色、字体、粗细、斜体等样式不同,就是不同的文字块
(4)插入图片
使用add_picture()插入图片
from docx import Document from docx.shared import Inches from docx.enum.text import WD_PARAGRAPH_ALIGNMENT document = Document() #图片 picture = document.add_picture('../data/1.jpg') # 查看大小 print(picture.width.cm) print(picture.height.cm) # 修改大小 picture.width = int(picture.width * 0.50) picture.height = int(picture.height * 0.50) #修改对齐 LEFT: 左对齐,CENTER: 居中对齐,RIGHT: 右对齐 document.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER document.save('../data/123.docx')
(5)插入表格
from docx import Document from docx.oxml.ns import qn from docx.shared import Cm from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT document = Document() document.styles['Normal'].font.name = u'黑体' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体') #插入表格 table = document.add_table(rows=2, cols=3, style=None) for r in range(len(table.rows)): row = table.rows[r] row.height = Cm(3) for c in range(len(row.cells)): cell = row.cells[c] cell.width = Cm(3) cell.text = '第' + str(r + 1) + '-' + str(c + 1) #设置单元格垂直居中 cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER #设置单元格水平居中 cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER #设置表格水平居中 table.alignment = WD_TABLE_ALIGNMENT.CENTER document.save('../data/123.docx')