-1

假设我有以下内容dataframe

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

我想给它一个用户提供的标题,例如: title = 'The sales'

如何添加titledf发送到Excel sheetpdf显示为:`

{title} in this case *The sales*
 A  B  C  D  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

搜索可能的解决方案会导致添加column title,而我想要的是添加dataframe标题。

4

2 回答 2

0

这是使用 xlsxwriter 作为 Pandas Excel 引擎的一种方法。使用 openpyxl 也可以进行类似的操作:

import pandas as pd

df = pd.DataFrame({'A': list('abcdef'),
                   'B': [4, 5, 4, 5, 5, 4],
                   'C': [7, 8, 9, 4, 2, 3],
                   'D': [1, 3, 5, 7, 1, 0],
                   'E': [5, 3, 6, 9, 2, 4],
                   'F': list('aaabbb')})

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

# Shift the dataframe down one row in the Excel file.
df.to_excel(writer, sheet_name='Sheet1', startrow=1)

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

# Write the title to the worksheet.
title = 'The sales'
worksheet.write(0, 0, title)

writer.save()

输出:

在此处输入图像描述

于 2021-09-25T12:46:26.767 回答
0

您可以使用 xlwings,它是使用 python 将数据转换为 excel 的最佳库之一

import pandas as pd
import xlwings as xw

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})


title = 'The sales'

wb = xw.Book("sales.xlsx")

sheet = wb.sheets['Sheet1']

sheet.range('A1').value = title

sheet.range('A2').options(pd.DataFrame, index=False).value = df

wb.save('sales.xlsx')
wb.close()

#如果你不需要索引保持在上面#如果你需要索引放索引=真

于 2021-09-25T09:50:52.057 回答