docx介绍
一、导入&创建&保存
from docx import Document
from docx.shared import Cm,Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TAB_ALIGNMENT
from docx.enum.table import wD_CELL_VERTICAL_ALIGNMENT
# 创建
doc = Document()
#编辑内容与设置格式
.....
.....
.....
#保存
doc.save("文档.docx")
shared:共享的
alignment 水平直线,定线
vertical 垂直
二、全局字体样式设置
doc.style["Normal"].font.size = Pt(12)
doc.style["Normal"].font.name = u"Times New Roman"
doc.style["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
三、标题与标题的样式设置
# 整理一个接口函数,可以扩充完善
def set_head_style(doc, head_content, level, size):
"""
doc: word文档对象
head_content: 标题的内容
level: 标题的等级,一级标题、二级标题、三级标题
size: 标题的大小
"""
head = doc.add_heading("", level=level)
run = head.add_run(head_content)
run.font.name = u'Times New Roman'
run.font.size = Pt(size)
# run.font.color.rgb = RGBColor(255, 255, 0)
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
run.bold = True # 加粗
四、段落与段落的样式设置
paragraph_content = '这是我的第一个段落,用来测试,内容是..............'
paragraph_1 = doc.add_paragraph(paragraph_content)
# 设置样式
paragraph_1.paragraph_format.left_indent = Cm(0.75) # 段首缩进(word只有左侧才将段首缩进)
paragraph_1.paragraph_format.space_after = Pt(5)
# 段落居中如何设置
paragraph_1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
paragraph_1.paragraph_format.space_after = Pt(0)
五、表格与表格的样式设置
表格由表名和二维表格组成,而所有的表格的表名都是居中的一个段落,二维表格中,表格的首行一定是表头,代码生成任何一个表格的模板如下:
# 1. 生成表名
p1 = doc.add_paragraph("表1 [表名]表")
# 设置表名格式,所有的都是居中
p1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
p1.paragraph_format.space_after = Pt(0)
# 2. 生成表格
# 生成一个表头
t1 = doc.add_table(row=1, cols=3, style='Table Grid') # 生成一个一行三列的表格
t1.alignment = WD_TAB_ALIGNMENT.CENTER
t1.style.paragraph_format.alignment = WD_TAB_ALIGNMENT.CENTER # 字体居中
t1.autofit = False
# 填充表头内容
t1_head_0 = t1.cell(0,0).paragraph[0].add_run("项目编号") ###### 表格填充内容的第一种方法
t1_head_0.bold = True # 加粗
t1_head_1 = t1.cell(0,1).paragraph[0].add_run("项目名称")
t1_head_1.bold = True # 加粗
t1_head_2 = t1.cell(0,2).paragraph[0].add_run("项目责任人")
t1_head_2.bold = True # 加粗
# 3. 填充Json或者字典格式的数据
"""
data_dic =
{
"type": {
"typename":"csc10003",
"MS":0,
"T":5.0,
"bond_layer_strength_paras":{
"Gb":28000.0,
"Tb":0.00017
},
"l":0.008,
"lower_strength_paras":{
"El":724.0,
"Tl":0.0166
},
"up_strength_paras":{
"Eu":724.0,
"Tu":0.00166
},
"X":0.0040
}
}
"""
# 所有字典数据填充表格,都采用这种模式
data = data_dic["type"]
for key,value in data.items():
if 'typename' == key:
continue
elif "bond_layer_strength_paras" == key:
cells01 = t1.add_row().cells ###### 表格填充内容的第二种方法
cells01[0].text = key
cells01[1].text = "Gb"
cells01[2].text = str(value["Gb"])
cells02 = t1.add_row().cells
cells02[0].text = key
cells02[1].text = "Tb"
cells02[2].text = str(value["Tb"])
# 把两行,参数一致的地方上下表格合并,但是注意合并后,只保留一个值
cells01[0].merge(cells02[0])
cells01[0].text = key
elif "" == key:
......
......
else:
cells = t1.add_row().cells
cells[0].text = key
cells[1].text = key
cells[2].text = str(value)
# 设置表格内,每个格子的格式
for row in t1.rows:
row.height = Cm(1.2)
for cell in row.cells:
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER # 单元格居中
六、基于win32com库合并多个word操作
from win32com import client
# 打开word软件
word = client.gencache.EnsureDispatch('Word.Application')
# 把word软件设置成非可视化运行
word.Visible = True
# 新建一个合并后的空白文档
output = word.Documents.Add()
for file in os.listdir(root_dir):
if str(file).endswith("docx"):
output.Application.Selection.Range.InsertFile(abspath(file))
res_file = os.path.join(root_dir, "分析报告.docx")
output.SaveAs(res_file)
output.Close()
word.Quit()