Python XlsxWriter - Insert Image



It is possible to insert an image object at a certain cell location of the worksheet, with the help of insert_image() method. Basically, you have to specify the location of cell using any type of notation and the image to be inserted.

worksheet.insert_image('C5', 'logo.png')

The insert_image() method takes following optional parameters in a dictionary.

Parameter Default
'x_offset' 0,
'y_offset' 0,
'x_scale' 1,
'y_scale' 1,
'object_position' 2,
'image_data' None
'url' None
'description' None
'decorative' False

The 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 add an in-memory byte stream in io.BytesIO format.

Example

The following program extracts the image data from a file in the current folder and uses is as value for 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

Here is the view of the resultant worksheet −

Insert Image
Advertisements