一、前记
需要操作word文档,读取,写入等。
实例:
from docx import Document
document = Document(needPath)
tables = document.tables
for k in range(0, len(tables)):
table = tables[k]
for j in range(1, len(table.rows)):
resultTemp = table.cell(j,3).text
Python Dox是一个用于创建和更新微软Word(.DOX)文件的Python库。python-docx包,这是一个很强大的包,可以用来创建docx文档,包含段落、分页符、表格、图片、标题、样式等几乎所有的word文档中能常用的功能都包含了,这个包的主要功能便是用来创建文档,相对来说用来修改功能不是很强大。
Python Dox允许您创建新文档,并对现有文档进行更改。实际上,它只允许您对现有文档进行更改;只是从一个没有任何内容的文档开始,它可能首先感觉像是从头开始创建一个文档。这个特点是强有力的。文档的外观是由删除所有内容时留下的部分决定的。样式和页眉和页脚等内容与主内容分开,允许您在开始文档中放置大量自定义,然后出现在所生成的文档中。让我们一步一步地创建一个文档一个例子,从文档中可以做的两件事开始,打开它并保存它。
二、安装
pip install python-docx
三、应用
打开及保存文件:
from docx import Document
document = Document('test.docx')
document.save('test.docx')
添加文本:
document.add_paragraph('test text')
调整文本位置格式为居中:
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document('test.docx')
paragraph = document.add_paragraph('123')
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
document.save('test.docx')
调整左缩进0.3英寸:
document = Document('test.docx')
paragraph = document.add_paragraph('this is test for left_indent with inches')
paragraph_format = paragraph.paragraph_format
paragraph_format.left_indent = Inches(0.3)
document.save('test.docx')
首行缩进:
paragraph_format.first_line_indent = Inches(0.3)
上行间距:
paragraph_format.space_before = Pt(18)
下行间距:
paragraph_format.space_after = Pt(12)
行距:
paragraph_format.line_spacing = Pt(18)
分页格式:
紧跟上段:
paragraph_format.keep_together
若本页无法完全显示,另起一页:
paragraph_format.keep_with_next
字体格式:
p = document.add_paragraph()
run = p.add_run('test typeface')
#加粗
run.font.bold = True
#斜体
run.font.italic = True
#下划线
run.font.underline = True
WD_UNDERLINE 中有所有下划线格式
调用样例:
run.underline = WD_UNDERLINE.DOT_DASH
字体颜色:
from docx.shared import RGBColor
test = document.add_paragraph().add_run('color')
font = test.font
font.color.rgb = RGBColor(0x42, 0x24 , 0xE9)
调用预设颜色:
from docx.enum.dml import MSO_THEME_COLOR
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1
四、一个不错的例子
# -*- coding: utf-8 -*-
'''
Created on 2018年9月24日
@author: 362409100
'''
import os
import sys
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK
from docx.oxml.ns import qn
from docx.shared import Inches, Pt, RGBColor
global doc
global last_err
last_err = ""
#sys.path.append('..\\Lib\\site-packages')
def Init():
global doc
doc = Document()
doc.styles["Normal"].font.name = u'宋体'
doc.styles["Normal"].font.size = Pt(8)
doc.styles["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
head = doc.add_heading("", level=1)
run = head.add_run(u"社会主义核心价值观")
run.font.size = Pt(20)
run.font.color.rgb = RGBColor(128, 0, 0)
run.font.name = u"宋体"
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
head.alignment = WD_ALIGN_PARAGRAPH.CENTER
def Save(dst):
global doc
global last_err
try:
doc.save(dst)
return True
except IOError as e:
last_err = e.strerror
return False
def AddLineTitle(title):
global doc
head = doc.add_heading("", level=2)
run = head.add_run(title)
run.font.size = Pt(16)
run.font.color.rgb = RGBColor(0, 0, 0)
run.font.name = u"宋体"
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
def AddInfoTitle(title):
global doc
head = doc.add_heading("", level=3)
run = head.add_run(title)
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(0, 0, 0)
run.font.name = u"宋体"
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
def AddLineText(text):
global doc
p = doc.add_paragraph()
run = p.add_run(text)
run.font.size = Pt(8)
run.font.name = u"宋体"
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
def AddRecord(qj, cj, gh, mc, lx, ms, bz, tp):
global doc
table = doc.add_table(6, 2)
table.style = "Table Grid" # The First Table Style Of The MS Word
for row in table.rows:
row.height = Pt(14)
row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY
table.rows[-1].height_rule = WD_ROW_HEIGHT_RULE.AUTO # The Last Row Contains A Picture
table.cell(0, 0).text = qj
table.cell(0, 1).text = cj
table.cell(0, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(0, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(1, 0).text = gh
table.cell(1, 1).text = mc
table.cell(1, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(1, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(2, 0).text = lx
table.cell(2, 1).text = ms
table.cell(2, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(2, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
item = table.cell(3, 0).merge(table.cell(3, 1))
item.text = bz
item.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
item = table.cell(4, 0).merge(table.cell(4, 1))
item.text = u"富强民主文明和谐爱国敬业诚信友善自由平等公正法治:"
item.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
item = table.cell(5, 0).merge(table.cell(5, 1))
p = item.paragraphs[0]
p.add_run().add_picture(tp, Pt(300), Pt(300))
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
def GetLastError():
global last_err
return last_err
def Test():
path = os.path.split(os.path.realpath(__file__))[0]
file = path + "\\word.docx"
Init()
AddLineTitle(u"富强民主")
AddInfoTitle(u"一、文明和谐")
AddLineText(u"爱国敬业")
AddRecord(u"诚信", u"友善", u"自由", u"平等", u"公正",
u"法治", u"社会主义核心价值观", "2.jpg")
Save(file)
Test()
print(GetLastError())
网友评论