1.数据插入表格
import xlwt
data_list = [
['张三','男','19'],
['李四','男','20'],
['王五','男','21'],
['麻刘','男','22']
]
wookbook = xlwt.Workbook(encoding="utf-8")
wooksheet = wookbook.add_sheet('testsheet')
#wooksheet.write(0, 0, 1) #写入数据,第一行参数"行",第二参数"列",第三个参数内容
#一般的数组都是二维或是三维数组,循环插入表格数据
for i in range(0,len(data_list)):
print(data_list[i])
for j in range(0,len(data_list[i])):
wooksheet.write(i,j,data_list[i][j])
wookbook.save('testsheet1.xls')
运行结果:
2.从表格中读取数据
import xlrd
workbook = xlrd.open_workbook('testsheet1.xls')
#sheet_name = workbook.sheet_names() # 获取所有sheet名称
sheet1 = workbook.sheet_by_index(0) #根据索引其获取表
#sheet1 = workbook.sheet_by_name('testsheet') #根据表名获取表
#print(sheet1.name,sheet1.nrows,sheet1.ncols) 表名,表的总行数,表的总列数
#rows = sheet1.row_values(0) 获取某行的数据
#cols = sheet1.col_values(0) 获取某列的数据
list = []
rows_num = sheet1.nrows
for i in range(rows_num): #将每行的数据组成数组
row_list = []
row_list = sheet1.row_values(i)
list.append(row_list)
print(list)
运行结果: