設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 244|回復: 0
打印 上一主題 下一主題

Python 快速读取 Excel 内容写入 Mysql

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2023-4-20 17:23:50 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
前置准备:
四个文件分别如下:
1. testdata.xls文件
2. 数据库配置信息
3. mysql数据库操作
4. excel读取
  1. 数据库配置信息

  2. PageCount=10

  3. dbhost="10.10.1.248"
  4. dbport=3306
  5. dbuser="root"
  6. dbpasswd="123456"
  7. dbname="testdb"
複製代碼

mysqldb.py文件内容
  1. # 数据库操作

  2. import pymysql
  3. from configs import dbhost,dbpasswd,dbport,dbuser,dbname

  4. def get_cur():
  5.     conn = pymysql.connect(host=dbhost, port=dbport, user=dbuser, passwd=dbpasswd, database=dbname)
  6.     cur = conn.cursor()
  7.     return cur,conn

  8. def get_count(sql):
  9.     cur,conn = get_cur()
  10.     cur.execute(sql)
  11.     count = cur.fetchall()
  12.     cur.close()
  13.     conn.close()
  14.     return count[0][0]


  15. def get_table_colum():
  16.     cur,conn = get_cur()
  17.     cur.execute("select * from xxljob_info")
  18.     col_name_list = [tuple[0] for tuple in cur.description]
  19.     cur.close()
  20.     conn.close()
  21.     return col_name_list

  22. def get_data(sql1):
  23.     cur,conn = get_cur()
  24.     cur.execute(sql1)
  25.     results = cur.fetchall()
  26.     cloumn = get_table_colum()
  27.     res = {}
  28.     reslist = []
  29.     for r in range(len(list(results))):
  30.         for m in range(len(list(cloumn))):
  31.             res[str(list(cloumn)[m])] = str(list(results)[r][m])
  32.         reslist.append(res)
  33.         res = {}
  34.     cur.close()
  35.     conn.close()
  36.     return reslist

  37. def execute_sql(sql):
  38.     cur, conn = get_cur()
  39.     cur.execute(sql)
  40.     cur.close()
  41.     conn.commit()
  42.     conn.close()

  43. if __name__ == '__main__':
  44.     get_table_colum()
  45.     sql = "insert into xxljob_info (executer,describes,router,block,cron,is_repeater,leader,status,mark,create_time) VALUES ('testabc','testabc','第一个','单机串行','testabc','否','testabc','testabc','testabc','2022-06-16 13:14:19')"

  46.     for i in range(55):
  47.         execute_sql(sql)
  48.       # get_count("select count(*) from xxljob_info")
複製代碼
readExcel.py文件内容
  1. # 读取excel表数据,并执行sql

  2. import xlrd
  3. from mysqldb import execute_sql
  4. file = xlrd.open_workbook("testdata.xls")
  5. table1 = file.sheet_by_name("数据表")
  6. sql = "insert into testdata values "

  7. for row in range(table1.nrows - 1):
  8.     list1 = table1.row_values(row + 1)
  9.     list1 = [row + 1] + list1
  10.     execute_sql(sql + str(tuple(list1)))
複製代碼
上 4 个文件即可通过 Python 实现 Excel 内容自动读取并入库 Mysql。



分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-4-29 16:55 , Processed in 0.241692 second(s), 20 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表