1、首先cmd下载fpdf包
pip install fpdf
2、调用fpdf包,先实现写入数据的功能
from fpdf import FPDF
pdf=FPDF()
pdf.add_page()#新建一页
pdf.set_xy(0,0)
pdf.set_font('arial','B',14)#设置字体
pdf.cell(60)#将定位向右移动60个单位
pdf.cell(70,10,'The transcript',0,2,'C')
pdf.cell(-40)#将定位向左移动40个单位
pdf.cell(50,10,'number',1,0,'C')
pdf.cell(40,10,'name',1,0,'C')
pdf.cell(40,10,'score',1,2,'C')
pdf.cell(-90)#将定位向下移动90个单位
pdf.set_font('arial','',12)
pdf.cell(50,10,'10010',border=1,ln=0,align='C')
pdf.cell(40,10,'lilei',border=1,ln=0,align='C')
pdf.cell(40,10,'97',border=1,ln=0,align='C')
pdf.ln()#换行
pdf.cell(10)#将定位向右移动10个单位
pdf.cell(50,10,'10012',border=1,ln=0,align='C')
pdf.cell(40,10,'wangbin',border=1,ln=0,align='C')
pdf.cell(40,10,'69',border=1,ln=0,align='C')
pdf.output('C:\\Users\\caoming\\Desktop\\20200914数据处理\\Excel2PDF.pdf', 'F')
生成如下内容
3、如果想单独生成每个人的成绩单,就可以配合pandas批量写入,将excel中的内容按照姓名分表,再按照一定格式生成个人成绩单。
import pandas as pd
import os
import selectUsecols as su
from fpdf import FPDF
lujing=r'C:\Users\caoming\Desktop\新建文件夹'
file_name='chengjidan.xls'
data_name=os.path.join(lujing,file_name)
wb=pd.read_excel(data_name)
names=su.hee(data_name,[1])
print(names)
pdf = FPDF()
pdf.add_page() # 新建一页
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 14) # 设置字体
pdf.cell(60) # 将定位向右移动60个单位
pdf.cell(70, 10, 'The transcript', 0, 2, 'C')
pdf.cell(-40) # 将定位向左移动40个单位
pdf.cell(50, 10, 'number', 1, 0, 'C')
pdf.cell(40, 10, 'name', 1, 0, 'C')
pdf.cell(40, 10, 'subject', 1, 0, 'C')
pdf.cell(40, 10, 'score', 1, 2, 'C')
pdf.cell(-130) # 将定位向左移动90个单位
for name in names:
chenji=wb[wb['name']==name]
chenji_list = chenji.values.tolist()
n=len(chenji_list)
print(n)
for i in range(n):
pdf.set_font('arial', '', 12)
pdf.cell(50, 10, str(chenji_list[i][0]), border=1, ln=0, align='C')
pdf.cell(40, 10, chenji_list[i][1], border=1, ln=0, align='C')
pdf.cell(40, 10, chenji_list[i][2], border=1, ln=0, align='C')
pdf.cell(40, 10, str(chenji_list[i][3]), border=1, ln=0, align='C')
pdf.ln() # 换行
pdf.ln() # 换行
pdf.output(lujing+'\\'+name+'.pdf', 'F')