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))#获取所有的列的数据

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM