将文件格式化为Excel工作表

时间:2017-10-10 11:55:47

标签: python json excel pandas csv

我是python的新程序员,我需要你的帮助。如果我在Chrome https://api.mysportsfeeds.com/v1.1/pull/nhl/2016-2017-regular/cumulative_player_stats。{format}中加载以下网址,其中{format}可能是csvjson格式,那么下载并打开后,该文件已经很好了格式化。如何使用pandasopenpyxl将其转换为Excel工作表?

更新

import base64
import requests
import json

USERNAME, PASSWORD = 'notworking', 'notworking'

def send_request():
    # Request

    try:
        response = requests.get(
            url="https://api.mysportsfeeds.com/v1.1/pull/nhl/2017-2018-regular/cumulative_player_stats.csv", 
            params={
                "fordate": "20171009"
            },
            headers={
                "Authorization": "Basic " +
                     base64.b64encode('{}:{}'.format(USERNAME,PASSWORD)\
                                      .encode('utf-8')).decode('ascii')
            }
        )
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Response HTTP Response Body: {content}'.format(
            content=response.content))
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

    return response


import pandas as pd
import io

test = send_request().content
df = pd.read_csv(io.StringIO(test.decode('utf-8')))
writer = pd.ExcelWriter('/home/jeremie/Projects/Work_Projects/NHL_project/output.xls')
df.to_excel(writer, 'Sheet1')

我正在努力解决我的代码似乎正常工作但没有创建文件的事实。

1 个答案:

答案 0 :(得分:0)

您需要添加最终.save()以关闭Pandas Excel编写器,然后输出Excel文件,例如

import pandas as pd
import io
import os

# Set the working folder to the same folder as the script
os.chdir(os.path.dirname(os.path.abspath(__file__)))

test = send_request().content
df = pd.read_csv(io.StringIO(test.decode('utf-8')))
writer = pd.ExcelWriter('output.xls')
df.to_excel(writer, 'Sheet1')
writer.save()

通过这种方式设置工作文件夹,它在Windows PC上同样可以正常工作。