Last active
February 24, 2023 14:27
-
-
Save heldonjose/da01455ab4df74954bbe339adec347e0 to your computer and use it in GitHub Desktop.
Ler imagens no excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from openpyxl import load_workbook | |
import io | |
import string | |
from PIL import Image | |
class SheetImageLoader: | |
"""Loads all images in a sheet""" | |
_images = {} | |
def __init__(self, sheet): | |
"""Loads all sheet images""" | |
sheet_images = sheet._images | |
for image in sheet_images: | |
row = image.anchor._from.row + 1 | |
col = string.ascii_uppercase[image.anchor._from.col] | |
cell_name = f'{col}{row}' | |
if cell_name in self._images: | |
cell = self._images.get(cell_name) | |
if type(cell) != list: | |
old_image = self._images.get(cell_name) | |
self._images[cell_name] = [] | |
self._images[cell_name].append(old_image) | |
self._images[cell_name].append(image._data) | |
else: | |
self._images[cell_name] = image._data | |
def image_in(self, cell): | |
"""Checks if there's an image in specified cell""" | |
return cell in self._images | |
def get(self, cell): | |
"""Retrieves image data from a cell""" | |
if cell not in self._images: | |
raise ValueError("Cell {} doesn't contain an image".format(cell)) | |
else: | |
if type(self._images[cell]) is list: | |
images = [Image.open(io.BytesIO(i())) for i in self._images[cell]] | |
return images, list | |
image = io.BytesIO(self._images[cell]()) | |
return Image.open(image), object | |
# Load your workbook and sheet as you want, for example | |
wb = load_workbook('temp.xlsx') | |
sheet = wb.worksheets[0] | |
# Put your sheet in the loader | |
image_loader = SheetImageLoader(sheet) | |
print(sheet["a1"].value) | |
image, type_item = image_loader.get('A1') | |
for i in image: | |
i.show() | |
image, type_item = image_loader.get('B1') | |
print('type_item', type_item) | |
image.show() | |
# Image now is a Pillow image, so you can do the following | |
# image.show() | |
# image.save('teste.png') | |
# Ask if there's an image in a cell |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment