【问题标题】:Uploading & Encoding .xls File Python Web.py上传和编码 .xls 文件 Python Web.py
【发布时间】:2014-02-28 23:54:08
【问题描述】:

我正在尝试创建一个 Web 应用程序,该应用程序允许用户上传一个 .xls 文件,然后我将该上传的.xls 文件输入到我的程序中,该程序读取并解析它。我目前在 Web.py 框架上使用 Python 2.7。

但是,我遇到了 Excel 文件的 utf-8 编码问题。这种方法似乎只适用于 .txt 和 .csv 文件,但是当我尝试图像或 .pdf 时它们不起作用,所以我不确定 web.py 内置库是否不支持 Excel 文件.当我上传 Excel 文件时,它只会吐出如下不可读的内容:

■ ♠☺☻ ☺ ☻╒═╒£.←►ô +,∙«0 ░ ☺ H ↨ P ♂ X ♀ ï ☻ Σ♦ ♥ ♫ ♂ ♂ ♂ ♂ ▲► ☺ Sheet1 ▲ ♂ 工作表♥ ☺

这是我的代码:

 class index:
    def POST(self):
        x = web.input(calendar_file={}, ref_id='')
        if x:
            ref_id = (x.ref_id if x.ref_id else "")
            filepath=x.calendar_file.filename # replaces the windows-style slashes with linux ones.
            fn=filepath.split('/')[-1] # splits the and chooses the last part (the filename
            filename = "%s/Users/jl98567/Documents/xMatters_calendar_app/test/" + fn
            fullpath = os.path.join('c:', filename % (ref_id))
            content = x["calendar_file"].file.read()
            with open(fullpath, 'w') as f_out:
                if not f_out:
                    raise Exception("Unable to open %s for writing. " % (fullpath))
                f_out.write(content)
        print x['calendar_file'].value
        raise web.seeother('/upload?ref_id=%s&filename=%s' % (ref_id, filename))

现在,当我尝试编码时:

print x['calendar_file'].value.encode('utf-8')

我收到以下错误:

at / 'ascii' 编解码器无法解码 位置 0 中的字节 0xd0:序数不在范围内(128)

奇怪的是,我知道将其编码为 utf-8 可以在我的应用程序上运行,该应用程序不是基于 Web 或使用 web.py 文件上传方法的。所以我似乎看不出这里有什么问题。

例如:

content = str(sheet.cell(row,0).value.encode('utf8'))

使用 xlrd 和 xlwt python-excel 方法可以很好地工作。

有什么建议吗?

非常感谢!

【问题讨论】:

  • 你想通过“编码”一个 .xls 文件来达到什么目的?这根本没有意义。
  • 我只是想解决我收到的上述错误。
  • 但是如果你试图做错事,你显然会得到一个错误。那么,您为什么要首先尝试“编码” .xls 文件呢?
  • 我一开始并没有尝试“编码” .xls 文件。我想要做的就是以可读形式获取上传的 Excel 文件的内容,但是当我上传文件而不对其进行编码时(通过 webpy 的文件上传库),我收到错误(“ at / 'utf8' codec can't decode byte 0xd0 in position 0: invalid continuation byte") 适用于 ALL 且仅适用于 .xls 文件。经过一番研究,我发现有些人建议使用 utf-8、cp866 等对文件进行编码。如果我接近这个错误,请分享我该如何解决这个问题。
  • 我已经从 webpy 切换到 web2py,因为 webpy 没有上传 excel 文档的功能,而 web2py 工作得非常好!我应该做更多的研究,并且知道 webpy 没有太多功能。

标签: python excel encoding utf-8 web.py


【解决方案1】:
    print unicode(x['calendar_file'].value, 'utf-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2014-06-29
    • 2015-05-10
    • 2017-12-21
    相关资源
    最近更新 更多