前提:
python操作excel需要使用的模块有xlrd、xlwt、xlutils。对excel进行读、写、更新操作。操作excel时需要先导入这些模块,demo如下:
excel-读操作知识点:
1 import xlrd 2 \'\'\' 3 读取 excel的操作步骤如下: 4 1. 打开excel,打开的excel必须存在 5 2. 获取sheet对象 6 3. 对excel进行操作: 7 获取excel的总行数、总列数、读取excel每一行的数据、读取excel每一列的数据、获取某个单元格的值 8 \'\'\' 9 #打开excel,打开的excel必须存在,返回book对象 10 book = xlrd.open_workbook(\'students.xlsx\') 11 #通过索引获取sheet对象 12 sheet = book.sheet_by_index(0) 13 #有多个sheet页时可以通过sheet的名称来获取sheet对象 14 sheet1 = book.sheet_by_name(\'Sheet1\') 15 16 #获取excel的总行数, 17 rows = sheet.nrows 18 #获取excel的总列数 19 cols = sheet.ncols 20 #获取excel第2行的数据,返回结果为list:[2.0, \'b\', \'women\'] 21 row_value = sheet.row_values(2) 22 #获取excel第1列的数据,返回结果为list:[\'name\', \'a\', \'b\', \'c\', \'d\', \'e\', \'f\', \'g\', \'小白\', \'小黑\'] 23 col_values = sheet.col_values(1) 24 #获取单元格第8行第1列的数据,返回结果为text: text:\'小白\' 25 cell_value = sheet.cell(8, 1) 26 #将text类型的结果转换为str类型:小白 27 cell_str = sheet.cell(8, 1).value
注意:获取每行、每列、某个单元格的值时,注意行、列的值要存在,否则会报错:list index out of range
excel - 读取excel小案例:
1 import xlrd 2 \'\'\' 3 读取excel的数据,读取数据的列固定,循环读取每行数据,读取后的数据格式如下: 4 [ 5 {\'name\':xxx,\'sex\':xxx,\'id\':1}, 6 {\'name\':xxx,\'sex\':xxx,\'id\':1}, 7 ....... 8 ] 9 \'\'\' 10 def readExcel(): 11 try: 12 #若输入的excel不存在,则打开excel报错 13 book = xlrd.open_workbook(\'students.xlsx\') 14 except Exception as e: 15 print(\'error msg:\', e) 16 else: 17 sheet = book.sheet_by_index(0) 18 #获取excel的总行数 19 rows = sheet.nrows 20 stu_list = [] 21 #循环读取每行数据,第0行是表头信息,所以从第1行读取数据 22 for row in range(1, rows): 23 stu = {} 24 #获取第row行的第0列所有数据 25 id = sheet.cell(row, 0).value 26 name = sheet.cell(row, 1).value 27 sex = sheet.cell(row, 2).value 28 #将id、name、sex添加到字典,若元素不存在则新增,否则是更新操作 29 stu[\'id\'] = id 30 stu[\'name\'] = name 31 stu[\'sex\'] = sex 32 stu_list.append(stu) 33 print(stu_list) 34 35 if __name__ == \'__main__\': 36 readExcel()
excel数据格式如下:
excel - 写操作知识点:
1 import xlwt 2 \'\'\' 3 写 excel的操作步骤如下: 4 1. 打开excel,打开不存在的excel,若打开已存在的excel,进行写操作,写入的数据会覆盖以前的数据 5 2. 获取sheet对象并指定sheet的名称 6 3. 对excel进行操作: 7 写入excel、保存excel 8 \'\'\' 9 #打开excel创建book对象 10 book = xlwt.Workbook() 11 #创建sheet指定sheet名称 12 sheet = book.add_sheet(\'stu2\') 13 #写入excel数据,第n行第n列写入某个值,写入的数据类型为str 14 sheet.write(0, 0, \'编号\') 15 sheet.write(0, 1, \'姓名\') 16 sheet.write(0, 2, \'年龄\') 17 #保存excel,保存的后缀必须是xls 18 book.save(\'studet.xls\')
excel写入 新的excel后,数据格式如下:
excel操作 已存在的excel,进行写操作后的 excel格式如下:
---->
excel - 写excel小案例:
1 import xlwt 2 \'\'\' 3 将list数据: 4 [{\'name\': \'小白\', \'id\': 1.0, \'sex\': \'男\'}, 5 {\'name\': \'小花\', \'id\': 2.0, \'sex\': \'女\'}, 6 {\'name\': \'小黑\', \'id\': 3.0, \'sex\': \'男\'}, 7 {\'name\': \'小茹\', \'id\': 4.0, \'sex\': \'女\'}, 8 {\'name\': \'小小\', \'id\': 5.0, \'sex\': \'男\'}] 9 写入excel,title信息为:编号、姓名、性别 10 \'\'\' 11 def writeExcel(): 12 book = xlwt.Workbook() 13 sheet = book.add_sheet(\'stu\') 14 titles = [\'编号\', \'姓名\', \'性别\'] 15 #循环读取titles的长度,col的值为:0,1,2,并将title值写入excel 16 for title_col in range(len(titles)): 17 #title 写入excel的第0行的第col列,写入titles[col]值 18 sheet.write(0, title_col, titles[title_col]) 19 students_list = [{\'name\': \'小白\', \'id\': 1.0, \'sex\': \'男\'},{\'name\': \'小花\', \'id\': 2.0, \'sex\': \'女\'},{\'name\': \'小黑\', \'id\': 3.0, \'sex\': \'男\'},{\'name\': \'小茹\', \'id\': 4.0, \'sex\': \'女\'},{\'name\': \'小小\', \'id\': 5.0, \'sex\': \'男\'}] 20 for stu_row in range(len(students_list)): 21 #循环读取student_list的长度,从0开始,写入excel时从第1行开始写入数据 22 #写入excel的数据是从list里进行取值,获取list的每个元素,返回字典,然后通过字典的key获取value 23 sheet.write(stu_row+1, 0, students_list[stu_row][\'id\']) 24 sheet.write(stu_row+1, 1, students_list[stu_row][\'name\']) 25 sheet.write(stu_row+1, 2, students_list[stu_row][\'sex\']) 26 book.save(\'student.xls\') 27 if __name__ == \'__main__\': 28 writeExcel()
excel数据格式如下:
excel- 更新操作知识点:
1 import xlrd 2 from xlutils.copy import copy 3 \'\'\' 4 更新excel操作: 5 1. 打开excel,更新的excel必须存在 6 2. 复制一个新的excel,使用xlutils模块中的copy方法 7 3. 更新excel内的数据 8 4. 保存更新后的excel数据,以前的excel数据不会更改 9 \'\'\' 10 from xlutils.copy import copy 11 #打开excel 12 book = xlrd.open_workbook(\'student.xlsx\') 13 #复制一个新的excel 14 new_book = copy(book) 15 #查看某个对象下的所有方法 16 #print(dir(new_book)) 17 #获取新excel的sheet对象 18 sheet = new_book.get_sheet(0) 19 #新增一列数据 20 sheet.write(0, 3, \'更新\') 21 #更新第4行第1列的值,将其修改为\'郭静\',修改的数据类型为str 22 sheet.write(4, 1, \'郭静\') 23 #保存更改后的excel,以前的excel数据不更改 24 new_book.save(\'student.xls\')
以上为excel简单操作~~~~
案例:
写一个函数,传入一个表名,然后把这个表里面所有的数据导出excel里面
import pymysql import xlwt import hashlib dic = { "host": \'192.1xx.xx.x\', \'user\': \'mysql_xx\', \'password\': \'xxx@123\', \'port\': 3306, \'db\': \'user_xx\' } #mysql 操作 def op_mysql( sql, res_many=False): con = pymysql.connect(host=dic[\'host\'], user=dic[\'user\'], password=dic[\'password\'], db=dic[\'db\'], port=dic[\'port\'], charset=\'utf8\', autocommit=True) cur = con.cursor(pymysql.cursors.DictCursor) cur.execute(sql) if res_many: res = cur.fetchall() else: res = cur.fetchone() cur.close() con.close() return res # 查询sql,将结果写入excel def op_table(table_name): sql = \'select * from {0};\'.format(table_name) res_data = op_mysql(sql, res_many=True) #返回结果是list [{},{}] book = xlwt.Workbook() sheet = book.add_sheet(\'标签\') for row, row_data in enumerate(res_data): for col, col_key in enumerate(row_data): # 获取下标、字典key if row == 0: sheet.write(0, col, col_key) else: sheet.write(row, col, row_data[col_key]) book.save(\'label_data.xls\') op_table(\'xxx_label\')
excel 插件效果: