How to convert JSON to XLS in Python

前端 未结 4 1199
梦毁少年i
梦毁少年i 2020-12-29 08:03

Does anyone know how can I convert JSON to XLS in Python?

I know that it is possible to create xls files using the package xlwt

4条回答
  •  Happy的楠姐
    2020-12-29 08:28

    In case someone wants to do output to Excel as a stream using Flask-REST

    Pandas versions:

    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
    

    and OpenPyXL version:

    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
    

提交回复
热议问题