python实现根据excle内容批量生成二维码

背景

今天有朋友有批量生成二维码的需求,虽然量不是太大,但要人工一个一个生成也是很非时间的,而且我在网上找了下,没有现成的工具,于是就自己动手花了10分钟用python写了个根据excel批量生成二维码工具的小脚本

excle模板

python实现根据excle内容批量生成二维码

用到的python模块

  • qrcode
  • xlrd

安装模块

pip install qrcode
pip install xlrd

python代码

import qrcode
import xlrd
import os

def read_excel_sheet(path,sheetname = "Sheet1"):
    try:
        data = xlrd.open_workbook(path)
        sheet = data.sheet_by_name(sheetname)
        return sheet
    except Exception as e:
        print(e)


def create_qrcode(name,content,path=''):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=1
    )
    qr.add_data(content)
    qr.make(fit=True)
    img = qr.make_image()
    file = '{}.png'.format(os.path.join(path,name))
    print(file)
    with open(file,'wb') as f:
        img.save(f)

if __name__ == "__main__":
    sheet = read_excel_sheet('qrcode.xlsx',sheetname = 'Sheet1')
    nrows = sheet.nrows
    for i in range(nrows):
        row = sheet.row_values(i)
        tw = row[0]
        name = row[1]
        mobile = int(row[2]) if type(row[2]) is float else row[2]
        yyzz = int(row[3]) if type(row[3]) is float else row[3]

        filename = '{}_{}_{}_{}'.format(tw,name,mobile,yyzz)
        content = '位置:{}\n 姓名:{}\n 代码:{}\n 电话:{}'.format(tw,name,yyzz,mobile)

        create_qrcode(filename,content,path="./tmp")

将代码保存成create_batch_qrcode.py,并在同目录下创建文件夹tmp

执行python脚本

python create_batch_qrcode.py

搞定