how to insert jpeg image into excel sheet in unix

Sidharth C. Nadhan picture Sidharth C. Nadhan · Apr 10, 2013 · Viewed 11.1k times · Source

I am able to insert bmp images using insert_bitmap command of the xlwt module in python using the following code:

import xlwt    
from PIL import Image   
book = xlwt.Workbook()
sheet3 = book.add_sheet('diagrams') 
Image.open('violations.png').convert("RGB").save('violations.bmp')    
sheet3.insert_bitmap('violations.bmp',5,13)
book.save('simple.xls')

This is correctly inserting the bmp image into the sheet but my concern is that the bmp image is around 3MB and I am unable to compress it without significant quality loss.

Is there some way to insert jpeg images into a worksheet in unix ?

Answer

jmcnamara picture jmcnamara · Apr 10, 2013

From looking at the code it looks like xlwt only supports 24bit bitmap images.

The XlsxWriter Python module can insert PNG images (or JPEG or Bitmap). Here is an example:

from xlsxwriter.workbook import Workbook


# Create an new Excel file and add a worksheet.
workbook = Workbook('images.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 30)

# Insert an image.
worksheet.write('A2', 'Insert an image in a cell:')
worksheet.insert_image('B2', 'python.png')

workbook.close()

Output:

XlsxWriter Image example

See the relevant section of the docs for further information.