Python基于xlrd模块操作Excel的方法示例
作者:breezey 时间:2021-07-18 16:04:06
本文实例讲述了Python基于xlrd模块操作Excel的方法。分享给大家供大家参考,具体如下:
一、使用xlrd读取excel
1、xlrd的安装:
pip install xlrd==0.9.4
2、基本操作示例:
#coding: utf-8
import xlrd #导入xlrd模块
xlsfile=r"D:\workspace\host.xls"
#获得excel的book对象
book = xlrd.open_workbook(filename=None, file_contents=xlsfile.read())
#也可以直接写成如下:
book = xlrd.open_workbook(xlsfile)
#获取sheet对象,有两种方法:
sheet_name = book.sheet_names()[0] #获取指定索引的sheet的名字
print sheet_name
sheet1 = book.sheet_by_name(sheet_name) #通过sheet名字来获取sheet对象
sheet0 = book.sheet_by_index(0) #通过sheet索引获取sheet对象
#获取行数和列数:
nrows = sheet.nrows #总行数
ncols = sheet.ncols #总列数
#获得指定行、列的值,返回对象为一个值列表:
row_data = sheet.row_values(0) #获得第1行的数据列表
col_data = sheet.col_values(0) #获得第1列的数据列表
#通过cell的位置坐标获取指定cell的值:
cell_value1 = sheet.cell_value(0,1) #只获取cell中的内容,如:http://xx.xxx.xx
print cell_value1
cell_value2 = sheet.cell_value(0,1) #除了cell的内容,还有附加属性,如:text:u'http://xx.xxx.xx'
print cell_value2
二、使用xlwt模块写excel
1、安装:
pip install xlwt
2、基本操作:
#coding: utf-8
import xlwt
#创建一个wbk的对象,使用utf-8编码,并设定压缩比
wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)
#添加一个sheet对象
sheet = wbk.add_sheet('sheet 1',cell_overwrite_ok=True) #第二个参数用于确认同一个cell单元是否可以重设值
sheet.write(0,0,'sometext') #往指定单元格写入数据
sheet.write(0,0,'overwrite') #覆盖写入,需要cell_overwrite_ok=True
#设定单元格风格,指定字体格式等
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True
style.font = font
sheet.write(0,1,'text', style)
wbk.save('D:\test.xls') #该文件名必须存在
希望本文所述对大家Python程序设计有所帮助。
来源:https://www.cnblogs.com/breezey/p/6663525.html
标签:Python,xlrd模块,Excel
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Go语言 go程释放操作(退出/销毁)
2023-09-17 22:03:42
![](https://img.aspxhome.com/file/2023/3/90483_0s.png)
Python微信企业号开发之回调模式接收微信端客户端发送消息及被动返回消息示例
2023-09-20 13:29:27
针对google Chrome的 CSS hacks
2009-11-30 12:45:00
SQL 查询性能优化 解决书签查找
2012-10-07 10:23:56
使用Python实现控制摄像头的方法详解
2023-01-15 14:38:12
pandas的apply函数用法详解
2022-05-09 11:41:16
Python之修改图片像素值的方法
2022-03-14 03:46:18
ASP 根据用户权限判断显示的列标题
2011-03-29 11:01:00
TensorFlow安装及jupyter notebook配置方法
2022-09-11 01:05:23
一文秒懂pandas中iloc()函数
2023-07-31 18:20:42
![](https://img.aspxhome.com/file/2023/9/76149_0s.png)
Oracle数据库性能优化技术开发者网络Oracle
2010-07-18 13:05:00
PyTorch搭建CNN实现风速预测
2022-09-11 17:40:19
![](https://img.aspxhome.com/file/2023/8/102328_0s.jpg)
使用实例管理器轻松管理多个MySQL实例
2009-03-25 17:07:00
Python实现数据可视化案例分析
2022-09-07 17:58:38
![](https://img.aspxhome.com/file/2023/2/90882_0s.png)
python 基于Apscheduler实现定时任务
2022-03-29 00:53:32
百分百弹窗
2013-08-07 07:41:06
PyTorch 迁移学习实践(几分钟即可训练好自己的模型)
2021-09-07 23:37:31
![](https://img.aspxhome.com/file/2023/2/75182_0s.png)
正则表达式简介
2007-08-12 18:01:00
ORACLE11g随RHEL5系统自动启动与关闭的设置方法
2009-08-31 12:43:00
用Python删除本地目录下某一时间点之前创建的所有文件的实例
2021-07-29 05:34:59