简体   繁体   English

使用 web.py 上传 Excel

[英]Upload Excel using web.py

I have tried the following code by slightly modifying the example in documentation我通过稍微修改文档中的示例尝试了以下代码

class Upload():
  def POST(self):
    web.header('enctype','multipart/form-data')
    print strftime("%Y-%m-%d %H:%M:%S", gmtime())
    x = web.input(file={})
    filedir = '/DiginUploads' # change this to the directory you want to store the file in.
    if 'file' in x: # to check if the file-object is created
        filepath=x.file.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
        filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
        fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
        fout.write(x.file.file.read()) # writes the uploaded file to the newly created file.
        fout.close() # closes the file, upload complete.

But this works only for csv and txt documents.但这仅适用于 csv 和 txt 文档。 For Excel/pdf etc file gets created but it can't be opened (corrupted).对于 Excel/pdf 等文件已创建,但无法打开(已损坏)。 What should I do to handle this scenario?我应该怎么做来处理这种情况?

I saw this but it is about printing the content which does not address my matter.我看到了这个,但它是关于打印没有解决我的问题的内容。

打开文件时需要使用wb (二进制)模式:

fout = open(filedir +'/'+ filename, 'wb')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM