Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use tkinter to prompt users to save a DataFrame to an Excel file?

I'm new to Python and programming in general. I'm trying to build a GUI for some code I wrote that imports data from Excel, does some analysis, then exports the new data from the DataFrame to another Excel file. I used this code previously, but now I need a prompt that asks the user where they want to save the file:

writer = pd.ExcelWriter("Results.xlsx", engine="xlsxwriter")
data.to_excel(writer, index=False, sheet_name="Results")
worksheet = writer.sheets["Results"]
writer.save()

Unfortunately, I can't get it to save the new Excel file when I use asksaveasfilename. Here's what I have been using to test file saving:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
import pandas as pd

class Analysis:
    def __init__(self, master):
        self.master = master
        master.title("Test")

        self.message = "Select an Excel file to import."
        self.label_text = StringVar()
        self.label_text.set(self.message)
        self.label = Label(master, textvariable=self.label_text)

        self.button = Button(master, text="Browse", command=self.load_file)
        self.label.grid(row=0, column=0, columnspan=2, sticky=W)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        file = askopenfilename(filetypes=(("Excel files", "*.xlsx"),
                                           ("All files", "*.*") ))
        if file:
            try:
                data = pd.read_excel(file,sheetname="Sheet1")
                #this doesn't save anything
                savefile = asksaveasfilename(mode="w",filetypes=(("Excel files", "*.xlsx"),
                                                          ("All files", "*.*") ))
                #used this code before
                writer = pd.ExcelWriter("Results.xlsx", engine="xlsxwriter")
                data.to_excel(writer, index=False, sheet_name="Results")
                worksheet = writer.sheets["Results"]
                writer.save()                
                self.message = "Complete"
                self.label_text.set(self.message)
            except:
                self.message = "Error"
                self.label_text.set(self.message)
                showerror("Open Source File", "Failed to import file\n'%s'" % file)
            return

root=Tk()
my_gui = Analysis(root)
root.mainloop()

I appreciate any help. Thanks!

Edit: I got it to work

    def load_file(self):
        file = askopenfilename(filetypes=(("Excel files", "*.xlsx"),
                                       ("All files", "*.*") ))
        if file:
            try:
                savefile = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),
                                                         ("All files", "*.*") ))               
                data = pd.read_excel(file,sheetname="Sheet1")
                data.to_excel(savefile + ".xlsx", index=False, sheet_name="Results")         
                self.message = "Complete"
                self.label_text.set(self.message)
            except:
                self.message = "Error. Please try again."
                self.label_text.set(self.message)
                showerror("Open Source File", "Failed to import file\n'%s'" % file)
            return
like image 866
WoomyWoomy Avatar asked Oct 27 '16 23:10

WoomyWoomy


2 Answers

There shouldn't be mode option. This is enough:

savefile = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"), ("All files", "*.*") ))

like image 84
Marcin Avatar answered Sep 19 '22 16:09

Marcin


design an example of how the process would be, but you must take into account the libraries used to generate the Excel file, then adapt it to your needs, taking into account that you have been slow to answer this question. I invite you to investigate the libraries used and They want to create their file with colors, fonts and formulas in a personalized way.

import xlwt
from xlwt import Workbook
import easygui as eg
from tkinter import *
from tkinter import ttk
import tkinter as tk
def generator():
    documento=Workbook()
    insert_celdas = documento.add_sheet('Nomina')
    cambio=insert_celdas.set_portrait(False)
    extension =["*.xls"]
    gplanilla=eg.filesavebox(msg="save file",
        title="",default='file_name_default',
        filetypes=extension) 
    if (gplanilla is not None) and (len(gplanilla)!=0):
        documento.save(str(gplanilla)+".xls")
        print("Proceso de generacion de nomina completado")
    else:
        print("cancelado proceso de generacion de nomina")
        return False
window=Tk()
window.geometry("508x400+0+0")
window.title("my code (the saltorman)")
Button(window,text="generate file excel",command=generator).pack()
window.mainloop()

my_code:execute.jpg

like image 27
Samuel Enrique Molina Bermudez Avatar answered Sep 21 '22 16:09

Samuel Enrique Molina Bermudez