#读取xlsx文件内容
#create an empty list to store rows
book = xlrd.open_workbook('表.xls') #open the Excel spreadsheet as workbook
# 以列表形式返回所有的表名称
table_names = book.sheet_names()
print('sheet表名称:%s' % table_names)
# 按照索引,读取指定的表对象sheet
sheet = book.sheet_by_index(0) #get the first sheet
# 获取表名称
name = sheet.name
print('sheet表的名称:%s'% name)
# 获取表的总行数
rows = sheet.nrows
print('表的总行数:%s' % rows)
# 获取表的总列数
cols = sheet.ncols
print('表的总列数:%s' % cols)
# 读取表数据,以列表形式返回表数据,每个列表里的数据就是excel的每一行的数据
for i in range(rows):
print('第%s行的数据是:%s' % (i,sheet.row_values(i)))
# print(sheet.row_values(0)) # 表头
# 返回一列内容
cols_data = sheet.col_values(0)
print('返回这一列的内容是:%s' % cols_data)
# 返回某一单元格内容, 类似于坐标定位
single_data1 = sheet.cell_value(0, 0)
single_data2 = sheet.cell_value(1, 1)
print(single_data1)
print(single_data2)
# for user in range(sheet.nrows): #iterate 1 to maxrows
# print(list(sheet.row_values(user, 0, sheet.ncols))) #iterate through the sheet and get data from rows in list
#
# #写入xls文件
# rows1 = [['Name', 'Age'],['fengju', '26'],['wuxia', '25']]
# book1 = xlwt.Workbook() #create new book1 excle
# sheet1 = book1.add_sheet('user') #create new sheet
# for i in range(0, 3):
# for j in range(0, len(rows1[i])):
# sheet1.write(i, j, rows1[i][j])
# book1.save('testdata1.xls') #sava as testdata1.xlsimport xlrd, xlwt #xlwt只能写入xls文件
xlrd、xlwt的简单使用
最新推荐文章于 2022-09-22 15:31:46 发布