简体   繁体   English

读取requests.POST(Python)得到的excel文件

[英]Read an excel file obtained by requests.POST( Python )

I use the POST method via the requests library to download an EXCEL file.我通过请求库使用 POST 方法下载 EXCEL 文件。

payload = json.dumps({
  "data_ids": [
    "124902201",
    "124835548"
  ]
})

headers = {
  'Accept': 'application/vnd.ms-excel', 
  'Content-Type': 'application/json',
  }


response=requests.post(url, headers=headers, data=payload)

file_excel=pandas.read_excel(response.content)

When I tried the query on Postman, it returns me a response in Bytes form.当我在 Postman 上尝试查询时,它以字节形式返回给我一个响应。 So the idea I had was to read this file and convert it to Excel format and then load it into a dataframe.所以我的想法是读取这个文件并将其转换为 Excel 格式,然后将其加载到 dataframe 中。 Is it possible.可能吗。

Install openpyxl安装openpyxl

pip install openpyxl

Pandas can read the response.content directly Pandas 可以直接读取response.content

import pandas as pd
import io

file_extension = "xlsx"

(...)

if file_extension == 'xlsx':
    excel_data = pd.read_excel(resp.content, engine='openpyxl')
elif file_extension == 'xls':
    excel_data = pd.read_excel(resp.content)

EDIT: Ok, now I've tested that this does the trick.编辑:好的,现在我已经测试过这可以解决问题。

Thanks, Geoffrey Garrett your suggestion worked for reading both versions of excel files from disk.谢谢,Geoffrey Garrett 您的建议适用于从磁盘读取两个版本的 excel 文件。 But I had to modify read_excel() for 'xls', by adding engine='xlrd' and I had to install current version of xlrd.但是我必须通过添加engine ='xlrd'来修改'xls'的read_excel(),并且我必须安装当前版本的xlrd。 Using current version of Pandas also.也使用当前版本的 Pandas。 Hope this helps others.希望这对其他人有帮助。

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

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