1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import pymysql import xlrd
''' 连接数据库 args:db_name(数据库名称) returns:db '''
def mysql_link(db_name): try: db = pymysql.connect(host="xxx.xxx.xxx.xxx", port=xxxx, user="xxxxxx", passwd="xxxxxx", db=db_name, charset='utf8') except: print("could not connect to mysql server") return db
''' 读取excel函数 args:excel_file(excel文件,目录在py文件同目录) returns:book '''
def open_excel(excel_file): try: book = xlrd.open_workbook(excel_file) except: print("open excel file failed!") return book
''' 执行插入操作 args:db_name(数据库名称) table_name(表名称) excel_file(excel文件名,把文件与py文件放在同一目录下) '''
def store_to(db_name: object, table_name: object, excel_file: object) -> object: db = mysql_link(db_name) cursor = db.cursor() book = open_excel(excel_file) sheets = book.sheet_names() for sheet in sheets: sh = book.sheet_by_name(sheet) row_num = sh.nrows if row_num != 0: print(row_num - 1) data_list = [] num = 0 for i in range(1, row_num): row_data = sh.row_values(i) value = ( row_data[0], row_data[1], row_data[2], row_data[3], row_data[4], row_data[5], row_data[6], row_data[7], row_data[8]) sql = "INSERT INTO " + str(table_name) + "(brand,sub_model_name,v8_10,`year`,trans_code,oe_code,std_name," \ "`level`,specification,creator,updator) VALUES(%s,%s,%s,%s,%s," \ "%s,%s,%s,%s,\"xing.liuxing1218\",\"xing.liuxing1218\") " data_list.append(value) num += 1 if num >= 1000: cursor.executemany(sql, data_list) data_list.clear() print("worksheets: " + sheet + " has been inserted 1000 data!") num = 0 cursor.executemany(sql, data_list) data_list.clear() print("worksheets: " + sheet + " has been inserted " + str(num) + " data!") if row_num != 0: print("Success: worksheets: " + sheet + " has been inserted " + str(row_num - 1) + " data!") db.commit() cursor.close() db.close() return 0
if __name__ == '__main__': store_to('xxx', 'xxx', 'xxx.xls')
|