在unix中如何将jpeg图像插入excel工作表

2024-10-16 20:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用python中的xlwt模块的insert_bitmap命令插入bmp图像,使用以下代码:

import xlwt    
from PIL import Image   
book = xlwt.Workbook()
sheet3 = book.add_sheet('diagrams') 
Image.open('violations.png').convert("RGB").save('violations.bmp')    
sheet3.insert_bitmap('violations.bmp',5,13)
book.save('simple.xls')

这是正确地将bmp图像插入到工作表中,但我担心bmp图像大约是3MB,如果没有明显的质量损失,我无法压缩它。

在unix中有没有办法将jpeg图像插入到工作表中?


Tags: 模块代码from图像imageimport命令save
2条回答

从代码来看,xlwt似乎只支持24位位图图像。

Python模块可以插入PNG图像(或JPEG或位图)。下面是一个例子:

from xlsxwriter.workbook import Workbook


# Create an new Excel file and add a worksheet.
workbook = Workbook('images.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 30)

# Insert an image.
worksheet.write('A2', 'Insert an image in a cell:')
worksheet.insert_image('B2', 'python.png')

workbook.close()

输出:

XlsxWriter Image example

有关详细信息,请参见relevant section of the docs

http://xlsxwriter.readthedocs.org/en/latest/example_images.html

如果需要在一次插入中偏移和缩放图像:

worksheet.insert_image('B5', 'python.png', {'x_offset': 2, 'y_offset': 2, 'x_scale': 0.5, 'y_scale': 0.5})

我花了一秒钟才弄明白,以为这样可以节省别人的时间

相关问题 更多 >