python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫
xlwt缺點,無法復制Excel格式
xlutils 可以復制Excel格式
一、安裝第三方庫
pip install xlrd
pip install xlwt
pip install xlutils
二、第三方庫的使用
1、xlrd 讀Excel
import xlrd book=xlrd.open_workbook("demo2.xls") sheet1=book.sheet_by_index(0) #通過索引取TAB,且返回的是對象 #sheet1=book.sheet_by_name('sheet1')#通過名字取TAB,且返回的是對象 print(sheet1.row_values(1)) #取某一行的數據 print(sheet1.col_values(0)) #取某一列的數據 print(sheet1.cell_value(0,0)) #取某一單元格內容 print(sheet1.cell(0,0).value) #取某一單元格內容 print(sheet1.col_values(1,0,6)) #取從第一列的第0行到第6行的數據,不包含第6行 print(sheet1.name) #取TAB名稱 print(sheet1.nrows) #取共多少行 print(sheet1.ncols) #取共多少列 print(sheet1.number) #取TAB的index print(sheet1.row_len(0)) #每行的長度
2、xlwt 寫Excel
import xlwt book=xlwt.Workbook() #聲明對象 sheet=book.add_sheet('標簽1') #添加TAB簽 list=["姓名","年齡","性別","班級"] #表頭數據 x,y=0,0 for i in list: sheet.write(x,y,i) #遍歷寫表頭 y+=1 book.save("b.xls") #保存的時候,如果你用的是微軟的Office,后綴就用.xls #如果是wps .xls,.xlsx

3、xlutils 復制修改
修改的思路是:打開----復制----修改
import xlrd from xlutils import copy book=xlrd.open_workbook("book.xls") #打開文件 newbook=copy.copy(book) #復制文件 sheet=newbook.get_sheet(0) #獲取表TAB list=["姓名","年齡","性別","班級"] for col,t in enumerate(list): #枚舉方式遍歷寫表頭 sheet.write(0,col,t) newbook.save("book.xls")

4、寫復雜的EXCEL,涉及合並單元格
write_merge 這個方法可以合並單元格,write_merge(row,row+n,col,col+n,value)參數含義
import xlwt def set_style(name,height,bold=False): style=xlwt.XFStyle() font=xlwt.Font() font.name=name font.bold=bold font.colour_index=4 font.height=height style.font=font return style def write_excel(): f=xlwt.Workbook() sheet1=f.add_sheet(u'sheet1',cell_overwrite_ok=True) row0=[u'業務',u'狀態',u'北京',u'上海',u'廣州',u'深圳',u'狀態小計',u'合計'] column0 = [u'機票', u'船票', u'火車票', u'汽車票', u'其它'] status = [u'預訂', u'出票', u'退票', u'業務小計'] for i in range(0,len(row0)): sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) i,j=1,0 while i<4*len(column0) and j<len(column0): sheet1.write_merge(i,i+3,0,0,column0[j],set_style('Arial',220,True)) sheet1.write_merge(i,i+3,7,7) i+=4 j+=1 sheet1.write_merge(21,21,0,1,u'合計',set_style('Times New Roman',220,True)) i=0 while i<4*len(column0): for j in range(0,len(status)): sheet1.write(j+i+1,1,status[j]) i+=4 f.save('demo1.xlsx') if __name__=='__main__': write_excel()

