這篇文章主要介紹了通過實例學習Python Excel操作,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
1.python 讀取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
|
# -*- coding: utf-8 -*- import xlrd import os,sys reload (sys) sys.setdefaultencoding( "utf8" ) filename = 'text.xlsx' filename = filename.decode( 'utf-8' ) book = xlrd.open_workbook(filename) sheet1 = book.sheets()[ 0 ] nrows = sheet1.nrows print u '表格總行數 ' ,nrows ncols = sheet1.ncols print u '表格總列數 ' ,ncols ##查詢表頭 excelhead = [] for i in range (ncols): excel_head_values = sheet1.col_values(i) excelhead.append(excel_head_values[ 0 ]) ##查詢行的值 excelhang = [] for i in range (nrows)[ 1 :]: row_values = sheet1.row_values(i) print 'User:' + row_values[ 2 ] + ' Filename:' + row_values[ 0 ] + ' Tablename:' + row_values[ 1 ] |
text.xlsx內容如下:
運行結果:
1
2
3
4
5
|
表格總行數 4 表格總列數 3 User:edw Filename:sh002_zyb_tx_chk_h0200.py Tablename:SH002_ZYB_TX_CHK_H0200 User:etl Filename:sh002_a_h0200.py Tablename:SH002_A_H0200 User:app Filename:sh002_b_h0200.py Tablename:SH002_B_H0200 |
2.python 寫入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
|
# -*- coding: utf-8 -*- import xlwt import pymysql def sql_connect(sql): conn = pymysql.connect(host = '192.168.3.xx' ,port = 3306 , user = 'root' , password = '123456' ,db = 'hive' ,charset = 'utf8' ) cur = conn.cursor() cur.execute(sql) data = cur.fetchall() cur.close() conn.close() return data def write_excel(filename, data): book = xlwt.Workbook() #創建excel對象 sheet = book.add_sheet( 'PARTITIONS' ) #添加一個表Sheet c = 0 #保存當前列 for d in data: #取出data中的每一個元組存到表格的每一行 for index in range ( len (d)): #將每一個元組中的每一個單元存到每一列 sheet.write(c,index,d[index]) c + = 1 book.save(filename) #保存excel sql = 'select * from PARTITIONS limit 100' res = sql_connect(sql) write_excel( 'partitions.xls' , res) |
運行結果:
3.python Excel寫入表內
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# -*- coding: utf-8 -*- import xlwt import xlrd import pymysql #從excel讀取數據寫入mysql def excel_to_mysql(filename): conn = pymysql.connect(host = '192.168.3.xx' ,port = 3306 , user = 'root' , password = '123456' ,db = 'hive' ,charset = 'utf8' ) cur = conn.cursor() #連接數據庫 book = xlrd.open_workbook(filename) sheet = book.sheet_by_name( 'Sheet1' ) rows = sheet.nrows #獲取行數 for r in range ( 1 ,rows): #將標題之外的其他行寫入數據庫 r_values = sheet.row_values(r) sql = 'insert into user_zw values(%s,%s,%s)' #有幾個字段需要幾個%s data = cur.execute(sql,r_values) #將每一行插入sql conn.commit() #插入所有數據后提交 cur.close() conn.close() excel_to_mysql( 'user_zw.xls' ) |
user_zw.xls的內容:
查詢表中內容:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/python960410445/p/12153611.html