From the docs, the insert_image
function takes the following options:
{
'x_offset': 0,
'y_offset': 0,
'x_scale': 1,
'y_scale': 1,
'url': None,
'tip': None,
'image_data': None,
'positioning': None,
}
The problem is that the size of input images I need to insert can vary, but the cell where they need to be is of a fixed size. Is it possible to somehow provide a width and a height and let Excel resize the image into the provided dimensions?
You can scale the image externally or within Excel using XlsxWriter and the x_scale
and y_scale
based on the the heights and widths of the cell(s) and the image.
For example:
import xlsxwriter
workbook = xlsxwriter.Workbook('image_scaled.xlsx')
worksheet = workbook.add_worksheet()
image_width = 140.0
image_height = 182.0
cell_width = 64.0
cell_height = 20.0
x_scale = cell_width/image_width
y_scale = cell_height/image_height
worksheet.insert_image('B2', 'python.png',
{'x_scale': x_scale, 'y_scale': y_scale})
workbook.close()
The advantage of scaling it like this is that the user can get back the original image by setting the scaling back to 100% in Excel.