Python XlsxWriter – Inserting Images
Python XlsxWriter – Inserting Images
With the help of the insert_image() method, you can insert an image object into a cell in a worksheet. Basically, you must specify the cell location and the image to be inserted using any type of notation.
worksheet.insert_image('C5', 'logo.png')
insert_image() method accepts the following optional parameters in a dictionary.
Parameters | Default value |
---|---|
‘x_offset | 0, |
‘y_offset | 0, |
‘x_scale’ | 1, |
‘y_scale’ | 1, |
‘o ‘object_position’ | 2, |
‘image_data’ | None |
‘url’ | None |
‘description’ | None |
‘decorative’ | False |
Offset values are in pixels. The x_scale and y_scale parameters are used to scale the image horizontally and vertically.
The image_data parameter is used to append a byte stream in the io.BytesIO format to memory.
Example
The following program extracts image data from a file in the current folder and uses it as the value of the image_data parameter.
from io import BytesIO
import xlsxwriter
workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
filename = 'logo.png'
file = open(filename, 'rb')
data = BytesIO(file.read())
file.close()
worksheet.insert_image('C5', filename, {'image_data': data})
workbook.close()
Output
Below is a view of the resulting worksheet —