读写excel表

安装xlwt、xlrd、xlutils

引入xlwt、xlrd、xlutils.copy文件的copy模块

#写入

writebook = xlwt.Workbook()    #打开excel
test= writebook.add_sheet('test')  #添加一个名字叫test的sheet
# test= writebook.add_sheet('test02')  #在添加一个名字叫test的sheet
test.write(0,4,'this is a test') #第1行第3列写入字符串'this is a test'
writebook.save('/Users/chenmeiru/Desktop/test_script/testdata.xls) #一定要保存为xls,后缀是xlsx的文件打不开

 

#读取

data=xlrd.open_workbook('/Users/chenmeiru/Desktop/test_script/testdata.xls')  #打开excel
data.sheet_names()   #获取所有sheet名字
table=data.sheet_by_index(0)  #获取第一个sheet表
tager=table.cell_value(0,4) #指定单元格的数据,或者指定行列用 table.row_values() 、table.col_values()

 

#追加

r_xls = xlrd.open_workbook('/Users/chenmeiru/Desktop/test_script/testdata.xls') # 读取excel文件
row = r_xls.sheets()[0].nrows # 获取已有数据的行数
excel = copy(r_xls) # 将xlrd的对象转化为xlwt的对象
table = excel.get_sheet(0) # 获取要操作的sheet
#对excel表追加一行内容
table.write(0, 4, u'内容1') #括号内分别第一行的第五列写入内容

excel.save(Excel.filea) # 保存并覆盖文件

 

 

posted @ 2021-04-30 23:33  amim  阅读(45)  评论(0编辑  收藏  举报