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

excel 通过openpyxl表格下载和插入图片

 1。 从表格下载图片

def download_excel_images(excel_path, url_path, output_dir):    # 设置路径os.makedirs(output_dir, exist_ok=True)position_log = []res = []# 方法2:用openpyxl记录单元格位置(需额外安装 pip install openpyxl)wb = load_workbook(excel_path)sheet = wb.activeurl_matrix = {}for i, img in enumerate(sheet._images):# 获取图片位置锚点anchor = img.anchorrow_idx = anchor._from.row  # 0-basedcol_idx = anchor._from.col  # 0-basedtop_left_cell = f"{chr(65+anchor._from.col)}{anchor._from.row+1}"img_name = f"{sheet.title}_img_{i}.png"with open(os.path.join(output_dir, img_name), "wb") as f:f.write(img.ref.getvalue())position_log.append(f"{img_name} | 位置: {sheet.title}!{top_left_cell}") img_data = Image.open(img.ref)img_url = upload_img(img_data)# 按行号分组,每行是一个dictif row_idx not in url_matrix:url_matrix[row_idx] = {}url_matrix[row_idx][col_idx] = img_url# pdb.set_trace()for row in sorted(url_matrix.keys()):row_urls = [url_matrix[row].get(col, "") for col in range(3)]res.append(row_urls)df = pd.DataFrame(res, columns=["图片1_url", "图片2_url", "图片3_url"])df.to_excel(url_path, index=False)

2. 通过图片链接将图片插入表格

def insert_img2excel(excel_path, url_path, output_dir):data = pd.read_excel(excel_path)# 创建一个工作簿wb = Workbook()# 获取默认的活动工作表ws = wb.activews.column_dimensions['C'].width = 100i = 2for index, row in data.iterrows():try:response = requests.get(row["merge_image_url2"])img = response.contentimage_path = os.path.join(output_dir, hashlib.md5(img).hexdigest()[:5] + ".png")# with open(image_path, 'wb') as f:#     f.write(img)# pdb.set_trace()except Exception as e:continueimg = Image.open(BytesIO(img))img.save(image_path)image_data = image.Image(image_path)image_data.width, image_data.height = 100, 100ws.add_image(image_data, "C" + str(i))ws.row_dimensions[i].height = 100image_path = image_pathi = i + 1wb.save(url_path)

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

相关文章:

  • Linux的用户和用户组与权限解析、环境变量说明与配置、sudo配置解析和使用
  • Linux系统下 挂载exfat文件系统U盘
  • 【C语言进阶】字符函数和字符串函数的内部原理
  • 解锁Redis:从安装到配置的全攻略
  • sqli-labs靶场通关笔记:第18-19关 HTTP头部注入
  • 阿里云 Kubernetes 的 kubectl 配置
  • 46. 携带研究材料(01背包二维数组)
  • Rust基础[part4]_基本类型,所有权
  • 深入理解设计模式:组合模式(Composite Pattern)
  • [设计模式]C++单例模式的几种写法以及通用模板
  • Ubuntu18.04 系统重装记录
  • 【高并发服务器】多路复用的总结 eventfd timerfd
  • 复习笔记 39
  • (李宏毅)deep learning(五)--learning rate
  • 单臂路由实现VLAN互通实验
  • 编译原理第一到三章(知识点学习/期末复习/笔试/面试)
  • HashMap详解
  • 优学教育官网搭建01首页
  • 多模态大语言模型arxiv论文略读(157)
  • Node.js 中http 和 http/2 是两个不同模块对比
  • React源码4 三大核心模块之一:Schedule,scheduleUpdateOnFiber函数
  • GBase 8a 与 Spring Boot + MyBatis 整合实战:从环境搭建到CRUD操作
  • Springboot集成SpringSecurity的介绍及使用
  • 【实时Linux实战系列】使用系统调用实现实时同步
  • 【PTA数据结构 | C语言版】前序遍历二叉树
  • 2025国自然青基、面上资助率,或创新低!
  • 板凳-------Mysql cookbook学习 (十一--------11)
  • C#,List<T> 与 Vector<T>
  • 焊接机器人智能节气阀
  • 关于list