我想将任何示例MS Excel电子表格中的所有数据(标题、列、行(导入tkinter框架。我试过做,但没有成功。有人能帮我完成这项任务吗?非常感谢。
这是我迄今为止开发的代码,但在这段代码中有通过列导入数据的按钮。我的期望是直接导入excel文件中的所有行和列,而无需单击任何按钮。此外,列的宽度应该重新调整。
from tkinter import *
from openpyxl.workbook import Workbook
from openpyxl import load_workbook
root = Tk()
root.title('Excel Sheet via Tkinter')
# root.iconbitmap('')
root.geometry("500x800")
# Create workbook instance
wb = Workbook()
# Load existing workbook
wb = load_workbook('test.xlsx')
# Create active worksheet
ws = wb.active
# Create variable for Column A
column_a = ws['A']
column_b = ws['B']
def get_a():
list = ''
for cell in column_a:
list = f'{list + str(cell.value)}n'
label_a.config(text=list)
def get_b():
list = ''
for cell in column_b:
list = f'{list + str(cell.value)}n'
label_b.config(text=list)
ba = Button(root, text="Get Column A", command=get_a)
ba.pack(pady=20)
label_a = Label(root, text="")
label_a.pack(pady=20)
bb = Button(root, text="Get Column B", command=get_b)
bb.pack(pady=20)
label_b = Label(root, text="")
label_b.pack(pady=20)
root.mainloop()
附言:我对Python很陌生,所以请和我一起裸一下。
使用只读模式从excel中获取所有数据以在Openpyxl中列出,每个子列表代表一行,因此您可以在每行上通过len()
找到列号。然后返回tkinter,创建与列表中的总行数相匹配的帧数。每一帧都会创建由每行的列数决定的音符数。并将列表中所有单元格的信息分配给tkinker的笔记
这只是基本的框架工作,欢迎您在tkinter中调整颜色和大小等内容。试试看:
def excel_data_to_list(excel):
from openpyxl import load_workbook
wb = load_workbook(filename=excel, read_only=True)
ws = wb.worksheets[0] # you can change it by making an arguments to input sheetname,
info = []
for row in ws.rows:
info_row =[]
for cell in row:
info_row.append(cell.value)
info.append(info_row)
wb.close()
return info
def excel_sheet_via_tkinter(excel):
import tkinter as tk
root = tk.Tk()
root.title('Excel Sheet via Tkinter')
root.geometry("500x800") # you may want to define a better size to fit all data from excel
info = excel_data_to_list(excel)
for row_num, row in enumerate(info):
for col_num, cell in enumerate(row):
label = tk.Label(root, text=cell) # you can add color in each label, this code hasn't involve this part yet
label.grid(row=row_num, column=col_num)
root.mainloop()
# run everything now!!!
excel = 'import_export.xlsx' # this is my file name, but input your
excel_sheet_via_tkinter(excel)