-3

How to upload excel file using Tkinter

read and show line by line in frames in loops, having a next button?

2
  • 1
    Welcome to SO. In order for someone to help you will need to expand on what it is you are trying to achieve and what help you need. What/where/how do you want to upload the Excel file. Are you wanting to show the Excel rows [columns] in tkinter? The 'next button' is expected to cycle through rows/columns or something else?
    – moken
    Sep 4, 2022 at 12:35
  • Hi @moken, I want to browse an excel file(not any specific file), and then read and show its content rowwise in cycle using the "Next Button". Hope, I am able to make you understand the scenario.
    – Sabbha
    Sep 5, 2022 at 6:57

1 Answer 1

0

How the data is displayed may depend on what data is used, type and size (length). Openpyxl will allow you to create a list of the cell values in a row which can then be inserted into the tkinter widget. The next button would increment the current row from which the cells are being read.
The Treeview widget is often used for Excel data as it uses grids like Excel.
The following example uses Treeview to display 1 row only of of an Excel Sheet. Clicking the 'next' button will overwrite this data with the next row's data and the 'prev' button overwrites with the previous row's data.
If the last row is displayed and 'next' button is pressed the row will loop back to the fist row.
If the first row is displayed and 'prev' button is pressed the row will loop to the last row.
The 'exit' button will exit the program.
The program is set to cycle through all used rows except Row 1 which is assumed to be the Header row which is used to create the display headers, and all used columns. It should display both text and numeric data.
Column 0, the identifier column is used to display the current row being displayed.
Columns widths are hard set for this example.

from tkinter import Tk, Button, W, CENTER, END
import tkinter.ttk as ttk
from openpyxl import load_workbook


class ExcelRows(Tk):

    def __init__(self, ):
        super().__init__()
        self.initialize_display()

    def initialize_display(self):
        # Configure root object
        self.title('Excel Rows')
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.config(background="yellow")

        # Load Excel Workbook and Sheet
        self.wb = load_workbook('../excel_files/foo.xlsx')
        self.ws = self.wb['Sheet8']

        # Initialise the row count
        self.cur_row = 0

        # Define 'Previous' button
        self.button_prev = Button(self, text='Get prev Row',
                                     command=lambda: self.insert_row_data('prev'))
        self.button_prev.grid(row=5, column=0, sticky=W)

        # Define 'Next' button
        self.button_next = Button(self, text='Get next Row',
                                     command=lambda: self.insert_row_data('next'))
        self.button_next.grid(row=5, column=1, sticky=W)

        # Define 'Exit' button
        self.exit_button = Button(self, text="Exit", command=self.quit)
        self.exit_button.grid(row=5, column=2)

        # Define treeview display
        col_list = self.get_columns()
        self.treeview = ttk.Treeview(self, columns=col_list, height=3)

        # Set the headings and column widths
        for enum, col_header in enumerate(col_list):
            self.treeview.heading(enum, text=col_header)
            self.treeview.column(col_header, width=50)
        self.treeview.heading('#0', text='Row', anchor=CENTER)
        self.treeview.column("#0", width=65)
        self.treeview.grid(row=1, columnspan=3, sticky='w')

    def get_columns(self):
        # Get a list of headers from row 1 and enter as Treeview Headers
        header_names = []
        for cell in self.ws[1]:
            header_names.append(cell.value)
        return header_names

    def insert_row_data(self, seq):
        # Get the row as selected by the 'next' or 'prev' button and insert to Treeview
        row_list = []

        # Clear existing Treeview data before writing new data to same row
        for item in self.treeview.get_children():
            self.treeview.delete(item)

        # 'next' button increments the current row, if the end of the used rows is reached
        # the row is set back to the start and loops
        if seq == 'next':
            self.cur_row += 1
            if self.cur_row == self.ws.max_row:
                self.cur_row = self.ws.min_row

        # 'prev' button decrements the current row, if the start of the used rows is reached
        # the row is set to the last used row and loops
        elif seq == 'prev':
            self.cur_row -= 1
            if self.cur_row == self.ws.min_row - 1 or self.cur_row == -1:
                self.cur_row = self.ws.max_row - 1

        # Builds a list of cell values in the set row
        for row_cells in self.ws.iter_cols(min_col=self.ws.min_column,
                                           max_col=self.ws.max_column):
            row_list.append(str(row_cells[self.cur_row].value))

        # Insert the row_list into the Treeview
        self.treeview.insert('', END,
                             text="Row " + str(self.cur_row),
                             values=[row_list][0])


app = ExcelRows()
app.mainloop()

Example view enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.