答案 0 :(得分:5)
这是使用XlsxWriter的一种方法:
import pandas as pd
# Create a Pandas dataframe from some data.
data = [10, 20, 30, 40, 50, 60, 70, 80]
df = pd.DataFrame({'Rank': data,
'Country': data,
'Population': data,
'Data1': data,
'Data2': data})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_table.xlsx", engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object. Turn off the default
# header and index and skip one row to allow us to insert a user defined
# header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape
# Create a list of column headers, to use in add_table().
column_settings = []
for header in df.columns:
column_settings.append({'header': header})
# Add the table.
worksheet.add_table(0, 0, max_row, max_col - 1, {'columns': column_settings})
# Make the columns wider for clarity.
worksheet.set_column(0, max_col - 1, 12)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
更新:我向XlsxWriter文档添加了一个类似的示例:Example: Pandas Excel output with a worksheet table
答案 1 :(得分:3)
如果您不想保存,重新打开和重新保存,另一种解决方法是使用xlsxwriter。它可以直接写入ListObject表,但不能直接从数据框中写入,因此您需要对这些部分进行分解:
import pandas as pd
import xlsxwriter as xl
df = pd.DataFrame({'Col1': [1,2,3], 'Col2': list('abc')})
filename = 'output.xlsx'
sheetname = 'Table'
tablename = 'TEST'
(rows, cols) = df.shape
data = df.to_dict('split')['data']
headers = []
for col in df.columns:
headers.append({'header':col})
wb = xl.Workbook(filename)
ws = wb.add_worksheet()
ws.add_table(0, 0, rows, cols-1,
{'name': tablename
,'data': data
,'columns': headers})
wb.close()
add_table()
函数期望'data'
作为列表列表,其中每个子列表代表数据帧的一行,而'columns'
作为表头的字典列表,其中每一列是由{'header': 'ColumnName'}
形式的字典指定。
答案 2 :(得分:1)
您无法使用to_excel
来做到这一点。一种解决方法是打开生成的xlsx文件,并使用openpyxl在其中添加表:
import pandas as pd
df = pd.DataFrame({'Col1': [1,2,3], 'Col2': list('abc')})
filename = 'so58326392.xlsx'
sheetname = 'mySheet'
with pd.ExcelWriter(filename) as writer:
if not df.index.name:
df.index.name = 'Index'
df.to_excel(writer, sheet_name=sheetname)
import openpyxl
wb = openpyxl.load_workbook(filename = filename)
tab = openpyxl.worksheet.table.Table(displayName="df", ref=f'A1:{chr(len(df.columns)+64)}{len(df)+1}')
wb[sheetname].add_table(tab)
wb.save(filename)
请注意所有表头必须是字符串。如果您有未命名的索引(这是规则),则第一个单元格(A1)将为空,这会导致文件损坏。为避免这种情况,请为您的索引命名(如上所示),或使用以下命令导出不带索引的数据框:
df.to_excel(writer, sheet_name=sheetname, index=False)