1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import os import qrcode import openpyxl from openpyxl.drawing.image import Image from openpyxl.utils import get_column_letter from openpyxl.styles import Alignment
# 配置参数 QR_SIZE_MM = 6 # 固定二维码大小6×6mm QR_PER_ROW = 10 # 每行10个二维码(可根据需要调整) MM_TO_PX = 6 # 毫米到像素的转换系数(96dpi)
def generate_qr_sheet(): # 打开工作簿 wb = openpyxl.load_workbook(excel_file()) # 准备二维码工作表(第二个sheet) if len(wb.worksheets) >= 2: qr_sheet = wb.worksheets[1] qr_sheet.title = "二维码" # 清空现有内容 qr_sheet.delete_rows(1, qr_sheet.max_row) # 移除所有图片 qr_sheet._images = [] else: qr_sheet = wb.create_sheet("二维码") # 数据源工作表 data_sheet = wb.worksheets[0] total_qr = data_sheet.max_row - 1 # 减去标题行 # 创建临时目录 os.makedirs("temp_qr", exist_ok=True) current_row = 1 for i in range(1, total_qr + 1): # 获取数据 text = data_sheet[f'A{i+1}'].value # 生成二维码(临时文件) qr_name = f"temp_qr/QR_{current_row}_{i%QR_PER_ROW or QR_PER_ROW}.png" generate_qr_image(text, qr_name, QR_SIZE_MM) # 计算插入位置 col_num = (i - 1) % QR_PER_ROW + 1 cell = f"{get_column_letter(col_num)}{current_row}" # 插入图片 img = Image(qr_name) img.anchor = cell qr_sheet.add_image(img) # 换行处理 if i % QR_PER_ROW == 0: current_row += 1 # 保存文件 wb.save(excel_file()) print(f"成功生成{total_qr}个{QR_SIZE_MM}×{QR_SIZE_MM}mm二维码,排列在{current_row}行×{QR_PER_ROW}列的表格中")
def generate_qr_image(text, filename, size_mm): """生成固定6×6mm尺寸的二维码""" size_px = int(size_mm * MM_TO_PX) qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_Q, box_size=6, # 较小的box_size以适应小尺寸 border=1 # 较小的边框 ) qr.add_data(text) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img = img.resize((size_px, size_px)) img.save(filename, "PNG", dpi=(96, 96))
def excel_file(): """自动查找Excel文件""" for f in os.listdir(): if f.endswith('.xlsx') and not f.startswith('~$'): return f raise FileNotFoundError("未找到Excel文件")
if __name__ == "__main__": generate_qr_sheet() # 清理临时文件 if os.path.exists("temp_qr"): for f in os.listdir("temp_qr"): os.remove(os.path.join("temp_qr", f)) os.rmdir("temp_qr")
|