python3操作excel和數據庫


1. 讀取excel數據並寫入數據庫

 1 '''
 2 Created on 2019年
 3 讀取excel數據並寫入數據庫
 4 @author: Root
 5 '''
 6 import xlrd
 7 from DBUtils import DBUtils
 8 
 9 # 獲取excel表格
10 def get_sheet():
11     #定義測試用例的文檔位置
12     filename = "E:/eclipse/workspace/Py36/com/wdzy/db2/t1.xlsx"
13     #打開測試文檔
14     excel = xlrd.open_workbook(filename)
15     #讀取sheet頁面位置
16     sheet = excel.sheet_by_name("test")
17     return sheet
18 
19 # 讀取excel表格數據並寫入數據庫
20 def read_write():
21     sheet = get_sheet()
22     sql = "insert into t1qian values(%s,%s)"
23     for i in range(sheet.nrows):
24         l = sheet.row_values(i)
25         count = (l[0],l[1])
26         DBUtils().operate_dateByCount(sql, count)
27         
28 read_write()
View Code

excel只設置了兩行內容id,name

2. 讀取數據庫數據寫入excel表格

 1 '''
 2 Created on 2019年
 3 讀取數據庫數據寫入excel表格
 4 @author: Root
 5 '''
 6 import xlwt
 7 from DBUtils import DBUtils
 8 
 9 # 設置表格樣式
10 def set_style(name,height,bold=True):
11     style = xlwt.XFStyle()
12     font = xlwt.Font()
13     font.name = name
14     font.bold = bold
15     font.colour_index = 4
16     font.height = height
17     style.font = font
18     return style
19 
20 # 將數據寫入excel表格
21 def write_excel(sql,path):
22     # 創建工作薄
23     workbook = xlwt.Workbook(encoding='utf8')
24     # 創建sheet
25     sheet = workbook.add_sheet('test',cell_overwrite_ok=True)
26     # 設置表頭
27     sheet.write(0,0,'id',set_style('Times New Roman', 220, True))   # 1行1列
28     sheet.write(0,1,'name',set_style('Times New Roman', 220, True)) # 1行2列
29 
30     # 查詢數據庫中數據   
31     result = DBUtils().get_allDate(sql)
32 
33     for i in range(len(result)):
34         # 寫入數據
35         sheet.write(i+1,0,result[i][0])   # i+1行1列
36         sheet.write(i+1,1,result[i][1])   # i+1行2列
37     
38     # 保存文件
39     workbook.save(path)
40     
41 #     workbook.close()
42 
43 sql = 'select * from t1qian'
44 path = 'E:/eclipse/workspace/Py36/com/wdzy/db3/t2.xlsx'
45 write_excel(sql, path)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM