excel table is as follows:
We need to use a python method to read xlrd excel, then traverse assigned to the dictionary. code show as below:
Import xlrd class Read_Ex (): DEF read_excel (Self): # Open the excel sheet, fill in the path of Book = xlrd.open_workbook ( " ../Data/test.xlsx " ) # find sheet page the Table = book.sheet_by_name ( " Sheet1 " ) # Get the total number of columns of rows row_num = table.nrows col_num = table.ncols S = [] key = table.row_values (0) # this is the first line of data, a dictionary key value IF row_num <=. 1 : Print ( " no data " ) the else : J =. 1 for I in Range (-row_num. 1 ): D = {} values = table.row_values (J) for X in Range (col_num): # the key value corresponding to the value ' to the key, each row cycle D [Key [X]] = values [X] J + =. 1 # the dictionary is added to the list s.append (D) return S IF __name__ == '__main__': r = Read_Ex() s=r.read_excel() for i in s: print(i) print(s)
The results are as follows, respectively, and traversing the display list branches directly output.
Just need to package this function, direct call can be used when needed
Calling code as follows:
# -*- coding:UTF-8 -*- import unittest from day_01.ReadExc import Read_Ex class Test(unittest.TestCase): def test001(self): readExcel=Read_Ex().read_excel() self.assertEqual(3,int(readExcel[0]["a"])+int(readExcel[0]["b"])) if __name__ == '__main__': unittest.main # -*- author: Hiro -*-
If necessary, you can walk readExcel