1.1寫excel,通過循環把一個列表的數據寫到excel中,需要定義行和列
import xlwt book=xlwt.Workbook() sheet=book.add_sheet('sheet1') stus = [ ['id', 'name', 'sex', 'age', 'addr', 'grade', 'phone', 'gold'], [314, '礦泉水', '男', 18, '北京市昌平區', '摩羯座', '18317155663', 14405], [315, '礦泉水', '女', 27, '上海', '摩羯座', '18317155664', 100], [5985, '礦泉水', '男', 18, '北京市昌平區', '班級', '18513867663', 100] ] # 需要定義行和列 row = 0#行號 for stu in stus:#控制行 col = 0#列號 for field in stu:#控制列的 sheet.write(row,col,field) col+=1 # row+=1
1.2寫excel,通過循環把一個表的數據寫到excel中,不需要循環
import xlwt book=xlwt.Workbook() sheet=book.add_sheet('sheet1') stus = [ ['id', 'name', 'sex', 'age', 'addr', 'grade', 'phone', 'gold'], [314, '礦泉水', '男', 18, '北京市昌平區', '摩羯座', '18317155663', 14405], [315, '礦泉水', '女', 27, '上海', '摩羯座', '18317155664', 100], [5985, '礦泉水', '男', 18, '北京市昌平區', '班級', '18513867663', 100] ] #不需要定義行和列,使用enumerate內置函數,行和列自動加一 for row ,stu in enumerate(stus):#控制行 for col,field in enumerate(stu):#控制列 sheet.write(row,col,field) book.save('students.xls')
2.讀取excel的基本方法
import xlrd book=xlrd.open_workbook('students.xls')#打開文件 sheet=book.sheet_by_index(0)#根據下標找文件 # sheet=book.sheet_by_name('sheet1')#根據文件名找文件 result=sheet.cell(0,0).value#查找某個單元格的內容 print(result) row=sheet.row(1)#查找某行的內容 print(row) col=sheet.col(2)#查找某列的內容 print(col) print(sheet.nrows)#總共行數 print(sheet.ncols)#總共列數 for row_num in range(1,sheet.nrows):#循環行,得到所有行的內容 print(sheet.row_values(row_num))