Django、xlsxwriter 和图像

Django, xlsxwriter and images

我有一个 Django 网站,我正在尝试创建一个 excel 文件,里面有一张图片。

图像在 AWS 上:https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/10e8f47bb84901d20ff435071577c58b_TFxmjcV.jpg

我正在使用:xlsxwriter==1.4.5 并尝试写成:

worksheet_s.insert_image(5, thisColumn, str('https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/'+image))

我的模型是这样的:

class Room(models.Model):

    # Relationships
    location = models.ForeignKey("asset_app.Locations",  on_delete=models.SET_NULL, blank=True, null=True)
    room_type = models.ForeignKey("asset_app.Room_type", on_delete=models.SET_NULL, blank=True, null=True)

    # Fields

    name = models.CharField(max_length=30)
    image = models.ImageField(storage=PublicMediaStorage(), null=True, blank=True

)

我收到的错误是:

worksheet_s.insert_image(5, thisColumn, str('https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/'+image))
TypeError: can only concatenate str (not "ImageFieldFile") to str

XlsxWriter 不会像那样直接从 url 插入图像。您需要先阅读数据。像这样:

from io import BytesIO
from urllib.request import urlopen
import xlsxwriter

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

# Read an image from a remote url.
url = 'https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/10e8f47bb84901d20ff435071577c58b_TFxmjcV.jpg'

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

# Write the byte stream image to a cell. Note, a dummy filename
# or description must be specified, or use a blank string.
worksheet.insert_image('B2', 'image name', {'image_data': image_data})


workbook.close()

输出: