怎么用python把图片按图片名导入到excel中
时间: 2023-08-04 17:13:54 浏览: 241
你可以使用 Python 中的 Pandas 库来导入图片到 Excel 中。具体步骤如下:
1. 安装 Pandas 库:在命令行中输入 `pip install pandas`。
2. 导入 Pandas 库:在代码中输入 `import pandas as pd`。
3. 创建一个空的 Pandas DataFrame 对象:`df = pd.DataFrame()`。
4. 使用 Pandas 的 `read_excel` 方法读取 Excel 文件:`df = pd.read_excel('your_excel_file.xlsx')`。
5. 遍历文件夹中的所有图片,将图片名和图片路径保存在一个字典中:
```
import os
img_dir = 'your_image_directory'
img_dict = {}
for file_name in os.listdir(img_dir):
if file_name.endswith('.jpg'): # 只处理 jpg 格式的图片
img_path = os.path.join(img_dir, file_name)
img_dict[file_name] = img_path
```
6. 遍历 DataFrame 中的每一行,将图片路径填入对应的单元格中:
```
for index, row in df.iterrows():
img_name = row['图片名'] # 你的 Excel 表格中图片名所在列的名称
if img_name in img_dict:
img_path = img_dict[img_name]
img_url = f'=HYPERLINK("{img_path}", "点击查看")' # 将图片路径转换为超链接
df.at[index, '图片'] = img_url # 填入单元格中
```
7. 使用 Pandas 的 `to_excel` 方法将 DataFrame 保存为 Excel 文件:`df.to_excel('output_excel_file.xlsx', index=False)`。
完整代码如下:
```
import os
import pandas as pd
# 读取 Excel 文件
df = pd.read_excel('your_excel_file.xlsx')
# 遍历文件夹中的所有图片,将图片名和图片路径保存在一个字典中
img_dir = 'your_image_directory'
img_dict = {}
for file_name in os.listdir(img_dir):
if file_name.endswith('.jpg'): # 只处理 jpg 格式的图片
img_path = os.path.join(img_dir, file_name)
img_dict[file_name] = img_path
# 遍历 DataFrame 中的每一行,将图片路径填入对应的单元格中
for index, row in df.iterrows():
img_name = row['图片名'] # 你的 Excel 表格中图片名所在列的名称
if img_name in img_dict:
img_path = img_dict[img_name]
img_url = f'=HYPERLINK("{img_path}", "点击查看")' # 将图片路径转换为超链接
df.at[index, '图片'] = img_url # 填入单元格中
# 将 DataFrame 保存为 Excel 文件
df.to_excel('output_excel_file.xlsx', index=False)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)