想在docx表格中插入图
使表格框线设置为白色,即隐藏。
以下代码为设置框线
参考:http://officeopenxml.com/WPtableBorders.php
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def set_cell_border(cell, **kwargs):
"""
Set cell`s border
Usage:
set_cell_border(
cell,
top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
bottom={"sz": 12, "color": "#00FF00", "val": "single"},
left={"sz": 24, "val": "dashed", "shadow": "true"},
right={"sz": 12, "val": "dashed"},
)
"""
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# check for tag existnace, if none found, then create one
tcBorders = tcPr.first_child_found_in("w:tcBorders")
if tcBorders is None:
tcBorders = OxmlElement('w:tcBorders')
tcPr.append(tcBorders)
# list over all available tags
for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
edge_data = kwargs.get(edge)
if edge_data:
tag = 'w:{}'.format(edge)
# check for tag existnace, if none found, then create one
element = tcBorders.find(qn(tag))
if element is None:
element = OxmlElement(tag)
tcBorders.append(element)
# looks like order of attributes is important
for key in ["sz", "val", "color", "space", "shadow"]:
if key in edge_data:
element.set(qn('w:{}'.format(key)), str(edge_data[key]))
以下为全代码。首先读取doc文件和目录,写进列表,如果文件与目录同名,则把目录下的4张图放进一个3行*2列的表格中,前两行里合并为一行,最后一行两个图,并设置框线为白色,隐藏起来,
from docx import Document #pip3 install python-docx
from docx.shared import Inches #英寸
import os
#from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Cm #厘米
from docx.shared import RGBColor
from docx.enum.table import WD_TABLE_ALIGNMENT #表格排列方式
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.text import WD_ALIGN_PARAGRAPH
from natsort import natsorted #自然排序
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def set_cell_border(cell, **kwargs):
"""
Set cell`s border
Usage:
set_cell_border(
cell,
top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
bottom={"sz": 12, "color": "#00FF00", "val": "single"},
left={"sz": 24, "val": "dashed", "shadow": "true"},
right={"sz": 12, "val": "dashed"},
)
"""
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# check for tag existnace, if none found, then create one
tcBorders = tcPr.first_child_found_in("w:tcBorders")
if tcBorders is None:
tcBorders = OxmlElement('w:tcBorders')
tcPr.append(tcBorders)
# list over all available tags
for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
edge_data = kwargs.get(edge)
if edge_data:
tag = 'w:{}'.format(edge)
# check for tag existnace, if none found, then create one
element = tcBorders.find(qn(tag))
if element is None:
element = OxmlElement(tag)
tcBorders.append(element)
# looks like order of attributes is important
for key in ["sz", "val", "color", "space", "shadow"]:
if key in edge_data:
element.set(qn('w:{}'.format(key)), str(edge_data[key]))
path=input('输入整理路径: ')
jpglists=[]
if path=="":
path=os.getcwd()
#print(path)
dirlists=[]
for file in os.listdir(path):
#print(file)
filename=os.path.join(path,file)
#print(filename)
if os.path.isdir(filename):
dirlists.append(filename)
print(dirlists)
# exit()
for dirlist in dirlists:
if not os.path.exists(dirlist+".doc"):
print("目录存在,无对应文件{} 存在,忽略....".format(dirlist+".doc"))
pass
else:
path1=os.path.join(path,dirlist)
print('path1-----',path1)
# exit()
jpglists=[]
for file in os.listdir(path1):
#print(file)
if os.path.splitext(file)[1].lower() in '.emf|.wmf|.jpg|.jpeg|.jfif|.jpe|.png|.bmp|.dib|.rle|.gif|.emz|.wmz|.tiff|.tiff|.svg|.ico':
jpglists.append(file)
jpglists=natsorted(jpglists)
#print(jpglists)
document = Document(dirlist+".doc")
rownums=int(len(jpglists)-1)
# if len(jpglists)%2==0:
# else:
# rownums=int(len(jpglists)/2+1)
#print('设表格行',rownums)
if len(jpglists)!=0:
#插入表格 表格是从1,0开始,第一行就是1,列是从0开始,NND
table = document.add_table(rows=rownums,cols=2,style ='Table Grid')
for rownum in range(rownums):
table.rows[rownum].height=Cm(7)
cell=table.cell(rownum,0)
# if rownum==0:
# cell.add_paragraph('附***照片\n')
p=cell.paragraphs[-1]
cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER #水平 居中
cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER #竖直居中
if rownum==0:
jpghid=19.3
elif rownum==2:
jpghid=9.2
else:
jpghid=12.2
run = p.add_run()
run.add_picture(os.path.join(path1,jpglists[int(rownum)]), height=Cm(jpghid)) # ,width=Cm(jpgwid))
#print('写入',str(rownum),"0",os.path.join(path1,jpglists[int((rownum)*2)]))
set_cell_border(cell,
top={"sz": 12 ,"val": "single", "color": "FFFFFF", "space": "0"},
bottom={"sz":12, "color": "FFFFFF", "val": "single"},
left={"sz":12 , "val": "dashed", "color": "FFFFFF","shadow": "true"},
right={"sz": 10, "color": "FFFFFF","val": "dashed"},
insideH={"color": "FFFFFF"},)
if rownum==0:
cell.add_paragraph('钻孔柱状图')
cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
if rownum==1:
cell.add_paragraph('经纬度截图')
cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
if rownum==2:
cell.add_paragraph('照片1 现场照片')
cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# jpghid=9.2
if rownum==rownums-1:
cell=table.cell(rownum,1)
p=cell.paragraphs[0]
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER #水平 居中
cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER #竖直居中
run = p.add_run()
run.add_picture(os.path.join(path1,jpglists[int((rownum)+1)]), height=Cm(jpghid)) #width=Cm(7.02)) # ,height=Cm(3.95))
#print('写入',str(rownum),"1",os.path.join(path1,jpglists[int((rownum)*2)+1]))
cell.add_paragraph('照片2 现场照片')
cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
set_cell_border(cell,
top={"sz": 12 ,"val": "single", "color": "FFFFFF", "space": "0"},
bottom={"sz":12, "color": "FFFFFF", "val": "single"},
left={"sz":12 , "val": "dashed", "color": "FFFFFF","shadow": "true"},
right={"sz": 10, "color": "FFFFFF","val": "dashed"},
insideH={"color": "FFFFFF"},)
else:
cell.merge(table.cell(rownum,1)) # 合并单元格
# table.cell(r,c).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
# WD_ALIGN_VERTICAL.TOP|WD_ALIGN_VERTICAL.BOTTOM
#table.cells0[0].add_paragraph('院(系)\n')
#p = document.add_paragraph('This is paragraph')
#合并表格
#table.cell(0,0).merge(table.cell(2,2))
#table.cols[0].weight=Cm(7.51)
# for jpglist in jpglists:
# document.add_picture(os.path.join(path1,jpglist), width=Inches(6)) #插入图片
document.save(dirlist+".docx") #保存文档
print('保存文件 {} ........'.format(dirlist+".docx"))
print()
input('按任意键退出。。。。。。。')