Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to import excel into python and read the contents?
How to import excel into python and read the contents?
Many pd libraries and xlrd libraries can be used to read excel.

take for example

Import XLR Drom XLRD Import XLDate _ As _ Tuple Import Datetime' XLRD cell data type numbers is always output as floating point type, date is output as decimal string, and Boolean type output is 0 or 1, so we must make a judgment in the program and convert it into the data type we want, 0 is empty. 1 string, 2 number, 3 date, 4 Boolean, 5 error''' class Excel data (): # initialization method def __init__(self, data_path, Sheetname): # Define the path of attribute receiving file self.data_path = data_path # Define the name of attribute receiving worksheet self.sheetname = sheetname # Use xlrd module to open an Excel table to read data self. data = xlrd. Open _ workbook (self. data _ path) # Get the worksheet content according to the worksheet name (mode ①) self. Table = self. Data. Sheet name (self. Sheet name) # Get the contents of the worksheet according to the index of the worksheet (mode ②) # self.table = self.data.sheet _ by _ name (0) # Get all the contents of the first row. If 1 in parentheses is the second line, it is similar to a list index: self. Key = self. Table. Row _ values (0) # Get the effective number of rows in the worksheet: self.rowNum = self.table.nrows # Get the effective number of columns in the worksheet self.colNum = self.table.ncols # Define the method of reading excel tables; Def readExcel(self): # Define an empty list data = []. For i in range( 1, Self.rowNum): # Define an empty dictionary sheet _ data = {} for j in range (self). Colnum): # Get the cell data type c _ type = self.table.cell (I, j). Ctype # gets cell data c_cell = self.table.cell_value(i, j) If c _ type = = 2, c _ cell% 1 = = 0: # If it is plastic, c_cell = int(c_cell). Elif c_type == 3: # Convert to date and time object Date = date and time. datetime(* XL date _ as _ tuple(c _ cell, 0))c _ cell = date . strftime(' % Y/% d/% M % H:% M:% S ')elif c _ type = = 4:c _ cell = True if c _ cell = = 1 Else false sheet _ data [self. keys [j]] = c _ cell # Loop through each valid cell and store the fields and values in the dictionary # The key of the dictionary is the field # sheet _ data [self]. keys [j]] = self。 Table. Row _ values (i) [j] # is located in the first row of each column in the excel table. Then the dictionary is appended to the list data. Append (sheet _ data) # returns data obtained from excel: returns data if _ _ name _ = "_ _ main _ _": data _ path = "TTT. Xlsx "sheet name =" sheet1"get _ data = Excel in the form of list dictionary. ata(data_path,sheet name)datas = get _ data . read excel()print(datas)