如何使用Excel()创建Excel**表格**pandas.to?

lmvvr0a8  于 2022-11-27  发布在  其他
关注(0)|答案(5)|浏览(271)

需要从 Dataframe 以编程方式实现此目的:

https://learn.microsoft.com/en-us/power-bi/service-admin-troubleshoot-excel-workbook-data

cwtwac6a

cwtwac6a1#

下面是使用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

vkc1a9a2

vkc1a9a22#

您不能使用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:{openpyxl.utils.get_column_letter(df.shape[1])}{len(df)+1}')
wb[sheetname].add_table(tab)
wb.save(filename)

请注意,所有表格标题必须是字符串。如果您有未命名的索引(这是规则),第一个单元格(A1)将为空,这将导致文件损坏。为避免这种情况给予请为您的索引命名(如上所示)或使用以下命令导出不带索引的 Dataframe :

df.to_excel(writer, sheet_name=sheetname, index=False)
ifmq2ha2

ifmq2ha23#

如果你不想保存、重新打开和重新保存,另一个解决方法是使用xlsxwriter。它可以直接写ListObject表,但不能直接从 Dataframe 中写,所以你需要分解这些部分:

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'作为列表的列表,其中每个子列表表示 Dataframe 的一行,'columns'作为标题的字典的列表,其中每个列由{'header': 'ColumnName'}形式的字典指定。

gstyhher

gstyhher4#

我创建了一个软件包来编写Pandas的格式正确的Excel表格:pandas-xlsx-tables

from pandas_xlsx_tables import df_to_xlsx_table
import pandas as pd

data = [10, 20, 30, 40, 50, 60, 70, 80]
df = pd.DataFrame({'Rank': data,
                'Country': data,
                'Population': data,
                'Strings': [f"n{n}" for n in data],
                'Datetimes': [pd.Timestamp.now() for _ in range(len(data))]})

df_to_xlsx_table(df, "my_table", index=False, header_orientation="diagonal")

也可以使用xlsx_table_to_df执行相反的操作

zwghvu4y

zwghvu4y5#

基于@jmcnamara的回答,而是作为一个方便的函数而使用“with”语句:

import pandas as pd

def to_excel(df:pd.DataFrame, excel_name: str, sheet_name: str, startrow=1, startcol=0):
    """ Exports pandas dataframe as a formated excel table """
    with pd.ExcelWriter(excel_name, engine='xlsxwriter') as writer:
        df.to_excel(writer, sheet_name=sheet_name, startrow=startrow, startcol=startcol, header=True, index=False)
        workbook = writer.book
        worksheet = writer.sheets[sheet_name]
        max_row, max_col = df.shape

        olumn_settings = [{'header': header} for header in df.columns]
        worksheet.add_table(startrow, startcol, max_row+startrow, max_col+startcol-1, {'columns': column_settings})
        # style columns
        worksheet.set_column(startcol, max_col + startcol, 21)

相关问题