Backend Development
Python Tutorial
Tutorial on inserting pictures into specific cells in Excel using openpyxl
Tutorial on inserting pictures into specific cells in Excel using openpyxl

This article details how to insert pictures into specific cells of an Excel worksheet using Python's `openpyxl` library. The tutorial covers the key steps of loading an image, anchoring it to a specific cell, and automatically adjusting the row height and column width of the cell based on the image size. Through these methods, you can achieve the effect of the picture being perfectly visually adapted and "embedded" in the specified cell, instead of just being a floating object.
In data visualization and report generation, it is sometimes necessary to display pictures directly in Excel cells to enhance the readability and intuitiveness of the data. However, many users encounter a common problem when using the openpyxl library: images are often added to the worksheet as floating objects, rather than "embedded" into specific cells. This tutorial will guide you in detail on how to use the functions of openpyxl to accurately place the image into the specified cell and adjust the cell size to fit the image.
Core steps: Insert pictures into specified cells
The openpyxl library allows you to add images to a worksheet and control their position by specifying anchor points. The key is to use the worksheet.add_image(image_object, cell_reference) method, where the cell_reference parameter is the cell you want the upper left corner of the image to be aligned to.
First, you need to import the necessary modules, create a workbook and worksheet, and then load your images.
from openpyxl import Workbook from openpyxl.drawing.image import Image # Create a new workbook and active worksheet wb = Workbook() ws = wb.active # Specify the path to the image file # Please replace "path/to/your/image.jpg" with your actual image path img_path = "path/to/your/image.jpg" #Load image img = Image(img_path) # Add the image to the worksheet and anchor it to the 'A1' cell # This means that the upper left corner of the image will be aligned with the upper left corner of the 'A1' cell ws.add_image(img, 'A1')
Key optimization: adjust cells according to image size
Simply anchoring the image to the cell is not enough, the image itself may be larger or smaller than the cell, resulting in poor display. To make the image appear to be "embedded" in the cell, we need to adjust the row height and column width of the target cell (and adjacent cells) according to the actual size of the image.
The image size in openpyxl is in EMUs (English Metric Units), while the column width and row height in Excel are in character width and points (points) respectively. Therefore, an approximate conversion factor is needed to map image dimensions to cell dimensions. It has been verified that dividing the picture width by 6 can roughly get the appropriate column width, and dividing the picture height by 18 can roughly get the appropriate row height.
# ... (continue from above code)
# Get the width and height of the image object (in EMUs)
# The img.width and img.height properties provide the original dimensions of the image # Note: These values are internal representations and need to be converted to be used with Excel's column width and row height img_width_emu = img.width
img_height_emu = img.height
# Adjust the width of column 'A' to fit the width of the picture # Experience value: Divide the width of the picture EMUs by 6, you can approximate the Excel column width ws.column_dimensions['A'].width = img_width_emu / 6
# Adjust the height of row 1 to adapt to the height of the picture # Experience value: Divide the height of the picture EMUs by 18, you can approximately get the Excel row height ws.row_dimensions[1].height = img_height_emu / 18
# Save the workbook wb.save("output_with_image_in_cell.xlsx")
Complete sample code
Here is the complete sample code to insert a picture into a specified cell and adjust the cell size:
from openpyxl import Workbook
from openpyxl.drawing.image import Image
import os # Used to check whether the file exists, optional def insert_image_into_excel_cell(image_path, cell_reference, output_filename="output_with_image.xlsx"):
"""
Insert the picture into the specified cell of the Excel worksheet, and adjust the cell size to fit the picture.
Args:
image_path (str): The full path of the image file.
cell_reference (str): Reference of the target cell, such as 'A1'.
output_filename (str): The name of the generated Excel file.
"""
if not os.path.exists(image_path):
print(f"Error: Image file does not exist at '{image_path}'")
return
wb = Workbook()
ws = wb.active
#Load image img = Image(image_path)
#Add the image to the worksheet and anchor it to the specified cell ws.add_image(img, cell_reference)
# Parse the cell reference to get the column letter and row number # For example, for 'A1', column_letter='A', row_number=1
from openpyxl.utils import get_column_letter, column_index_from_string
column_letter = ''.join(filter(str.isalpha, cell_reference))
row_number = int(''.join(filter(str.isdigit, cell_reference)))
# Adjust the column width and row height to fit the picture # The picture size of openpyxl is EMUs, and the column width and row height of Excel have different units # The divisor here is an empirical value, which may need to be fine-tuned according to the actual situation ws.column_dimensions[column_letter].width = img.width / 6
ws.row_dimensions[row_number].height = img.height / 18
# Save the workbook wb.save(output_filename)
print(f"The picture has been successfully inserted into the '{cell_reference}' cell of '{output_filename}'.")
# --- Usage example ---
# Make sure to replace with your actual image path my_image_path = "example_image.jpg" # Assume you have an image named example_image.jpg in the same directory # Create an example image file if it does not exist
# This is a simple PIL image creation for testing try:
from PIL import Image as PILImage, ImageDraw
if not os.path.exists(my_image_path):
img_pil = PILImage.new('RGB', (200, 100), color = 'red')
d = ImageDraw.Draw(img_pil)
d.text((10,10), "Test Image", fill=(255,255,0))
img_pil.save(my_image_path)
print(f"Sample image created: {my_image_path}")
except ImportError:
print("The PIL (Pillow) library is not installed and cannot create the example image. Please make sure you have the 'example_image.jpg' file.")
print("You can use 'pip install Pillow' to install the Pillow library.")
# Call the function to insert the image into the 'B2' cell insert_image_into_excel_cell(my_image_path, 'B2', "report_with_logo.xlsx")
Things to note and best practices
- Pictures are not really "embedded" : Please note that even with the above adjustments, pictures inserted by openpyxl are still technically floating objects, but their position and size are precisely controlled to make them appear "embedded" in the cell. This means that if you drag or resize a cell, the picture may not automatically move or scale with it.
- Path issues : Make sure the image_path is correct and that the Python script has permission to access the path. It is recommended to use an absolute path or ensure that the image file and script are in the same directory.
- Scaling factors : width / 6 and height / 18 are empirical values. Different image resolutions, Excel versions or display settings may result in a slightly imperfect fit. If you find that the image doesn't completely fill the cell or overflows, you may need to fine-tune these divisors.
- Performance considerations : Inserting large numbers of images may significantly increase Excel file size and processing time. If you need to process a large number of images, consider optimizing the image size or using a more advanced image processing strategy.
- Multiple images : If you need to insert multiple images in different cells, just repeat the img = Image(img_path) and ws.add_image(img, cell_reference) steps and adjust the size of its target cell for each image.
- Error handling : In actual applications, you should add error handling mechanisms such as file non-existence and image corruption to improve the robustness of the code.
Summarize
Through the openpyxl library, we can effectively insert pictures into specified cells of an Excel worksheet, and adjust the row height and column width of the cells to perfectly fit the pictures and cells. Although the picture is still technically a floating object, this method provides the powerful ability to visually "embed" the picture into the cell, greatly improving the flexibility and professionalism of using Python to generate Excel reports. Understanding and using the ws.add_image() method and cell resizing techniques will be an important tool in automating Excel tasks.
The above is the detailed content of Tutorial on inserting pictures into specific cells in Excel using openpyxl. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20522
7
13634
4
Solve the error of multidict build failure when installing Python package
Mar 08, 2026 am 02:51 AM
When installing libraries that depend on multidict in Python, such as aiohttp or discord.py, users may encounter the error "ERROR: Could not build wheels for multidict". This is usually due to the lack of the necessary C/C compiler or build tools, preventing pip from successfully compiling multidict's C extension from source. This article will provide a series of solutions, including installing system build tools, managing Python versions, and using virtual environments, to help developers effectively solve this problem.
How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction
Mar 13, 2026 am 11:54 AM
The essence of zip is zipper pairing, which packs multiple iterable objects into tuples by position and does not automatically unpack the dictionary. When passing in a dictionary, its keys are traversed by default. You need to explicitly use the keys()/values()/items() view to correctly participate in parallel traversal.
How to draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation
Mar 13, 2026 pm 12:18 PM
Multi-dimensional classification histograms need to manually calculate the x position and call plt.bar hierarchically; when stacking, bottom must be used to accumulate height, and xticks and ylim must be explicitly set (bottom=0); avoid mixing stacked=True and seaborn, and colors should be dynamically generated and strictly match the layer sequence.
How to find the sum of 5 numbers using Python's for loop
Mar 10, 2026 pm 12:48 PM
This article explains in detail how to use a for loop to read 5 integers from user input and add them up, provide a concise and readable standard writing method, and compare efficient alternatives to built-in functions.
How Python manages dependencies_Comparison between pip and poetry
Mar 12, 2026 pm 04:21 PM
pip is suitable for simple projects, which only install packages and do not isolate the environment; poetry is a modern tool that automatically manages dependencies, virtual environments and version locking. Use pip requirements.txt for small projects, and poetry is recommended for medium and large projects. The two cannot be mixed in the same project.
Python set intersection optimization_large data volume set operation skills
Mar 13, 2026 pm 12:36 PM
The key to optimizing Python set intersection performance is to use the minimum set as the left operand, avoid implicit conversion, block processing and cache incremental updates. Priority should be given to using min(...,key=len) to select the smallest set, disabling multi-parameter intersection(), using frozenset or bloom filters to reduce memory, and using lru_cache to cache results in high-frequency scenarios.
How to store sparse matrices in Python_Dictionary coordinate storage and use of scipy.sparse
Mar 12, 2026 pm 05:48 PM
Use scipy.sparse.coo_matrix instead of a dictionary because the bottom layer uses row/col/data three-array to efficiently support operations; the structure needs to be deduplicated, converted to csr/csc and then calculated; save_npz is preferred for saving; operations such as slicing must use csr/csc format.
How to run a Python script_Detailed explanation of various ways to run a Python script and command line operations
Apr 03, 2026 pm 01:51 PM
To run a Python script, make sure that Python is installed, the PATH configuration is correct, and the script has no syntax errors; confirm the interpreter path and version through which/where and --version; shebang only takes effect on Linux/macOS and requires chmod x; when reporting module errors, you need to check the working directory, sys.path, piplist, and running mode.





