Python基于xlrd模块操作Excel的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python操作Excel表格技巧总结》、《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python3 能振兴 Python的原因分析

我从Stephen A. Goss那读到关于了《Python 3正在毁灭Python》。这篇文章有不少精彩的论点,但我却并不认为Python 3是在毁灭Python,也不认为整个局面对P...

pytorch程序异常后删除占用的显存操作

1-删除模型变量 del model_define 2-清空CUDA cache torch.cuda.empty_cache() 3-步骤2(异步)需要一定时间,设置时延...

python 字典(dict)按键和值排序

python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行: 1 下面的是按照value的值从大到...

python读写ini配置文件方法实例分析

本文实例讲述了python读写ini配置文件方法。分享给大家供大家参考。具体实现方法如下: import ConfigParser import os class ReadWrite...

Python中AND、OR的一个使用小技巧

python中的and-or可以用来当作c用的?:用法。比如 1 and a or b,但是需要确保a为True,否则a为False,还要继续判断b的值,最后打印b的值。 今天看到一个好...