0

So I have the following Code. It should export an excelfile but the naming does not work. Though the contents are alright. The file is named "Empty DataFrame Columns: [Column1, Column2] Index: [].xlsx"

It should be named testDF.xlsx. Is there an easy solution?

import pandas as pd

ExportExcelParam = 1;

testDF = pd.DataFrame(columns=['Column1','Column2'], dtype=object)


def ExcelExportDF(Dataframe, ExportExcelParam):
    if ExportExcelParam == 1: 
        Filename = str(Dataframe) + ".xlsx"
        Dataframe.to_excel(Filename)


ExcelExportDF(testDF, ExportExcelParam)
MarK
  • 51
  • 9

1 Answers1

1

That is because testDF is not a string, it is just a name of your variable. Now that variable contains a DataFrame, so when you use str(), it will try to provide a reasonable string that represents the DataFrame itself.

An easy solution is to pass the name as string in an additional parameter. Yes, it requires to type the name twice, but it is probable the safest and most straight-forward option, unless you can retrieve the name from somehwere else.

def ExcelExportDF(Dataframe, Filename, ExportExcelParam):
    if ExportExcelParam == 1: 
        Dataframe.to_excel(Filename + ".xlsx")


ExcelExportDF(testDF, 'testDF', ExportExcelParam)

Edit: Just saw the comments. If you know what you are doing, maybe this could work.

  • Thanks, this solves the problem. Pass the object _and_ the string. Otherwise iterating through globals should work! – MarK Jun 30 '21 at 14:32