[英]How to convert JSON to XLS in Python
有誰知道如何在 Python 中將 JSON 轉換為 XLS?
我知道可以使用 Python 中的xlwt
包創建xls
文件。
如果我想將JSON
數據直接轉換為XLS
文件怎么辦?
有沒有辦法存檔這個?
使用 pandas (0.15.1) 和 openpyxl (1.8.6):
import pandas
pandas.read_json("input.json").to_excel("output.xlsx")
我通常將 tablib 用於此用途。 使用起來非常簡單: https ://pypi.python.org/pypi/tablib/0.9.3
如果您的 json 文件存儲在某個目錄中,那么,
import pandas as pd
pd.read_json("/path/to/json/file").to_excel("output.xlsx")
如果您在代碼中有您的 json,那么您可以簡單地使用 DataFrame
json_file = {'name':["aparna", "pankaj", "sudhir", "Geeku"],'degree': ["MBA", "BCA", "M.Tech", "MBA"],'score':[90, 40, 80, 98]}
df = pd.DataFrame(json_file).to_excel("excel.xlsx")
如果有人想使用 Flask-REST 以流的形式輸出到 Excel
熊貓版本:
json_payload = request.get_json()
with NamedTemporaryFile(suffix='.xlsx') as tmp:
pandas.DataFrame(json_payload).to_excel(tmp.name)
buf = BytesIO(tmp.read())
response = app.make_response(buf.getvalue())
response.headers['content-type'] = 'application/octet-stream'
return response
和 OpenPyXL 版本:
keys = []
wb = Workbook()
ws = wb.active
json_data = request.get_json()
with NamedTemporaryFile() as tmp:
for i in range(len(json_data)):
sub_obj = json_data[i]
if i == 0:
keys = list(sub_obj.keys())
for k in range(len(keys)):
ws.cell(row=(i + 1), column=(k + 1), value=keys[k]);
for j in range(len(keys)):
ws.cell(row=(i + 2), column=(j + 1), value=sub_obj[keys[j]]);
wb.save(tmp.name)
buf = BytesIO(tmp.read())
response = app.make_response(buf.getvalue())
response.headers['content-type'] = 'application/octet-stream'
return response
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.