Reputation: 1748
I have a .xlsx
file and I want to recreate that table in a GUI using a Treeview from TKinter. I have a solution below that gives me the output I want but it's long and I'm not sure if there's a better way to do it. For my application, performance is a concern because I don't have that much power and I think with a larger .xlsx
file I'll start to see a performance hit.
I also have to assume that I don't know the heading and number of rows but that the number of columns is less than 15
import numpy as np
import pandas as pd
xls = pd.ExcelFile('file.xlsx');
sheetData = pd.read_excel(xls, 'Sheet-1')
# Get column headings
headings = sheetData.columns
# Convert headings to list
data = list(headings.values.tolist())
# Get row count
rows = len(sheetData)
# Create tree with the the number of columns
# equal to the sheet, the id of the column
# equal to the column header and disable
# the 'treeview'
tree = ttk.Treeview(self, columns=data, show=["headings"],selectmode='browse')
# Create column headings on tree
for heading in headings:
heading = str(heading) # convert to string for processing
tree.column(heading, width=125, anchor='center')
tree.heading(heading, text=heading)
# Populate rows --The part that concerns me
for rownumber in range(rows):
rowvalue = sheetData.values[rownumber] # Get row data
rowvalue = np.array2string(rowvalue) # Convert from an np array to string
rowvalue = rowvalue.strip("[]") # Strip the string of square brackets
rowvalue = rowvalue.replace("'",'') # Replace all instances of ' with no character
tree.insert('', 'end', values= rowvalue) # Append the row to table
Is there a simpler way to get row data and append it to a treeview?
Upvotes: 0
Views: 1370
Reputation: 12672
I create an easy example to do this:
import tkinter as tk
from tkinter import ttk
import pandas as pd
# Maybe This is what you want
def Start():
fp = pd.read_excel("./test.xlsx") # Read xlsx file
for _ in range(len(fp.index.values)): # use for loop to get values in each line, _ is the number of line.
tree.insert('','end',value=tuple(fp.iloc[_,[1,2]].values)) # [_,[1,2]] represents that you will get the values of second column and third column for each line.
win = tk.Tk()
win.wm_attributes('-topmost',1)
# win.geometry("+1300+0")
ttk.Button(win,text="Import it",command=Start).pack()
columns = ("name","gender")
tree = ttk.Treeview(win,show="headings",columns=columns)
tree.column("name",width=100,anchor='center')
tree.column("gender",width=50, anchor="center")
tree.heading("name",text="name")
tree.heading("gender",text="gender")
tree.pack()
win.mainloop()
This is my example excel file:
Result:
Upvotes: 1