【问题标题】:How to create Excel **Table** with pandas.to_excel()?如何使用 pandas.to_excel() 创建 Excel **Table**?
【发布时间】:2020-02-08 02:30:07
【问题描述】:

【问题讨论】:

    标签: excel pandas dataframe excel-tables


    【解决方案1】:

    这是使用 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

    【讨论】:

    • 我可能不得不借用一些你写的东西。我更喜欢你提出标题的方式,而不是我提出的丑陋方法。
    【解决方案2】:

    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)
    

    【讨论】:

    【解决方案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'}。

    【讨论】:

      【解决方案4】:

      我创建了一个包来从 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做相反的事情

      【讨论】:

        猜你喜欢
        • 2015-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-20
        • 2011-03-02
        • 2013-07-01
        相关资源
        最近更新 更多