python - 具有已定义名称范围的 Pandas 数据框到 Excel

标签 python excel pandas

我想在我的代码运行时将多个不同大小的 df 写入 Excel。

一些表将包含源数据,而其他表将包含对该源数据进行操作的 Excel 公式。

我希望公式 df 包含对源数据 df 的 Excel 引用,而不是跟踪我将源数据写入的单元格范围。

这可以通过 Excel 的名称或 Excel 的表格功能来完成。

例如,在我的公式 df 中,我可以有 =INDEX(my_Defined_Name_source_data, 4,3) * 2 并且 Excel 名称 my_Defined_Name_source_data 是我索引源数据所需的全部内容。

Openpyxl 在这里详细写表 https://openpyxl.readthedocs.io/en/stable/worksheet_tables.html?highlight=tables

表格不支持多索引 df.to_excel 将创建的合并单元格。

所以我正在寻找定义的名称。几乎没有使用 openpyxl 编写定义名称的文档
wb.defined_names.append()
这是我发现的 https://openpyxl.readthedocs.io/en/stable/api/openpyxl.workbook.defined_name.html?highlight=definednames

我正在寻求帮助:如何将 DataFrame 写入 Excel 并为其提供 Excel 定义的名称。文档和在线示例几乎不存在。

也很感激地接受有关替代想法的建议,因为我似乎正在访问几乎没有其他人使用的东西。

最佳答案

“xlsxwriter”库允许您创建 Excel 数据表,因此我编写了以下函数来获取 DataFrame,将其写入 Excel,然后将数据转换为数据表。

def dataframe_to_excel_table(df, xl_file, xl_tablename, xl_sheet='Sheet1'):
    """
    Pass a dataframe, filename, name of table and Excel sheet name.
    Save an excel file of the df, formatted as a named Excel 'Data table'
    * Requires "xlsxwriter" library ($ pip install XlsxWriter)

    :param df: a Pandas dataframe object
    :param xl_file: File name of Excel file to create
    :param xl_sheet: String containing sheet/tab name
    :param xl_tablename: Data table name in the excel file
    :return: Nothing / New Excel file
    """

    # Excel doesn't like multi-indexed df's. Convert to 1 value per column/row
    #   See https://stackoverflow.com/questions/14507794
    df.reset_index(inplace=True)  # Expand multiindex

    # Write dataframe to Excel
    writer = pd.ExcelWriter(path=xl_file,
                            engine='xlsxwriter',
                            datetime_format='yyyy mm dd hh:mm:ss')
    df.to_excel(writer, index=False, sheet_name=xl_sheet)

    # Get dimensions of data to size table
    num_rows, num_cols = df.shape

    # make list of dictionaries of form [{'header' : col_name},...]
    # to pass so table doesn't overwrite column header names
    # https://xlsxwriter.readthedocs.io/example_tables.html#ex-tables
    dataframes_cols = df.columns.tolist()
    col_list = [{'header': col} for col in dataframes_cols]

    # Convert data in Excel file to an Excel data table
    worksheet = writer.sheets[xl_sheet]
    worksheet.add_table(0,0,    # begin in Cell 'A1'
                        num_rows, num_cols-1,
                        {'name': xl_tablename,
                         'columns': col_list})
    writer.save()

关于python - 具有已定义名称范围的 Pandas 数据框到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51531715/

相关文章:

java - JExcel - 在关闭 WritableWorkbook 之前修改多个单元格

python - 线条颜色作为 pandas 数据框中列值的函数

python - 使用 Python statsmodel 进行多元线性回归

python - 如何使用 tqdm 实现 JSON 文件加载进度条?

python - 使用 np.random.uniform 最接近 (1,0) 的端点

python - python BaseHttpServer 支持 Html5 吗?

python - 使用 mongoengine 将多文档插入到 mongodb

excel - 使用高级过滤器加速从 VBA 中的另一个工作表复制

vba - Excel 宏将数据插入下一行

python - 计算仅在 B 列和/或 C 列中观察到的单个不同值的 A 列值