【问题标题】:How do you read excel files with xlrd on Appengine如何在 Appengine 上使用 xlrd 读取 excel 文件
【发布时间】:2012-05-14 13:29:47
【问题描述】:

我在 appengine 中使用 xlrd。我用烧瓶

我无法读取输入文件,并且一直显示相同的错误消息

代码是

def read_rows(inputfile):
    rows = []
    wb = xlrd.open_workbook(inputfile)
    sh = wb.sheet_by_index(0)
    for rownum in range(sh.nrows):
        rows.append(sh.row_values(rownum))
    return rows

@app.route('/process_input/',methods=['POST','GET'])
def process_input():
  inputfile = request.files['file']
  rows=read_rows(request.files['file'])
  payload = json.dumps(dict(rows=rows))
  return payload

我意识到这可能是由于未上传并将其保存为文件造成的。有什么解决方法吗?这也将帮助许多其他人。任何帮助表示赞赏,thx

更新:找到了我在下面发布的解决方案。对于那些对使用 xlrd 感到困惑的人,可以参考我发布的开源项目 repo。关键是传递文件的内容而不是文件名

【问题讨论】:

    标签: python google-app-engine flask xlrd


    【解决方案1】:

    终于找到解决办法

    这就是我的做法。我没有保存文件,而是读取文件的内容并让 xlrd 读取它

    def read_rows(inputfile):
      rows = []
      wb = xlrd.open_workbook(file_contents=inputfile.read())
      sh = wb.sheet_by_index(0)
      for rownum in range(sh.nrows):
        rows.append(sh.row_values(rownum))
      return rows
    

    运行良好,并将 excel 文件转换为 JSON 格式。如果要输出 json,只需使用 json.dumps()。

    完整的代码示例可以在 https://github.com/cjhendrix/HXLator/blob/master/gae/main.py 找到,它具有 xlrd 的完整实现以及如何处理数据。

    感谢指点

    【讨论】:

      【解决方案2】:

      用途:

      wb = xlrd.open_workbook(file_contents=inputfile)
      

      您调用 open_workbook 的方式期望您传入的是文件名,而不是包装实际文件的 Flask FileStorage 对象。

      【讨论】:

      • 这对我很有帮助。我需要获取内容而不是文件名。因此出现了 inputfile.read()。非常感谢
      【解决方案3】:

      从您的回溯中判断。

      File "/Users/fauzanerichemmerling/Desktop/GAEHxl/gae/lib/xlrd/init.py", line 941, in biff2_8_load
          f = open(filename, open_mode)
      

      您可以尝试将此行更改为:

      f = filename
      

      【讨论】:

      • 该代码位于第三方库中,只是随意更改它以接受文件而不是文件名似乎很可能会破坏事情。
      猜你喜欢
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2020-09-15
      相关资源
      最近更新 更多