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