python excel读写

xlrd和xlwt

import xlrd,xlrd模块既可读取xls文件也可读取xlsx文件。

获取工作簿对象:book = xlrd.open_workbook('excel文件名称')

获取所有工作表名称:names = book.sheet_names(),结果为列表

根据索引获取工作表对象:sheet = book.sheet_by_index(i)

根据名称获取工作表对象:sheet = book.sheet_by_name('工作表名称')

获取工作表行数:rows = sheet.nrows

获取工作表列数:cols = sheet.ncols

获取工作表某一行的内容:row = sheet.row_values(i) ,结果为列表   【sheet.row(i),列表】

获取工作表某一列的内容:col = sheet.col_values(i)  结果为列表   【sheet.col(i),列表】

获取工作表某一单元格的内容:cell = sheet.cell_value(m,n)、 sheet.cell(m,n).value、sheet.row(m)[n].value,sheet.col(n)[m].value,结果为字符串或数值    【sheet.cell(0,0),xlrd.sheet.Cell对象】

示例:假设在py执行文件同层目录下有一fruit.xls文件,有三个sheet页Sheet1、Sheet2、Sheet3,其中Sheet1内容如下:

import xlrd
book = xlrd.open_workbook('fruit.xls')
print('sheet页名称:',book.sheet_names())
sheet = book.sheet_by_index(0)
rows = sheet.nrows
cols = sheet.ncols
print('该工作表有%d行,%d列.'%(rows,cols))
print('第三行内容为:',sheet.row_values(2))
print('第二列内容为%s,数据类型为%s.'%(sheet.col_values(1),type(sheet.col_values(1))))
print('第二列内容为%s,数据类型为%s.'%(sheet.col(1),type(sheet.col(1))))
print('第二行第二列的单元格内容为:',sheet.cell_value(1,1))
print('第三行第二列的单元格内容为:',sheet.cell(2,1).value)
print('第五行第三列的单元格内容为:',sheet.row(4)[2].value)
print('第五行第三列的单元格内容为%s,数据类型为%s'%(sheet.col(2)[4].value,type(sheet.col(2)[4].value)))
print('第五行第三列的单元格内容为%s,数据类型为%s'%(sheet.col(2)[4],type(sheet.col(2)[4])))

# 执行结果
# sheet页名称: ['Sheet1', 'Sheet2', 'Sheet3']
# 该工作表有5行,3列.
# 第三行内容为: ['梨', 3.5, 130.0]
# 第二列内容为['单价/元', 8.0, 3.5, 4.5, 3.8],数据类型为<class 'list'>.
# 第二列内容为[text:'单价/元', number:8.0, number:3.5, number:4.5, number:3.8],数据类型为<class 'list'>.
# 第二行第二列的单元格内容为: 8.0
# 第三行第二列的单元格内容为: 3.5
# 第五行第三列的单元格内容为: 300.0
# 第五行第三列的单元格内容为300.0,数据类型为<class 'float'>
# 第五行第三列的单元格内容为number:300.0,数据类型为<class 'xlrd.sheet.Cell'>

xlrd读取excel示例

2.xlwt写入excel文件

使用xlwt模块之前需要先导入import xlwt,xlwt模块只能写xls文件,不能写xlsx文件(写xlsx程序不会报错,但最后文件无法直接打开,会报错)。

创建工作簿:book = xlwt.Workbook(),如果写入中文为乱码,可添加参数encoding = 'utf-8'

创建工作表:sheet = book.add_sheet('Sheet1')

向单元格写入内容:sheet.write(m,n,'内容1')、sheet.write(x,y,'内容2')

保存工作簿:book.save('excel文件名称'),默认保存在py文件相同路径下,如果该路径下有相同文件,会被新创建的文件覆盖,即xlwt不能修改文件。

import xlwt
proj = ['名称','单价/元','库存/kg']
fruit = ['苹果','梨','香蕉','橘子']
price = [8,3.5,4.5,3.8]
storage = [150,130,100,300]
book = xlwt.Workbook()
sheet = book.add_sheet('Sheet1')
for i in range(0,len(proj)):
    sheet.write(0,i,proj[i]) #按行插入行标题
for i in range(0,len(fruit)):
    sheet.write(i+1,0,fruit[i])  #插入第一列水果名称
for i in range(0,len(price)):
    sheet.write(i+1,1,price[i])  #插入第二列单价
for i in range(0,len(storage)):
    sheet.write(i+1,2,storage[i])   #插入第三列库存
book.save('fruit2.xls')

xlwt逐行或列写入excel

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值