使用以前先導入三個模塊:spa
import xlwt #只能寫Excel import xlrd #只能讀Excel import xlutils #修改Excel,在原來的基礎上修改
1、寫EXCELcode
book=xlwt.Workbook() #新建一個Excel sheet=book.add_sheet('sheet1')#建一個sheet頁 sheet.write(0,0,'id')#指定行和列,寫內容 sheet.write(0,1,'username') sheet.write(0,2,'password') sheet.write(1,0,'1') sheet.write(1,1,'xiaoming') sheet.write(1,2,'123456') book.save('stu.xls')#保存內容 #注意:要保存成結尾時.xls的文件,.xlsx用微軟的文件打不開,只能用WPS的打開
使用循環方式寫入內容:blog
#給定文件內容: stus=[ [1,'njf','1234'], [2,'xiaojun','1234'], [3,'hailong','1234'], [4,'xiaohei','1234'], [5,'xiaohei','1234'], [6,'xiaohei','1234'], [7,'xiaohei','1234'], [8,'xiaohei','1234'], [9,'xiaohei','1234'], ] #內容寫入Excel book=xlrt.Workbook() #新建一個Excel sheet=book.add_sheet('sheet1') #新建一個sheet頁 line=0 #控制的是行 for stu in stus: col=0 #控制列 for s in stu: sheet.write(line,col,s) col+=1 line+=1 book.save('stu.xls') #保存內容
2、讀EXCELget
import xlrd book=xlrd.open_workbook('stu.xls') #打開Excel sheet=book.sheet_by_index(0) #根據編號獲取sheet頁 #sheet=book.sheet_by_name('sheet1') #也能夠根據sheet頁名字獲取sheet頁 print(sheet.nrows) #Excel裏有多少行 print(sheet.ncols) #Excel裏有多少列 print(sheet.cell(0,0).value) #獲取到指定單元格的內容 print(sheet.cell(0,1).value) #獲取到指定單元格的內容 print(sheet.row_values(0)) #獲取到整行的內容 print(sheet.col_values(0)) #獲取到整列的內容 for i in range(sheet.nrows): #循環獲取每行的內容 print(sheet.row_values(i))
3、修改EXCELit
因爲xlwt模塊只能寫一次,再從新打開Excel後會覆蓋原來的內容;而xlrd模塊只能讀,所以修改Excel就要使用xlutils模塊了。class
#import xlutils import xlrd #兩個模塊配合使用 from xlutils import copy book=xlrd.open_workbook('stu.xls') #先用xlrd打開一個Excel new_book=copy.copy(book) #而後用xlutils裏面的copy功能,複製一個Excel sheet=new_book.get_sheet(0) #獲取sheet頁,注意這裏的sheet頁是xlutils裏的,只能用.get_sheet()的方法獲取了 sheet.write(0,1,'小明') new_book.save('stu.xls') #修改完內容後再保存成同名的Excel