使用python将excel数据导入数据库
https://www.cnblogs.com/longbigbeard/p/9309180.html?
- 因為需要對數據處理,將excel數據導入到數據庫,記錄一下過程。
- 使用到的庫:xlrd 和 pymysql (如果需要寫到excel可以使用xlwt)
- 直接丟代碼,使用python3,注釋比較清楚。
-
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
import?xlrd
import?pymysql
# import importlib
# importlib.reload(sys) #出現呢reload錯誤使用
?
?
def?open_excel():
????try:
????????book?=?xlrd.open_workbook("XX.xlsx")??#文件名,把文件與py文件放在同一目錄下
????except:
????????print("open excel file failed!")
????try:
????????sheet?=?book.sheet_by_name("sheet名稱")???#execl里面的worksheet1
????????return?sheet
????except:
????????print("locate worksheet in excel failed!")
?
?
#連接數據庫
try:
????db?=?pymysql.connect(host="127.0.0.1",user="root",
????????passwd="XXX",
????????db="XXX",
????????charset='utf8')
except:
????print("could not connect to mysql server")
?
def?search_count():
????cursor?=?db.cursor()
????select?=?"select count(id) from XXXX"?#獲取表中xxxxx記錄數
????cursor.execute(select)?#執行sql語句
????line_count?=?cursor.fetchone()
????print(line_count[0])
?
?
def?insert_deta():
????sheet?=?open_excel()
????cursor?=?db.cursor()
????for?i?in?range(1, sheet.nrows):?#第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數,所以值是1
?
????????name?=?sheet.cell(i,0).value?#取第i行第0列
????????data?=?sheet.cell(i,1).value#取第i行第1列,下面依次類推
????????print(name)
????????print(data)
????????value?=?(name,data)
????????print(value)
????????sql?=?"INSERT INTO XXX(name,data)VALUES(%s,%s)"
????????cursor.execute(sql,value)?#執行sql語句
????????db.commit()
????cursor.close()?#關閉連接
?
?
?
insert_deta()
?
db.close()#關閉數據
print?("ok ")
XXX里自行修改自己的名稱。
- 說明:對于不規則的單元格,例如合并過的單元格會取到空值。
- 有機會把數據庫寫到excel貼上來。
- ?
- ?
- ?優化了一下這個程序
-
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
import?pymysql
import?xlrd
?
?
# 連接數據庫
try:
????db?=?pymysql.connect(host="127.0.0.1", user="root",
?????????????????????????passwd="XXX",
?????????????????????????db="XXX",
?????????????????????????charset='utf8')
except:
????print("could not connect to mysql server")
?
?
def?open_excel():
????try:
????????book?=?xlrd.open_workbook("XXX.xlsx")??#文件名,把文件與py文件放在同一目錄下
????except:
????????print("open excel file failed!")
????try:
????????sheet?=?book.sheet_by_name("XXX")???#execl里面的worksheet1
????????return?sheet
????except:
????????print("locate worksheet in excel failed!")
?
?
def?insert_deta():
????sheet?=?open_excel()
????cursor?=?db.cursor()
????row_num?=?sheet.nrows
????for?i?in?range(1, row_num):??# 第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數,所以值是1
????????row_data?=?sheet.row_values(i)
????????value?=?(row_data[0],row_data[1],row_data[2],row_data[3])
????????print(i)
????????sql?=?"INSERT INTO demo_yangben(xxx,xxxx,xxxx,xxxx)VALUES(%s,%s,%s,%s)"
????????cursor.execute(sql, value)??# 執行sql語句
????????db.commit()
????cursor.close()??# 關閉連接
?
?
open_excel()
insert_deta()
- ?
- ?
- ?
- ?
- ?
- ?再改一下,每一萬條數據寫入到數據庫一次
-
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
import?pymysql
import?xlrd
import?sys
?
'''
????連接數據庫
????args:db_name(數據庫名稱)
????returns:db
?
'''
?
?
def?mysql_link(de_name):
????try:
????????db?=?pymysql.connect(host="127.0.0.1", user="xxx",
?????????????????????????????passwd="xxx",
?????????????????????????????db=xxx,
?????????????????????????????charset='utf8')
????????return?db
????except:
????????print("could not connect to mysql server")
?
?
'''
????讀取excel函數
????args:excel_file(excel文件,目錄在py文件同目錄)
????returns:book
'''
?
?
def?open_excel(excel_file):
????try:
????????book?=?xlrd.open_workbook(excel_file)??# 文件名,把文件與py文件放在同一目錄下
????????print(sys.getsizeof(book))
????????return?book
????except:
????????print("open excel file failed!")
?
?
'''
????執行插入操作
????args:db_name(數據庫名稱)
?????????table_name(表名稱)
?????????excel_file(excel文件名,把文件與py文件放在同一目錄下)
?
'''
?
?
def?store_to(db_name, table_name, excel_file):
????db?=?mysql_link(db_name)??# 打開數據庫連接
????cursor?=?db.cursor()??# 使用 cursor() 方法創建一個游標對象 cursor
?
????book?=?open_excel(excel_file)??# 打開excel文件
????sheets?=?book.sheet_names()??# 獲取所有sheet表名
????for?sheet?in?sheets:
????????sh?=?book.sheet_by_name(sheet)??# 打開每一張表
????????row_num?=?sh.nrows
????????print(row_num)
????????list?=?[]??# 定義列表用來存放數據
????????num?=?0??# 用來控制每次插入的數量
????????for?i?in?range(1, row_num):??# 第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數,所以值是1
????????????row_data?=?sh.row_values(i)??# 按行獲取excel的值
????????????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], row_data[9], row_data[10], row_data[11], row_data[12],
?????????????????????row_data[13], row_data[14])
????????????list.append(value)??# 將數據暫存在列表
????????????num?+=?1
????????????if( num>=?10000?):??# 每一萬條數據執行一次插入
????????????????print(sys.getsizeof(list))
????????????????sql?=?"INSERT INTO "?+?table_name?+?" (time, xingbie, afdd, xzb, yzb, cfbj, jjlbmc, \
????????????????bjlbmc, bjlxmc, bjlxxlmc, gxqymc,gxdwmc, afql, afxqxx, cjdwmc)\
????????????????VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
????????????????cursor.executemany(sql,?list)??# 執行sql語句
?
????????????????num?=?0??# 計數歸零
????????????????list.clear()??# 清空list
????????????????print("worksheets: "?+?sheet?+?" has been inserted 10000 datas!")
?
????print("worksheets: "?+?sheet?+?" has been inserted "?+?str(row_num)?+?" datas!")
????db.commit()??# 提交
????cursor.close()??# 關閉連接
????db.close()
?
?
if?__name__?==?'__main__':
????store_to('demo',?'demo_yangben',?'xxx.xlsx')
- ?
- ?
- 思考,如果數據插入有錯誤,怎么解決,
- ?
- ?其實有很多數據庫工具可以直接來解決這個問題,注意字符轉換的格式就好。
- ?
- ?上面這個程序在當數據不足10000的時候會出現問題,下面的一篇文章里進行了更正。
- 批量插入數據請看:?https://www.cnblogs.com/longbigbeard/p/9317141.html
- 以上。
總結
以上是生活随笔為你收集整理的使用python将excel数据导入数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 21天学通python 第2版_21天学
- 下一篇: Python 齿轮动力学建模及信号分析(