在GAE中使用xlwt插入位图图像到Excel文件
我需要在Excel文件中插入一张位图图片(我是用xlwt创建的)。我尝试用insert_bimap()这个方法来插入,但它返回了一个IO错误。
错误信息:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 701, in __call__
handler.get(*groups)
File "C:\apps\test.py", line 44, in get
ws0.insert_bitmap('images/logo.gif', 2, 2)
File "C:\apps\xlwt\Worksheet.py", line 1034, in insert_bitmap
bmp = Bitmap.ImDataBmpRecord(filename)
File "C:\apps\xlwt\Bitmap.py", line 255, in __init__
self.width, self.height, self.size, data = _process_bitmap(filename)
File "C:\apps\xlwt\Bitmap.py", line 195, in _process_bitmap
fh = file(bitmap, "rb")
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 578, in __init__
raise IOError(errno.EACCES, 'file not accessible', filename)
IOError: [Errno 13] file not accessible: 'images/logo.gif'
代码:
class MainHandler(webapp.RequestHandler):
def get(self):
wb = Workbook()
ws0 = wb.add_sheet('Sheet 1')
ws0.write(0, 2, "chg wid: none")
ws0.insert_bitmap('images/logo.gif', 2, 2)
self.response.headers['Content-Type'] = 'application/ms-excel'
self.response.headers['Content-Transfer-Encoding'] = 'Binary'
self.response.headers['Content-disposition'] = 'attachment; filename="Sample.xls"'
wb.save(self.response.out)
请问有没有什么解决办法?
谢谢!
NN
2 个回答
3
我知道这个项目可能早就完成了,但你可以看看 xlsxwriter。
http://xlsxwriter.readthedocs.org/en/latest/example_images.html
这个工具在插入图片方面比 xlwt 好很多,支持 jpeg 和 png 格式的文件,不仅仅是 bmp。
如果你需要在一次插入中同时调整图片的位置和大小:
worksheet.insert_image('B5', '/python/reports/garmentspreadsheet/Images/Garments/6702RD-WH.jpg', {'x_offset': 2, 'y_offset': 2, 'x_scale': 0.5, 'y_scale': 0.5})
这里的偏移量是以像素为单位的。
如果你还没有安装 xlsxwriter:
- 可以用命令 pip install xlsxwriter 来安装。
如果你没有 pip?它就像是 easy_install。
在 centos/redhat 系统上:
可以用 yum install python-pip 或 yum install pip 来安装。
在 debian 系统上:
可以用 apt-get install pip 来安装。
3
看起来 insert_bitmap()
这个函数只支持 bmp 格式的图片。你可以打开你的 gif 文件,然后另存为 bmp 格式的副本,然后用 insert_bitmap('images/logo.bmp',2,2)
来调用它,这样就可以正常工作了。