我希望用户从Excel复制数据并将其粘贴到电子表格中,如GUI,然后按确定。该数据(三列+100/1000行)将存储在一个数组中,以便在程序中进一步进行后续计算。
我更喜欢使用tkinter,因为它已经包含在我的Python安装中,而Python 3.4不支持其他类似wxPython。
我已经有以下但有一些问题: 1.我无法将数据粘贴到表格中。 2.行数是固定的。那么,如果我的数据比表大,该怎么办?
class SimpleTableInput(tk.Frame):
def __init__(self, parent, rows, columns):
tk.Frame.__init__(self, parent)
self._entry = {}
self.rows = rows
self.columns = columns
# create the table of widgets
for row in range(self.rows):
for column in range(self.columns):
index = (row, column)
e = tk.Entry(self)
e.grid(row=row, column=column, stick="nsew")
self._entry[index] = e
# adjust column weights so they all expand equally
for column in range(self.columns):
self.grid_columnconfigure(column, weight=1)
# designate a final, empty row to fill up any extra space
self.grid_rowconfigure(rows, weight=1)
def get(self):
'''Return a list of lists, containing the data in the table'''
result = []
for row in range(self.rows):
current_row = []
for column in range(self.columns):
index = (row, column)
current_row.append(self._entry[index].get())
result.append(current_row)
return result
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.table = SimpleTableInput(self, 20, 3)
self.table.pack(side="top", fill="both", expand=True)
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()>
答案 0 :(得分:2)
除非您想花费数月时间编写自己的代码,否则#34;翻译"将excel表格变成python可以使用的东西我建议你看一下:http://www.python-excel.org/
根据文件类型(.xls,.xlsx),您需要使用特定的模块进行读/写。更多信息可以在图书馆文档中找到。
这是打印到.xls文件屏幕的简单程序,这应该可以让你开始。
import xlrd
from tkFileDialog import askopenfile
data = tkFileDialog.askopenfilename()
book = xlrd.open_workbook(data) #open our xls file
sheet = book.sheets()[0] #book.sheets() returns a list of objects alternatively...
sheet = book.sheet_by_name("qqqq") #we can pull by name
sheet = book.sheet_by_index(0) #or by the index it has in excel's sheet collection
r = sheet.row(0) #returns all the CELLS of row 0,
c = sheet.col_values(0) #returns all the VALUES of row 0,
datastore = [] #make a data store
for i in xrange(sheet.nrows):
datastore.append(sheet.row_values(i)) #drop all the values in the rows into datastore
print (datastore)
取自here
的代码示例