一、写excel
1 import xlwt
2 book = xlwt.Workbook()
3 sheet = book.add_sheet('sheet1')
4 #行
5 sheet.write(0,0,'名字')
6 sheet.write(0,1,'性别')
7 sheet.write(0,2,'手机号')
8 #列
9 sheet.write(1,0,'xmb')
10 sheet.write(1,1,'男')
11 sheet.write(1,2,'110')
12 book.save('students.xls')
13
14 #例子1:
15 stus = [
16 ['id', 'name', 'sex', 'age', 'addr', 'grade', 'phone', 'gold'],
17 [1, '小明', '男', 18, '北京', '一班', '18600000000', 144],
18 [2, '小兰', '女', 27, '上海', '二班', '18600000001', 100],
19 [3, '小花', '女', 18, '深圳', '三班', '18600000002', 100]
20 ]
21 row = 0
22 for stu in stus: #控制行
23 col = 0
24 for filed in stu: #控制列
25 sheet.write(row,col,filed)
26 col +=1
27 row +=1
28 book.save('students.xls')
29
30 #例子2
31 for row,stu,in enumerate(stus): #控制行
32 for col,filed in enumerate(stu) #控制列
33 sheet.write(row,col,filed)
34 book.save('students.xls')
二、读excel
1 import xlrd
2 book = xlrd.open_workbook('students.xls')
3 sheet = book.sheet_by_index(0)
4
5 result = sheet.cell(0,0).value #读取某个单元格的内容
6 print(result)
7
8 row = sheet.row_values(0) #读取整行的内容
9 print(row)
10
11 col = sheet.col_values(0) #读取整列的内容
12 print(col)
13
14 print(sheet.nrows) #计算总共多少行
15
16 print(sheet.ncols) #计算总共多少列
17
18 for row_num in range(0,sheet.nrows): #循环读出整个excel
19 print(sheet.row_values(row_num))