First install xlrd module: pip install xlrd, there are many online core code, here mainly deal with some personal details about the actual problem encountered
1, excel data does not result in the presence of specification data read blank rows and columns;
2, performs parameterized sql
Code below for reference:
. 1 Import xlrd 2 . 3 Import AppSetting.AppConfig AS config . 4 Import AppSetting.dbConfig AS DB . 5 . 6 # processing excel dependent xlrd the install module xlrd PIP . 7 . 8 # read excel file . 9 excel_data = xlrd.open_workbook (config.file_path) 10 # Get the first sheet p . 11 sheet = excel_data.sheet_by_index (0) 12 is # total rows 13 is rows = sheet.nrows 14 # obtain column (often there may be read to excel blank blank column or row, where the first row of data in accordance with acquiring data to be imported to the number of columns) 15 rowlsts = [Ifor I in sheet.row_values (0) IF I! = '' ] 16 Cursor = db.connect.cursor () . 17 # define variables n, when n = parameterized when assembled SQL 0 18 is n = 0 . 19 SQL = " " 20 # because excel in the first row is stored in the field names, the data acquired from the second line 21 is for I in Range (. 1 , rows): 22 is the try : 23 is Item = sheet.row_values (I) [: len (rowlsts )] 24 Data = '' 25 # assembled parametric sql, obtained by splicing placeholder S% 26 is for j in range(0, len(rowlsts)): 27 data += "%s," 28 data = data.rstrip(',') 29 if n == 0: 30 sql = "insert into co_zfxx(%s) values( %s )" % (str.join(',', rowlsts), data) 31 cursor.execute(sql, tuple(item)) 32 else: 33 cursor.execute(sql, tuple(item)) 34 35 except Exception as ex: 36 print(ex) 37 38 finally: 39 n += 1 40 41 db.connect.commit() 42 cursor.close() 43 db.connect.close()
The test execution 5w of data (26 fields), the execution time of 22s