上传&编码.xls文件Python Web.py [英] Uploading & Encoding .xls File Python Web.py

查看:164
本文介绍了上传&编码.xls文件Python Web.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a web application that lets users upload an .xls file that I then take and feed that uploaded.xls file into my program which reads and parses it. I am currently using Python 2.7 on the Web.py framework.

但是,我对Excel文件的utf-8编码有问题。这种方法似乎只适用于.txt& .csv文件,但是当我尝试图像或.pdf它们不工作,所以我不知道如果web.py内置的库只是不支持Excel文件。当我上传Excel文件时,它只会吐出不可读的内容,如下所示:

However, I am having issues with the utf-8 encoding for the Excel files. This method seems to be only working for .txt & .csv files, but when I try images or .pdf they don't work, so I'm not sure if the web.py built in library just doesn't support Excel files. When I upload an Excel file, it just spits out unreadable content like the following:

■♠☺☺☺☻╒☻╒╒╒╒╒∙∙∙∙∙ 0░☺H↨P♂X
♀ï☻☻♥♥♫♂♂♂♂▲►☺Sheet1
▲♂工作表♥☺

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

这是我的代码:

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

我收到以下错误:


在/'ascii'编解码器无法解码
字节0xd0在位置0:o rdinal不在范围内(128)

at / 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

奇怪的是,我知道编码utf-8在我的应用程序上工作, t网页或使用web.py文件上传方法。所以我似乎看不到这里有什么问题。

The weird thing is that I know encoding it to utf-8 works on my application that isn't web based or using the web.py file upload method. So I can't seem to see what the problem is here.

例如:

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

使用xlrd工作得很好和xlwt python-excel方法。

that works perfectly fine using the xlrd and xlwt python-excel methods.

任何建议?

非常感谢!

推荐答案

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

这篇关于上传&编码.xls文件Python Web.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆