• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
bobo-tester
博客园    首页    新随笔    联系   管理    订阅  订阅

python操作excel、读写修改。

导入xlwt模块

第一、新建一个excel文件

 

1、新建一个excel
2、添加sheet页
3、写入内容
4、保存该excel

import xlwt


book = xlwt.Workbook()           #新建一个excel
sheet = book1.add_sheet('sheet1')#加sheet页
sheet.write(0,0,'姓名')          #行、列、写入的内容
sheet.write(0,1,'年龄')
sheet.write(0,2,'性别')
book.save('stu.xls')             #结尾一定要用.xls

 

第二 修改excel文件

 import xlutils,xlrd


from xlutils import copy

book = xlrd.open_workbook('app_student.xls')
#先用xlrd打开一个excel

new_book = copy.copy(book)

#通过xlutis先复制一个excel

sheet=new_book.get_sheet(0)#获取sheet页 get_sheet(0)是xlutils模块的方法。
# sheet.write(0,0,'编号')
# sheet.write(0,1,'名字')

lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
for col, filed in enumerate(lis):
    sheet.write(0, col, filed)

new_book.save('app_student.xls')#保存

enumerate(lis)

在循环的时候能同时得到lis的下标和元素 

在这里  col做为下标,filed做为元组来进行循环,然后得到结果在写入到excel中。

第三、读取excel文件

 

import xlrd

book= xlrd.open_workbook('app_student.xls')
sheet = book.sheet_by_index(0)
print(sheet.cell(0,0).value)#指定sheet里面的行和列
print(sheet.cell(1,0).value)
print(sheet.row_values(0)) #获取整行的数据
print(sheet.nrows)         #获取所有的行数

for i in range(sheet.nrows):
    print(sheet.row_values(i))#循环获取到每行的数据


print(sheet.ncols)#获取所有的列数
print(sheet.col_values(0)) #第一列的内容


for i in range(sheet.ncols):
    print(sheet.col_values(i))#获取所有的列的数据

 

posted @ 2018-05-07 13:30  bobo-tester  阅读(1951)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3