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
| '''批量将Excel数据写入MySQL''' import pymysql import xlrd
def mysql_link(db_name): ''' 连接数据库 guest:数据库名称 return:db ''' try: db = pymysql.connect(host='192.168.0.*', user='username', passwd='password', db=db_name, charset='utf8mb4') return db except ConnectionError as e: print("数据库连接异常!" + str(e))
def open_excel(excel_file): ''' 读取Excel函数 excel_file:表格文件路径 return:book ''' try: book = xlrd.open_workbook(excel_file) return book except Exception as e: print(str(e))
def store_to(db_name, table_name, file_url): ''' 执行插入操作 db_name(数据库名称) table_name(表名称) excel_file(excel文件名,把文件与py文件放在同一目录下) ''' db = mysql_link(db_name) cursor = db.cursor()
book = open_excel(file_url) sheets = book.sheet_names() for sheet in sheets: sh = book.sheet_by_name(sheet) row_nuw = sh.nrows print(row_nuw - 1) listdata = [] for i in range(1, row_nuw): row_data = sh.row_values(i) listdata.append(row_data) print(listdata) sql = "INSERT INTO " + table_name + "(tracking_name, tracking_no, create_date, sort_num, del_flag) " \ "VALUES (%s, %s, %s, %s, %s)" cursor.executemany(sql, listdata) db.commit() listdata.clear() print('插入成功!' + '共计' + str(row_nuw - 1) + '条数据!') cursor.close() db.close()
if __name__ == '__main__': store_to('cccivaoperate', 't_tracking', '快递.xlsx')
|