python操作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')    #该文件名必须存在
复制代码

 

posted @   breezey  阅读(645)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示