Wynter
Wynter

Reputation: 1

Can I save a Pandas DataFrame with a Tkinter File Dialog?

I am fairly new to programming, and even newer to Tkinter.

I am setting up a GUI that works with an SQL Server to allow front end users to retrieve, update, and delete certain information.

Currently I have everything communicating and working correctly, but I have a function that exports a list of the results into an excel file using Pandas. The export works fine, but it has the static name and directory I give it inside the Pandas to_excel method.

I want to use a Tkinter asksaveasfilename dialog to allow the user to name and choose the files export location, but I can't seem figure out how this works with this dialogue box (if it is even possible). Is there an option inside the dialog boxes code where I specify what information I want to save?

def exportFunc():
      pd.DataFrame(data).to_excel("TestList.xlsx", header=False, index = True)
      filedialog.asksaveasfilename(initialdir = "/", title = 'Save File', filetypes = ("Excel File", "*.xlsx"))
      pass

My code doesn't produce any errors, just simply saves nothing with the dialogue box with everything I try. Right now I have the file dialog commented out in my actual code, but if someone could direct me towards a possible solution, I would be grateful!

Upvotes: 0

Views: 3263

Answers (2)

ElLorans
ElLorans

Reputation: 134

Asksaveasafile returns a file object, so we can use that to save the df.

from tkinter import filedialog, Tk

import pandas as pd

df = pd.DataFrame(
{"Test": range(20)}
)

root = Tk()  # this is to close the dialogue box later
try:
    # with block automatically closes file
    with filedialog.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
        df.to_excel(file.name)
except AttributeError:
    # if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
    print("The user cancelled save")
    
root.destroy() # close the dialogue box

Upvotes: 3

Cole
Cole

Reputation: 71

10 months ago this was posted, but I hope this answer can help a fellow novice googling around for this answer as well.

How I solved this was noticing the asksaveasfile function outputs a value that contains the user specified file path and file name. For example:

< closed file u'E:Filepath/AnotherPath/work2.xlsx', mode 'w' at 2119x6710 >

I then used regex and the replace method to strip away all values surrounding the filepath, which once finished, the to_excel function would see as a hardcode.

Hope this helps someone out there!

out = tkFileDialog.asksaveasfile(mode='w', defaultextension=".xlsx")
out.close()


restr = str(out)

RegexPrep = restr.replace("'w'", '')

outRegex = re.findall(r"'(.*?)'", RegexPrep)
ToExcelRegex = str(outRegex)

MorePrep = ToExcelRegex.replace("[",'')
MorePrep = MorePrep.replace("]",'')
MorePrep = MorePrep.replace("'",'')
Final = MorePrep.strip()

find.to_excel(Final, index=False)

Upvotes: 2

Related Questions