当前位置: 代码网 > it编程>前端脚本>Python > Python Excel操作之将ISBN转条形码

Python Excel操作之将ISBN转条形码

2025年06月22日 Python 我要评论
一、效果原始文件:输出文件:二、代码import osimport loggingfrom openpyxl import load_workbookfrom openpyxl.drawing.ima

一、效果

原始文件:

输出文件:

二、代码

import os
import logging
from openpyxl import load_workbook
from openpyxl.drawing.image import image as excelimage
from barcode import ean13
from barcode.writer import imagewriter
 
logging.basicconfig(level=logging.info, format='%(asctime)s - %(levelname)s - %(message)s')
 
 
def delete_files(directory):
    file_list = os.listdir(directory)
    for file in file_list:
        file_path = os.path.join(directory, file)
        if os.path.isfile(file_path):
            os.remove(file_path)
 
 
def generate_barcode_image_with_text(barcode_str, output_path_without_ext):
    # generate barcode image without text
    ean = ean13(barcode_str, writer=imagewriter())
    saved_path = ean.save(output_path_without_ext)
 
    return saved_path
 
 
def insert_barcodes_to_excel(excel_file, isbncol, imgcol):
    logging.info("开始处理")
 
    if not os.path.exists('barcode_temp'):
        os.makedirs('barcode_temp')
 
    wb = load_workbook(excel_file)
    ws = wb.active
    logging.info(f"加载工作表: {ws.title}")
 
    img_height_in_points = 45  # 你设置的图片高度,单位是磅,1磅约等于1.33像素
 
    for row in range(2, ws.max_row + 1):
        barcode_cell = ws.cell(row=row, column=isbncol)
        barcode_str = str(barcode_cell.value).strip()
        if not barcode_str or len(barcode_str) != 13 or not barcode_str.isdigit():
            logging.warning(f"第{row}行条码格式不正确,跳过: {barcode_str}")
            continue
 
        img_path_no_ext = os.path.join('barcode_temp', f'barcode_{barcode_str}')
        try:
            img_path = generate_barcode_image_with_text(barcode_str, img_path_no_ext)
        except exception as e:
            logging.error(f"生成条码失败,行{row},条码{barcode_str},错误: {e}")
            continue
 
        img_for_excel = excelimage(img_path)
        img_for_excel.width = 180
        img_for_excel.height = 60
 
        img_cell = f'{imgcol}{row}'
 
        # # 设置列宽
        ws.column_dimensions[imgcol].width = img_for_excel.width * 0.15
        # # 设置行高
        ws.row_dimensions[row].height = img_for_excel.height
 
        ws.add_image(img_for_excel, img_cell)
 
        # 调整当前行高,避免图片重叠
        current_height = ws.row_dimensions[row].height
        if current_height is none or current_height < img_height_in_points:
            ws.row_dimensions[row].height = img_height_in_points
 
        # logging.info(f"插入条码图片到 {img_cell} 并调整行高")
 
    new_file = os.path.splitext(excel_file)[0] + '_with_barcodes.xlsx'
    try:
        wb.save(new_file)
        logging.info(f"保存新文件: {new_file}")
    except permissionerror:
        logging.error(f"保存文件失败,可能文件被打开: {new_file}")
 
    if os.path.exists('barcode_temp'):
        logging.info("删除临时文件")
        delete_files('barcode_temp')
 
    logging.info("完成处理!")
 
 
if __name__ == "__main__":
    excel_path = 'd:\\temp\\图书清单.xlsx'
    insert_barcodes_to_excel(excel_path, 1, "b")

三、说明

1、insert_barcodes_to_excel参数1:原始excel表格文件绝对路径。

2、insert_barcodes_to_excel参数2:isbn所在列,数字格式。例如:isbn在a列则输入1,在b列则输入2。

3、insert_barcodes_to_excel参数3:生成的条形码需要放在第几列,大写字母格式。例如:需要放在第二列则输入b,第三列则输入c。

到此这篇关于python excel操作之将isbn转条形码的文章就介绍到这了,更多相关python isbn转条形码内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com