Python - Excel 添加自定义列标题

Python - Excel adding custom column headings

我正在使用 Coinmarketcap REST Api 以获得最新的加密货币类别。
该代码将 JSON 响应打印到 DataFrame 中,该 DataFrame 用于传输到 excel (df.to_excel)。我在 excel.
中使用“for column in df”以获得更大的宽度 现在我想知道如何将服装列标题添加到 excel sheet.

def Cryptocurrencies():
    url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/categories'
    parameters = {

    }
    headers = {
        'Accept': 'application/json',
        'X-CMC_PRO_API_KEY': 'mypersonalapikey',
    }

    session = Session()
    session.headers.update(headers)
    data = session.get(url, params=parameters)

    response = session.get(url, params=parameters)
    f = (json.loads(response.text)['data'])
    df = pd.DataFrame(f)
    writer = pd.ExcelWriter("Workingpaper1D.xlsx",
                            engine='xlsxwriter',
                            datetime_format='mmm d yyyy hh:mm:ss',
                            date_format='mmmm dd yyyy')
    df.to_excel(writer, sheet_name='Sheet1',
                startrow=1, header=False, index=False, )
    (max_row, max_col) = df.shape
    worksheet = writer.sheets['Sheet1']
    worksheet.autofilter(0, 0, max_row, max_col - 1)
    for column in df:
        column_length = max(df[column].astype(str).map(len).max(), len(column))
        col_idx = df.columns.get_loc(column)
        writer.sheets['Sheet1'].set_column(col_idx, col_idx, column_length)
    writer.save()
    print(df)
    return

您可以像这样设置自定义 header:

# Convert the dataframe to an XlsxWriter Excel object. Note that we turn off
# the default header and skip one row to allow us to insert a user defined
# header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1})

# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)

另请参阅 Formatting of the Dataframe headers 上的 XlsxWriter 文档的这一部分。