当前位置: 首页 > news >正文

【Python】Excel表格操作:ISBN转条形码

一、效果

原始文件:

输出文件:

二、代码

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 ImageWriterlogging.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 textean = EAN13(barcode_str, writer=ImageWriter())saved_path = ean.save(output_path_without_ext)return saved_pathdef 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.activelogging.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}")continueimg_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}")continueimg_for_excel = ExcelImage(img_path)img_for_excel.width = 180img_for_excel.height = 60img_cell = f'{imgCol}{row}'# # 设置列宽ws.column_dimensions[imgCol].width = img_for_excel.width * 0.15# # 设置行高ws.row_dimensions[row].height = img_for_excel.heightws.add_image(img_for_excel, img_cell)# 调整当前行高,避免图片重叠current_height = ws.row_dimensions[row].heightif 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。

http://www.xdnf.cn/news/1062289.html

相关文章:

  • RPC常见问题回答
  • Qwen3 Embedding 结构-加载-训练 看透模型设计哲学
  • windows查看占用端口的进程并杀死进程
  • phpstudy无法启动apache,80端口被占用,完美解决
  • 【MySQL篇10】:四种分库分表详解
  • Symbol.iterator 详解
  • Windows 10 防火墙 0x8007045b 打不开
  • Rust 项目文档生成之旅:cargo doc
  • 博士,超28岁,出局!
  • MySQL复杂查询优化实战:从多表关联到子查询的性能突破
  • 掌握Bash脚本编写:从服务启动脚本到语法精要
  • Xilinx XC7A12T‑1CPG238I Artix‑7 FPGA
  • SAM2论文解读-既实现了视频的分割一切,又比图像的分割一切SAM更快更好
  • 猿人学js逆向比赛第一届第九题
  • 基于物联网的智能衣柜系统设计
  • Redis如何解决缓存击穿,缓存雪崩,缓存穿透
  • .docx 和 .doc 都是 Word 文档格式的区别
  • 华为 FreeArc耳机不弹窗?
  • css 实现1个像素在不同分辨率屏幕上画网格线
  • 如何正确处理音频数据:16位整数与32位浮点数
  • 【考研数学:高数11】一元函数积分学的应用(二)——积分等式和积分不等式
  • SSE 流与普通 HTTP 响应的区别
  • FPGA基础 -- Verilog 层次路径名
  • 物体变化下的迈克尔逊干涉:条纹密度、载波解调与双曝光去畸变
  • DAY 54 python打卡
  • 解锁数据宝藏:数据挖掘之数据预处理全解析
  • 【MySQL性能优化】DISTINCT和GROUP BY去重性能深度剖析
  • 基于存储过程的MySQL自动化DDL同步系统设计
  • 技术评测:三丰云免费服务器的真实能力边界
  • Vue 比较两个数组对象,页面展示差异数据值