【问题标题】:Insert bitmap image in Excel file(xlwt) in GAE在 GAE 中的 Excel 文件(xlwt)中插入位图图像
【发布时间】:2012-01-05 11:26:17
【问题描述】:

我需要在 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

【问题讨论】:

  • 您是否尝试过使用其他方法(例如直接打开)阅读“images/logo.gif”?权限被拒绝听起来不像 xlwt 问题,听起来您无权访问该文件。可能是insert_bitmap 试图打开文件进行写入,但这不是回溯rb 所说的。
  • 是的。我可以通过localhost:8081/images/logo.gif 访问它。
  • 我的意思不是通过网络浏览器,我的意思是您的 MainHandler 例程可以访问该文件吗?无需创建工作簿,只需打开 logo.gif 文件并读取第一个字节。

标签: python google-app-engine xlwt


【解决方案1】:

insert_bitmap() 似乎只适用于 bmp 格式。打开你的 gif 文件,以 bmp 格式保存一份副本并用insert_bitmap('images/logo.bmp',2,2) 调用它,它会工作的。

【讨论】:

    【解决方案2】:

    我确定这个项目早就完成了,但请查看 xlsxwriter

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

    插入图片比xlwt好很多,支持jpegs和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

    • 点安装 xlsxwriter

    没有点子?这就像easy_install

    • centos/redhat

      yum 安装 python-pip 或者 百胜安装点子

    • debian

      apt-get install pip

    【讨论】:

    • 关于这个答案的重要说明:xlsxwriter 无法读取 excel 工作表,只能生成新工作表。因此,如果您想将图像插入现有的 xlsxwriter 不是正确的工具。
    • 您可以使用 openpyxl 和 numpy 或其他 python-excel.org 读取 xlsx 数据,然后使用 xlsxwriter 创建一个新的 xlsx 文件,其中添加并合并新数据/图像。我经常发现制作新文件比修改文件效果更好,而 xlsxwriter 最适合图像。 stackoverflow.com/questions/4371163/…
    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2023-03-23
    • 1970-01-01
    • 2011-07-20
    相关资源
    最近更新 更多