excel的操作
Posted luonanhenniu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了excel的操作相关的知识,希望对你有一定的参考价值。
#############读excel
import xlrd
book = xlrd.open_workbook(‘stu.xls‘)#打开一个excel
sheet = book.sheet_by_index(0)#根据顺序获取sheet
#heet = book.sheet_by_name(‘sheet1‘)
print(sheet.cell(0,0).value)
print(sheet.ncols)#获取excel的行
print(sheet.nrows)#获取excel的列
# for i in sheet.get_rows():
# print(i)
for i in range(sheet.nrows):#0,1,2
print(sheet.row_values(i))#打印第几行的数据
for i in range(sheet.ncols):
print(sheet.col_values(i))
################################################
写excel
################################################
import xlwt#写
##############写excel
# book =xlwt.Workbook()#新建一个excel
# sheet = book.add_sheet(‘sheet1‘)
# print(dir(sheet))
# sheet.write(0,0,‘name‘)#第一行的第一列
# sheet.write(0,1,‘sex‘)#第一行的第二列
# sheet.write(0,2,‘age‘)#
# book.save(‘stu.xls‘)#写的时候只能用xls的格式 不能用xlsx
#ctrl+/ 多行注释
######################################################
# title=[‘name‘,‘sex‘,‘age‘,‘score‘]
# stus=[
# [‘luonan1‘,‘girl‘,‘12‘,100],
# [‘luonan2‘,‘girl‘,‘12‘,100],
# [‘luonan3‘,‘girl‘,‘12‘,100],
# [‘luonan4‘,‘girl‘,‘12‘,100],
# [‘luonan5‘,‘girl‘,‘12‘,100],
# ]
# book=xlwt.Workbook()
# sheet = book.add_sheet(‘sheet1‘)
# cols=0
# for t in title:
# sheet.write(0,cols,t)
# cols+=1
# raw=1
#
# for stu in stus:
# col = 0
# for s in stu:
# sheet.write(raw,col,s)
# col+=1
# raw+=1
# book.save(‘stu.xls‘)
#########################
stus=[
[‘name‘,‘sex‘,‘age‘,‘score‘],
[‘luonan1‘,‘girl‘,‘12‘,100],
[‘luonan2‘,‘girl‘,‘12‘,100],
[‘luonan3‘,‘girl‘,‘12‘,100],
[‘luonan4‘,‘girl‘,‘12‘,100],
[‘luonan5‘,‘girl‘,‘12‘,100],
]
book=xlwt.Workbook()
sheet=book.add_sheet(‘sheet1‘)
raw=0
for stu in stus:
col=0
for s in stu:
sheet.write(raw,col,s)
col+=1
raw+=1
book.save(‘stt.xls‘)
##########################
修改excel
###########################
import xlrd
from xlutils.copy import copy
book1 = xlrd.open_workbook(‘stu.xls‘)
book2 = copy(book1)#拷贝原来一份excel
sheet = book2.get_sheet(0)#获取第n个sheet页
sheet.write(1,3,0)
book2.save(‘stu_new.xls‘)
以上是关于excel的操作的主要内容,如果未能解决你的问题,请参考以下文章