- 用python实现批量生成包含变量字段(从excel读取)的固定格式excel文档;
- 参见下述代码:
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 11:46:52 2018
@author: onlyonelucas
"""
import pandas as pd
import xlrd
import xlwt
from xlutils.copy import copy #导入copy模块
excelFile = r'选票数据来源.xlsx' #变量字段excel来源
df = pd.DataFrame(pd.read_excel(excelFile))
for index,row in df.iterrows(): #遍历各行
a=row['ID']
c1=row['N1']
c2=row['N2']
c3=row['N3']
c4=row['N4']
c5=row['N5']
c6=row['N6']
d=row['F']
rb = xlrd.open_workbook('选票.xls',formatting_info=True) #打开批量生成excel模板文件
wb = copy(rb) #利用xlutils.copy下的copy函数复制
ws = wb.get_sheet(0) #获取第一个sheet
rs=rb.sheet_by_index(0)
style1 = xlwt.XFStyle()
fnt = xlwt.Font() # 创建一个文本格式,包括字体、字号和颜色样式特性
fnt.name = u'宋体' # 设置其字体
fnt.height = 320 # 16 * 20, for 16 point
fnt.bold = True
style1.font = fnt #将赋值好的模式参数导入Style
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER #水平居中
alignment.vert = xlwt.Alignment.VERT_CENTER #垂直居中
style1.alignment = alignment
ws.write(0,0,"某某医院第九次党代会代表选举投票单(%s)" % (a),style1) #改变(0,0)的值 & 变量字段格式化
ws.write(3,5,c1) #改变(3,5)的值
ws.write(4,5,c2)
ws.write(5,5,c3)
ws.write(6,5,c4)
ws.write(7,5,c5)
ws.write(8,5,c6)
ws.write(10,5,d) #改变(10,5)的值
wb.save(str(a)+'选票.xls') #保存文件