Python- excel添加自定义列标题

发布于 2025-01-22 12:35:06 字数 1423 浏览 2 评论 0原文

我正在使用CoinMarketCap REST API用于最新的加密货币类别。
代码将JSON响应打印到用于传输到Excel的数据框中(DF.TO_EXCEL)。我使用“ DF中的“ for column in in for column in in excel”中的宽度更大。
现在,我想知道如何在Excel表中添加服装列标题。

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

I am using the Coinmarketcap REST Api for having the latest cryptocurrency categories.
The code prints the JSON response into a DataFrame which is used for the transfer to excel (df.to_excel). Im using the "for column in df" for a bigger width in excel.
Now I would like to know how I can add costum column headings into the 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

≈。彩虹 2025-01-29 12:35:06

您可以设置这样的自定义标题:

# 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)

另请参见 dataFrame标头格式

You can set a custom header like this:

# 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)

See also this section of the XlsxWriter docs on Formatting of the Dataframe headers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文