I created the following trial code to make a program that will load an excel sheet into a dataframe and then save that dataframe to another excel sheet (all of the user's choosing)
import os
import pandas
from pandas import ExcelWriter
import tkinter as tk
from tkinter import filedialog
class Load_Save_Program():
def __init__(self,master):
self.master = master
self.button1=tk.Button(self.master,text="Load",command=self.Load_file)
self.button1.grid(row=0,column=0)
self.button2=tk.Button(self.master,text="Save",command=self.Save_file)
self.button2.grid(row=0,column=1)
self.text=tk.Text(master)
self.text.grid(row=1,column=0,columnspan=2)
def Load_file(self):
self.df_import=pandas.read_excel(filedialog.askopenfilename(initialdir = os.getcwd()),
filetypes=("excel files","*.xlsx"))
self.text.insert(tk.END,self.df_import)
def Save_file(self):
self.writer = ExcelWriter(filedialog.asksaveasfilename(initialdir = os.getcwd()),
filetypes=("Excel files", "*.xlsx"))
self.df_import.to_excel(self.writer,'sheet1')
self.writer.save()
root=tk.Tk()
Load_Save_Program(root)
root.mainloop()
What I would like to do is to expand this so that when the program pops up the file directory window, it only shows files that are of the .xlsx filetype as to avoid an error from the user opening up an incompatible file type. So far I've yet to come up with any information that can explain how to set this up properly.
The filedalogs have a filetypes option to do exactly what you want. The general syntax is filetypes=[(label1, ext1), (label2, ext2), ...]
.
In your case that will give:
filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
It turns out that the order is important. Additionally, the answer must include the [] around the filetype. The two lines in question must be
self.df_import=pandas.read_excel(filedialog.askopenfilename(filetypes=[("Excel files","*.xlsx")],initialdir = os.getcwd()))
self.writer = ExcelWriter(filedialog.asksaveasfilename(filetypes=[("Excel files", "*.xlsx")],initialdir = os.getcwd()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With