我想在我的代码运行时将多个不同大小的 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/