pengzhuopeng

安装

pip install xlwt

pip install xlrd

写Excel

import xlwt
book = xlwt.Workbook() #新建一个excel
sheet = book.add_sheet(\'sheet1\')    #加sheet页
sheet.write(0,0,\'姓名\')   #行,列,写入的内容
sheet.write(0,1,\'年龄\')
sheet.write(row,column,\'内容\')

book.save(\'stu.xls\')    #结尾一定要用.xls,否则打不开

读Excel

import xlrd
book = xlrd.open_workbook(\'app_student.xls\')
sheet = book.sheet_by_index(0)
sheet = book.sheet_by_name(\'app_student.xls\')
print(sheet.cell(0,0).value)  #指定sheet页里面的行和列获取数据
print(sheet.cell(1,0).value)  #指定sheet页里面的行和列获取数据
res = sheet.row_values(0)  #获取第1行的内容,放到列表中
print(sheet.row_values(0))  #获取第1行的内容,放到列表中
print(sheet.row_values(1))  #获取第2行的内容,放到列表中
print(sheet.nrows)  #获取excel中的所有行数
for i in range(sheet.nrows):    #循环获取excel中每一行内容
    print(sheet.row_values(i))

print(sheet.ncols)  #获取excel表的列数
print(sheet.col_values(0))  #获取第一列的数据。

修改Excel

import xlrd
from xlutils import copy
book = xlrd.open_workbook(\'app_student.xls\')
#先用xlrd模块,打开一个excel
new_book = copy.copy(book)
#通过xlutils模块里面的copy方法,复制一份excel
sheet = new_book.get_sheet(0)   #xlutils中的方法,获取sheet页
# sheet.write(0,0,\'编号\')
# sheet.write(0,1,\'名字\')
lis = [\'编号\',\'名字\',\'性别\',\'年龄\',\'地址\',\'班级\',\'手机号\',\'金币\']
for index,col in enumerate(lis):    #把第一行的表头按上面的lis顺序修改excel表
    sheet.write(0,index,col)
# new_book.save(\'app_student1.xls\')
new_book.save(\'app_student.xls\')

  

 

 
 
 
 
 

分类:

技术点:

相关文章: