如何使用python导出excel文件中的二维码图片?

问题描述 投票:0回答:1

我正在尝试将产品代码转换为二维码并将其导出到 Excel 文件中,但二维码输出为字符串类型。请帮帮我,谢谢。如何使用python将QR码图像导出到excel文件中?这是我的代码:

import pandas as pd
import qrcode
import xlsxwriter
import os
from PIL import Image, ImageDraw, ImageFont

def create_qr_code(product_code, product_name, file_path):
    # Create QR code
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(f"{product_code}, {product_name}")
    qr.make(fit=True)

    # Create an image from the QR code
    img = qr.make_image(fill_color="black", back_color="white")
    return img

# Read data from an Excel file using pandas
# Get the path to the Excel file
file_path = r'C:\Users\DELL\Documents\project\PMS-231116-BME-code.xlsx'
data = pd.read_excel(file_path, skiprows=2)

# Create QR codes for each product in the data
product_codes = []
qr_images = []
for index, column in data.iterrows():
    product_code = column['Asset no.']
    product_name = column['Equipment name']
    img = create_qr_code(product_code, product_name, file_path)
    product_codes.append(product_code)
    qr_images.append(img)

new_data = {'Product name': product_codes, 'Qr code': qr_images}
new_df = pd.DataFrame(new_data)

# Create a new Excel file and write the DataFrame to it
file_path = 'C:/Users/DELL/Documents/project/output_data.xlsx'

with pd.ExcelWriter(file_path) as writer:
    new_df.to_excel(writer, index=False)

我该如何修复此代码?

python excel image qr-code
1个回答
0
投票

您可以使用openpyxl将图像插入excel。并向其中写入数据。这是向您展示如何在程序中使用它的代码。你可以尝试一下。

import openpyxl as op
if __name__ == "__main__":
    wb = op.Workbook()
    ws = wb['Sheet']
    YourData = [{'Product name': 1234, 'Qr code': img}]
    for data in YourData:
        ws.append(data['Product name'])
        ws.add_img(img,'B1')
    wb.save('qrcode.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.