How does Python batch insert pictures into Excel as hyperlinks

【R&D background】

In daily office work, we often need to insert pictures into Excel, but if too many pictures are inserted, the file memory of Excel will become larger and larger, but if I directly insert the path of the picture, or just change a certain column The data set as a hyperlink, in this way, we will greatly reduce the memory size of the file

The first step is to open an Excel

My column A is my keyword, I want it to be a hyperlink to a picture, as shown in Figure 1

Preconditions: A列的每一个超链接文字,必须能通过这个文字找到这个图片!!, as shown in Figure 2

insert image description here
insert image description here

Directory structure (modify according to your actual situation!)

Folder [data source] - store the source files you want to set hyperlinks

Folder [Accessories] - the folder where your pictures are stored

Folder [result] - the folder where the file result is stored after saving

insert image description here

The third-party library that needs to be used is just an openpyxl

library Install
openpyxl pip install openpyxl

Precautions ( 一定要看啊 一定要看啊 一定要看啊)

1. On line 5 of the code, here is the path where the attachment is inserted, please use the absolute path!filePath = 'F:\随笔\测试\附件\\'

2. On line 8 of the code, pay attention to the sheet you are operating on,sheet1 = sheets[0] # 读取第一个表格

3. In the 10th line of the code, it refers to which column of text you want to use as a hyperlink, here A is column A, modify it according to the actual situation! !for col in sheet1['A']: # 遍历表格第一列内容

4. In the 12th line of the code, col1.append(col.value[13:]), here I sliced ​​it, because my table contains a complete path, and I need to cut out the name of the attachment! ! , please modify it according to the actual situation!

Full version code:

import os
import openpyxl  # 处理xlsx文件模块

fileName = './数据源/' + os.listdir('./数据源/')[0]  # xlsx文件相对路径
filePath = './附件/'  # 图片所在文件夹路径
wb = openpyxl.load_workbook(fileName)  # 加载表格
sheets = wb.worksheets  # 读取表格内容
sheet1 = sheets[0]  # 读取第一个表格
col1 = []  # 存放表格第一列内容
for col in sheet1['A']:  # 遍历表格第一列内容
    if col.value != None:
        col1.append(col.value[13:])  # 这里我切片了,是因为我表格里是完整的路径,我需要切出附件的名字!!
lists = os.listdir(filePath)  # 读取图片名称
ws = wb.active  # 激活
for l in lists:  # 遍历存放图片名称的数组
    if l in col1:  # 找到图片名对应的列表标签
        i = int(col1.index(l)) + 1  # 用index()获取元素下标
        path = os.path.join(filePath, l)
        ws.cell(i, 1).value = ('=HYPERLINK("{}","{}")'.format(path, ws.cell(i, 1).value))  # 以超链接方式写入表格单元
wb.save('./结果/res.xlsx')  # 一定要保存表格

video display

insert image description here

I hope it can be helpful to everyone. If there is any mistake, please correct me.

A little programmer dedicated to office automation

Hope to get [a free follow] from everyone! grateful

Guess you like

Origin blog.csdn.net/weixin_42636075/article/details/131591231