python笔记8 - excel操作
前提:
python操作excel需要使用的模块有xlrd、xlwt、xlutils。对excel进行读、写、更新操作。操作excel时需要先导入这些模块,demo如下:
excel-读操作知识点:
- import xlrd
- '''
- 读取 excel的操作步骤如下:
- 1. 打开excel,打开的excel必须存在
- 2. 获取sheet对象
- 3. 对excel进行操作:
- 获取excel的总行数、总列数、读取excel每一行的数据、读取excel每一列的数据、获取某个单元格的值
- '''
- #打开excel,打开的excel必须存在,返回book对象
- book = xlrd.open_workbook('students.xlsx')
- #通过索引获取sheet对象
- sheet = book.sheet_by_index(0)
- #有多个sheet页时可以通过sheet的名称来获取sheet对象
- sheet1 = book.sheet_by_name('Sheet1')
- #获取excel的总行数,
- rows = sheet.nrows
- #获取excel的总列数
- cols = sheet.ncols
- #获取excel第2行的数据,返回结果为list:[2.0, 'b', 'women']
- row_value = sheet.row_values(2)
- #获取excel第1列的数据,返回结果为list:['name', 'a', 'b', 'c', 'd', 'e', 'f', 'g', '小白', '小黑']
- col_values = sheet.col_values(1)
- #获取单元格第8行第1列的数据,返回结果为text: text:'小白'
- cell_value = sheet.cell(8, 1)
- #将text类型的结果转换为str类型:小白
- cell_str = sheet.cell(8, 1).value
注意:获取每行、每列、某个单元格的值时,注意行、列的值要存在,否则会报错:list index out of range
excel - 读取excel小案例:
- import xlrd
- '''
- 读取excel的数据,读取数据的列固定,循环读取每行数据,读取后的数据格式如下:
- [
- {'name':xxx,'sex':xxx,'id':1},
- {'name':xxx,'sex':xxx,'id':1},
- .......
- ]
- '''
- def readExcel():
- try:
- #若输入的excel不存在,则打开excel报错
- book = xlrd.open_workbook('students.xlsx')
- except Exception as e:
- print('error msg:', e)
- else:
- sheet = book.sheet_by_index(0)
- #获取excel的总行数
- rows = sheet.nrows
- stu_list = []
- #循环读取每行数据,第0行是表头信息,所以从第1行读取数据
- for row in range(1, rows):
- stu = {}
- #获取第row行的第0列所有数据
- id = sheet.cell(row, 0).value
- name = sheet.cell(row, 1).value
- sex = sheet.cell(row, 2).value
- #将id、name、sex添加到字典,若元素不存在则新增,否则是更新操作
- stu['id'] = id
- stu['name'] = name
- stu['sex'] = sex
- stu_list.append(stu)
- print(stu_list)
- if __name__ == '__main__':
- readExcel()
excel数据格式如下:
excel - 写操作知识点:
- import xlwt
- '''
- 写 excel的操作步骤如下:
- 1. 打开excel,打开不存在的excel,若打开已存在的excel,进行写操作,写入的数据会覆盖以前的数据
- 2. 获取sheet对象并指定sheet的名称
- 3. 对excel进行操作:
- 写入excel、保存excel
- '''
- #打开excel创建book对象
- book = xlwt.Workbook()
- #创建sheet指定sheet名称
- sheet = book.add_sheet('stu2')
- #写入excel数据,第n行第n列写入某个值,写入的数据类型为str
- sheet.write(0, 0, '编号')
- sheet.write(0, 1, '姓名')
- sheet.write(0, 2, '年龄')
- #保存excel,保存的后缀必须是xls
- book.save('studet.xls')
excel写入 新的excel后,数据格式如下:
excel操作 已存在的excel,进行写操作后的 excel格式如下:
---->
excel - 写excel小案例:
- import xlwt
- '''
- 将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': '男'}]
- 写入excel,title信息为:编号、姓名、性别
- '''
- def writeExcel():
- book = xlwt.Workbook()
- sheet = book.add_sheet('stu')
- titles = ['编号', '姓名', '性别']
- #循环读取titles的长度,col的值为:0,1,2,并将title值写入excel
- for title_col in range(len(titles)):
- #title 写入excel的第0行的第col列,写入titles[col]值
- sheet.write(0, title_col, titles[title_col])
- 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': '男'}]
- for stu_row in range(len(students_list)):
- #循环读取student_list的长度,从0开始,写入excel时从第1行开始写入数据
- #写入excel的数据是从list里进行取值,获取list的每个元素,返回字典,然后通过字典的key获取value
- sheet.write(stu_row+1, 0, students_list[stu_row]['id'])
- sheet.write(stu_row+1, 1, students_list[stu_row]['name'])
- sheet.write(stu_row+1, 2, students_list[stu_row]['sex'])
- book.save('student.xls')
- if __name__ == '__main__':
- writeExcel()
excel数据格式如下:
excel- 更新操作知识点:
- import xlrd
- from xlutils.copy import copy
- '''
- 更新excel操作:
- 1. 打开excel,更新的excel必须存在
- 2. 复制一个新的excel,使用xlutils模块中的copy方法
- 3. 更新excel内的数据
- 4. 保存更新后的excel数据,以前的excel数据不会更改
- '''
- from xlutils.copy import copy
- #打开excel
- book = xlrd.open_workbook('student.xlsx')
- #复制一个新的excel
- new_book = copy(book)
- #查看某个对象下的所有方法
- #print(dir(new_book))
- #获取新excel的sheet对象
- sheet = new_book.get_sheet(0)
- #新增一列数据
- sheet.write(0, 3, '更新')
- #更新第4行第1列的值,将其修改为'郭静',修改的数据类型为str
- sheet.write(4, 1, '郭静')
- #保存更改后的excel,以前的excel数据不更改
- 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 插件效果:
python笔记8 - excel操作的更多相关文章
- python中的excel操作
一. Excel在python中的应用 存测试数据 有的时候大批量的数据,我们需要存到数据库中,在测试的时候才能用到.测试的时候就从数据库中读取出来.这点是非常重要的! 存测试结果 二. Excel中 ...
- python(读取excel操作-xlrd模块)
一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境. 或者在cmd窗口 pip install ...
- python(读取 excel 操作 xlrd 模块)
一.安装 xlrd 模块 到 python 官网下载 http://pypi.python.org/pypi/xlrd 模块安装,前提是已经安装了 python 环境. 或者在 cmd 窗口 pip ...
- python笔记01-----列表操作
在python中列表用 '[]' 表示 列表的查询操作 列表的切片 names = ["a","b","c"] #定 ...
- python笔记--5--文件操作
文件内容操作三部曲:打开.读写.关闭 open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, close ...
- python(写入excel操作-xlwt模块)
一.安装xlwt模块 pip install xlwt 二.excel写入操作 这种方式只能新增或者覆盖文件写入 import xlwt # 创建一个workbook 设置编码 workbook = ...
- python笔记006-文件操作
1文件操作... 1 1.1打开和关闭文件... 1 1.1.2 open函数... 1 1.2 文件 File对象的属性... 1 1.2.1 属性... 1 1.2.2 方法... 2 1.2.3 ...
- Python学习之==>Excel操作
一.简介 使用Python读.写.修改excel分别需要用到xlrd.xlwt以及xlutils模块,这几个模块使用pip安装即可. 二.读excel import xlrd book = xlrd. ...
- python(写入 excel 操作 xlwt 模块)
一.安装 xlwt 模块 pip install xlwt 二.excel 写入操作 这种方式只能新增或者覆盖文件写入 import xlwt # 创建一个workbook 设置编码 workbook ...
随机推荐
- jenkins+testNG
1.项目的pom.xml要配置插件,同时指定testng.xml文件的位置.就被这个卡了好久 <properties> <maven-surefire-plugin.version& ...
- 使用jsmin压缩javascript脚本
官方地址:http://www.crockford.com/javascript/jsmin.html 点击页下方的”zip file containing an MS-DOS.exe file“下载 ...
- ffmpeg相关资源
FFPLAY的原理(一) http://blog.csdn.net/shenbin1430/article/details/4291893 ubuntu12.04下命令安装ffplay等: sudo ...
- Odoo环境下Ubuntu服务器性能优化--参数调整
公司在使用Odoo进行内部信息化管理,随着业务增长,服务器性能问题变成了瓶颈,为了解决这些问题,最近的工作重点将移到性能调整上来,同时也会在此记录整个处理过程,以便日后回顾. 1.根据相关资料建议,在 ...
- 萌新学习Python爬取B站弹幕+R语言分词demo说明
代码地址如下:http://www.demodashi.com/demo/11578.html 一.写在前面 之前在简书首页看到了Python爬虫的介绍,于是就想着爬取B站弹幕并绘制词云,因此有了这样 ...
- 阿里云云盘扩容数据盘_Linux
随着业务的增长,您的数据盘容量可能无法满足数据存储的需要,这时您可以使用 磁盘扩容 功能扩容数据盘. 说明 挂载在实例上的数据盘,只有当实例处于 运行中 (Running) 或 已停止(Stopp ...
- sphinx设置多属性过滤的方法(setFilter)
需求描述 mysql中,每一个文档都有多个标签,查询时可以筛选一个标签也可以筛选同时拥有多个标签的文档. 数据示例 文档 标签 1 1,2,3,4,5 2 2,3,4,5,6 ...
- jBoss修改端口号
http://blog.csdn.net/ghost_t/article/details/5708991 jBoss版本: jboss-5.1.0.GA jboss-6.0.0.Final j ...
- js中加入数据缓存
因为我们的系统设计 所有的数据查询全部是采用参数化json 后台解析后进行数据返回 由于使用统一的数据查询入口 所有可以很方便的为数据设置缓存 var ModelDataCache = new Arr ...
- instanceof 与typeof的用法
通常来讲,使用 instanceof 就是判断一个实例是否属于某种类型.例如: var oStringObject = new String("hello world"); con ...