XlsxWriter:根据整个单元格值插入特定图像 sheet

XlsxWriter: insert specific images based on cell value throughout sheet

我正在尝试弄清楚如何让 XlsxWriter 循环 sheet 并根据每个单元格值添加/替换单元格值到特定图像(例如单元格值为 1 添加 pic1.jpg,单元格值为2加pic2.jpg,等

我的Excelsheet是这样的: Example sheet

我不知道如何让 Xslxwriter 循环检查每个单元格的值,并在单元格符合条件时使用 worksheet.insert_image 插入图像。

感谢任何帮助!

下载这些测试图片并将它们与脚本一起放在根目录下(当然你可以把它们放在任何你想要的地方但是你需要调整代码以使用例如绝对路径)。

https://i.stack.imgur.com/9nVXn.jpg

https://i.stack.imgur.com/vIGO6.jpg

https://i.stack.imgur.com/Ujwa0.jpg

代码:

import pandas as pd
import numpy as np

# Create a test dataframe
df = pd.DataFrame({
    'Beverage': ['Juice', 'Milk', 'Beer', 'Water'],
    'Copenhagen': [1, 1, 1, 3],
    'Berlin': [2, 1, 1, 3],
    'Oslo': [1, 1, 1, np.nan],
    'Helsinki': [2, 1, np.nan, np.nan]
})

# Pass the df into xlsxwriter
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

# Create a cell format with lock protection turned off so that we can delete the value
unlocked_format = workbook.add_format({'locked': False})

# Iterate through the columns and the rows
max_row = df.shape[0]
max_column = df.shape[1]

for col in range(1,max_column):
    for row in range(0, max_row):
        if (df.iloc[row,col] == 1):
            # Empty the cell's value
            worksheet.write(row+1, col, None, unlocked_format)
            # Insert the image, adjust the scale properties according to the image's size
            worksheet.insert_image(row+1, col, 'pic1.png', {'x_scale': 0.1, 'y_scale': 0.1})
        elif (df.iloc[row,col] == 2):
            worksheet.write(row+1, col, None, unlocked_format)
            worksheet.insert_image(row+1, col, 'pic2.png', {'x_scale': 0.015, 'y_scale': 0.015})
        elif (df.iloc[row,col] == 3):
            worksheet.write(row+1, col, None, unlocked_format)
            worksheet.insert_image(row+1, col, 'pic3.png', {'x_scale': 0.015, 'y_scale': 0.015})

worksheet.write("A1", None, unlocked_format)

writer.save()

初始输出:

最终输出:

这是一种实现您想要的方法,希望您明白了!