Insert bitmap image in Excel file(xlwt) in

2020-07-27 11:51发布

I need to insert an Bitmap image in Excel file(creating using xlwt). i tried to insert using insert_bimap() method but it return IO Error.

Error:

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'

Code:

  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)

Please let me know if Any Workaround for this ?

Cheers! ,
NN

2条回答
爷的心禁止访问
2楼-- · 2020-07-27 12:13

I'm sure this project is long since done, but check out xlsxwriter

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

It's a lot better at inserting images than xlwt, supports jpegs and png files, not just bmp

if you need to offset -and- scale an image in one insert:

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})

offsets are in pixels

Don't have xlsxwriter

  • pip install xlsxwriter

don't have pip? it's like easy_install

  • centos/redhat

    yum install python-pip or yum install pip

  • debian

    apt-get install pip

查看更多
Lonely孤独者°
3楼-- · 2020-07-27 12:31

It seems that insert_bitmap() works only with bmp format. Open your gif file, save a copy under bmp format and call it with insert_bitmap('images/logo.bmp',2,2), it will work.

查看更多
登录 后发表回答