有谁知道如何在Python中将JSON转换为XLS?
我知道可以使用Python中的包xls
创建xlwt
个文件。
如果我想直接将JSON
数据转换为XLS
文件,该怎么办?
有没有办法存档?
答案 0 :(得分:14)
我通常使用tablib来实现此用途。它非常简单易用: https://pypi.python.org/pypi/tablib/0.9.3
答案 1 :(得分:8)
使用pandas(0.15.1)和openpyxl(1.8.6):
import pandas
pandas.read_json("input.json").to_excel("output.xlsx")
答案 2 :(得分:1)
如果您的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")
答案 3 :(得分:0)
如果有人想使用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