使用之前先導入三個模塊:
import xlwt #只能寫Excel import xlrd #只能讀Excel import xlutils #修改Excel,在原來的基礎上修改
一、寫EXCEL
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的打開
使用循環方式寫入內容:
#給定文件內容: 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') #保存內容
二、讀EXCEL
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))
三、修改EXCEL
由於xlwt模塊只能寫一次,再重新打開Excel后會覆蓋原來的內容;而xlrd模塊只能讀,因此修改Excel就要使用xlutils模塊了。
#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