一、
1. 向word或者txt文件写入并保存
#第一种 print输出 向文件输出内容
file=open('d:/1.txt',mode='w+',encoding='utf-8')
file.write("奋斗改变未来")
# 读数据时光标回到开头
file.seek(0)
# 将数据从文件读进内存中
file_content=file.read()
# 将内存中的数据打印到控制台
print(file_content)
file.close()
# 第二种更加简单
f=open('d:/2.txt','a+')
print('奋斗成就更好的你',file=f)
f.close()
#第三种
with open('d:/3.txt','w') as file:
file.write('杨江澜很帅')
# 有了上下文工作之后,就不用file.close了
实例操作:
-----------------------------------
季度 1 2 3 4
-----------------------------------
补贴 1000 1000 2000 2000
-----------------------------------
2. 批量生成合同文件
from docx import Document
from openpyxl import load_workbook
# 利用os模块建立文件夹,用于存放生成的合同
import os
# 给定合同模板和汇总表所在的文件夹路径,方便复用
path = r'C:\Users\admin\Desktop\合同'
# 结合路径判断生成文件夹,规避程序报错而终止的风险
if not os.path.exists(path + '/' + '全部合同'):
os.mkdir(path + '/' + '全部合同')
workbook = load_workbook(path + '/' + '合同信息表.xlsx')
sheet = workbook.active
for table_row in range(2, sheet.max_row + 1):
wordfile = Document(path + '/' + '合同模板.docx')
for table_col in range(1, sheet.max_column + 1):
old_text = str(sheet.cell(row=1, column=table_col).value)
new_text = str(sheet.cell(row=table_row, column=table_col).value)
if ' ' in new_text:
new_text = new_text.split()[0]
# 文档Document - 段落Paragraph - 文字块Run
all_paragraphs = wordfile.paragraphs
for paragraph in all_paragraphs:
for run in paragraph.runs:
run.text = run.text.replace(old_text, new_text)
# 文档Document - 表格Table - 行Row/列Column - 单元格Cell
all_tables = wordfile.tables
for table in all_tables:
for row in table.rows:
for cell in row.cells:
cell.text = cell.text.replace(old_text, new_text)
# 获取公司名用以生成合同的名称
company = str(sheet.cell(row=table_row, column=1).value)
wordfile.save(path + '/' + f'全部合同/{company}合同.docx')
原理 就是文字替换 例如: #发包人# 换成 A公司
这里要求合同信息表中字段名要同 合同模板中一致。
这里导包有一个问题,就是python-docx 和docx 不是一回事,要导入前者。不然会报问题。
实例操作:批量生成校园邀请函
from docx import Document
from openpyxl import load_workbook
# 利用os模块建立文件夹
import os
# 给定模板和汇总表所在的文件夹路径,方便复用
path = r'C:\Users\admin\Desktop\邀请函'
# 结合路径判断生成文件夹,规避程序报错而终止的风险
if not os.path.exists(path + '/' + '全部邀请函'):
os.mkdir(path + '/' + '全部邀请函')
workbook = load_workbook(path + '/' + '校庆邀请函数据.xlsx')
sheet = workbook.active
for table_row in range(2, sheet.max_row + 1):
wordfile = Document(path + '/' + '邀请函.docx')
for table_col in range(1, sheet.max_column + 1):
old_text = str(sheet.cell(row=1, column=table_col).value)
new_text = str(sheet.cell(row=table_row, column=table_col).value)
if ' ' in new_text:
new_text = new_text.split()[0]
# 文档Document - 段落Paragraph - 文字块Run
all_paragraphs = wordfile.paragraphs
for paragraph in all_paragraphs:
for run in paragraph.runs:
run.text = run.text.replace(old_text, new_text)
# 文档Document - 表格Table - 行Row/列Column - 单元格Cell
all_tables = wordfile.tables
for table in all_tables:
for row in table.rows:
for cell in row.cells:
cell.text = cell.text.replace(old_text, new_text)
# 获取id用以生成邀请函的名称
name = str(sheet.cell(row=table_row, column=1).value)
wordfile.save(path + '/' + f'全部邀请函/{name}邀请函.docx')
print("运行完毕")