Python Xlsxwriter 简明教程

Python XlsxWriter - Insert Image

可以借助 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')

insert_image() 方法在字典中采用以下可选参数。

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

偏移值以像素为单位。 x_scaley_scale 参数用于水平和垂直缩放图像。

The offset values are in pixels. The x_scale and y_scale parameters are used to scale the image horizontally and vertically.

image_data 参数用于在 io.BytesIO 格式中添加内存中字节流。

The image_data parameter is used to add an in-memory byte stream in io.BytesIO format.

Example

下列程序从当前文件夹中的文件中提取图像数据,并将其用作 image_data 参数的值。

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