Получить данные строки для Treeview от Panda - PullRequest
0 голосов
/ 19 марта 2020

У меня есть файл .xlsx, и я хочу воссоздать эту таблицу в GUI, используя Treeview от TKinter. У меня есть решение ниже, которое дает мне вывод, который я хочу, но он длинный, и я не уверен, есть ли лучший способ сделать это. Для моего приложения важна производительность, потому что у меня не так много энергии, и я думаю, что с большим файлом .xlsx я начну видеть снижение производительности.

Я также должен предположить, что я Не знаю заголовок и количество строк, но количество столбцов меньше 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

Есть ли более простой способ получить данные строки и добавить их в древовидную структуру?

1 Ответ

1 голос
/ 19 марта 2020

Я создаю простой пример, чтобы сделать это:

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()

Это мой пример файла Excel:

enter image description here

Результат :

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...