File: images_bytesio.py

package info (click to toggle)
xlsxwriter 3.1.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 56,308 kB
  • sloc: python: 51,511; javascript: 7,768; sh: 284; makefile: 195; perl: 75
file content (47 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
##############################################################################
#
# An example of inserting images from a Python BytesIO byte stream into a
# worksheet using the XlsxWriter module.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2023, John McNamara, jmcnamara@cpan.org
#

from io import BytesIO
from urllib.request import urlopen


import xlsxwriter

# Create the workbook and add a worksheet.
workbook = xlsxwriter.Workbook("images_bytesio.xlsx")
worksheet = workbook.add_worksheet()


# Read an image from a remote url.
url = (
    "https://raw.githubusercontent.com/jmcnamara/XlsxWriter/"
    + "master/examples/logo.png"
)

image_data = BytesIO(urlopen(url).read())

# Write the byte stream image to a cell. Note, the filename must be
# specified. In this case it will be read from url string.
worksheet.insert_image("B2", url, {"image_data": image_data})


# Read a local image file into a a byte stream. Note, the insert_image()
# method can do this directly. This is for illustration purposes only.
filename = "python.png"

image_file = open(filename, "rb")
image_data = BytesIO(image_file.read())
image_file.close()


# Write the byte stream image to a cell. The filename must  be specified.
worksheet.insert_image("B8", filename, {"image_data": image_data})


workbook.close()