安装第三方库命令
pip install python-docx
import os
from docx import Document
from docx.shared import Pt, Inches, Emu, Cm
from docx.oxml.ns import qn
from openpyxl import load_workbook
def load_xlsx(file):
xls = load_workbook(file)
sheet = xls.active
list = []
for row in range(1, sheet.max_row):
new_list = []
for column in range(1, sheet.max_column + 1):
cell = sheet.cell(row, column).value
new_list.append(cell)
list.append(new_list)
return list
def doc_insert(file_path, file, list):
doc = Document(file_path)
for row in list:
if row[1] in str(file):
print(file, row)
content = row[4]
p_index = 1
for no, p in enumerate(doc.paragraphs): # 遍历文档段落
# print(p.text)
if "2023年03月21日" in p.text:
p.text = p.text.replace('03月21日', '01月12日')
p.style.font.name = u'仿宋_GB2312'
p.style.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
p.style.font.size = Pt(14)
if "六、关于新疆维吾尔自治区" in p.text:
p_index = no
new = doc.paragraphs[p_index - 1]
in_index = doc.paragraphs[p_index]
index_num = int(str(doc.paragraphs[p_index - 1].text).split('.')[0])
a = in_index.insert_paragraph_before(str(index_num + 1) + '.' + content)
a.paragraph_format.first_line_indent = Cm(1)
# a.style.font.size = Pt(14)
# a.runs[0].font.bold = True
a.runs[0].font.size = Pt(14)
# a.style.font.name = 'Times New Roman'
a.style.font.name = u'仿宋_GB2312'
a.style.element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')
ss = doc.paragraphs[p_index]
ss.paragraph_format.element.pPr.ind.set(qn("w:firstLineChars"), '200')
# doc.styles['Normal'].font.size = Pt(10.5)
doc.save(str(file_name))
# file_2 = input('\033[1;32m 请输入表格地址 :\033[0m').replace('\\', '/')
file_2 = '无标题.xlsx'
# path = input(str(i + 1) + '\033[1;32m 请输入文档文件夹地址 :\033[0m').replace('\\', '/')
path = "叶城"
sum = 0
list = load_xlsx(file_2)
for file_name in os.listdir(path):
if '.docx' not in file_name or '$' in file_name:
continue
# print(file_name)
doc_path = path + '/' + file_name
doc_insert(doc_path, file_name, list)
sum += 1
# if sum == 2:
# break
print(f"\033[1;33m ================ 已完成 {sum} 个文件 =================\033[0m")
附:字体大小参照这篇博客的对照表:
字号‘八号’对应磅值5
字号‘七号’对应磅值5.5
字号‘小六’对应磅值6.5
字号‘六号’对应磅值7.5
字号‘小五’对应磅值9
字号‘五号’对应磅值10.5
字号‘小四’对应磅值12
字号‘四号’对应磅值14
字号‘小三’对应磅值15
字号‘三号’对应磅值16
字号‘小二’对应磅值18
字号‘二号’对应磅值22
字号‘小一’对应磅值24
字号‘一号’对应磅值26
字号‘小初’对应磅值36
字号‘初号’对应磅值42
https://gitee.com/hayratjan/
https://github.com/hayratjan/