hey, can you help me to get the script to insert photo in excel by looping in python?
- User
hey, can you help me to get the script to insert photo in excel by looping in python?
- Assistant
Certainly! Here's a sample script that uses openpyxl library to insert photos in Excel by looping through a directory of image files:
pythonimport os from openpyxl import Workbook from openpyxl.drawing.image import Image # Create a new workbook wb = Workbook() # Get the active sheet sheet = wb.active # Directory containing image files image_dir = 'path/to/directory' # Loop through the image files for index, filename in enumerate(os.listdir(image_dir)): if filename.endswith('.jpg') or filename.endswith('.png'): # Calculate the cell reference for image insertion cell_reference = f'A{index + 1}' # Change the column letter as needed # Load the image file img = Image(os.path.join(image_dir, filename)) # Adjust the image dimensions as needed img.width = 200 img.height = 200 # Add the image to the worksheet at the specified cell sheet.add_image(img, cell_reference) # Save the workbook wb.save('output.xlsx') - User
I mean in pandas dataframe
- Assistant
I apologize for the confusion. In pandas, you can't directly insert images into a DataFrame. However, you can achieve a similar outcome by using the Python Imaging Library (PIL) to resize and save the images, and then insert the image file paths into the DataFrame. Here's an example:
pythonimport os import pandas as pd from PIL import Image # Directory containing image files image_dir = 'path/to/directory' # Create an empty DataFrame df = pd.DataFrame(columns=['Name', 'Image']) # Loop through the image files for filename in os.listdir(image_dir): if filename.endswith('.jpg') or filename.endswith('.png'): # Read the image file img = Image.open(os.path.join(image_dir, filename)) # Resize the image as needed img = img.resize((200, 200)) # Save the resized image output_filename = f'resized_{filename}' img.save(os.path.join(image_dir, output_filename)) # Add the image file path to the DataFrame df = df.append({'Name': filename, 'Image': output_filename}, ignore_index=True) # Display the DataFrame print(df)