Python操作Excel,主要用到xlrd和xlwt這兩個庫,即xlrd是讀Excel,xlwt是寫Excel的庫
1、Python讀取Excel表格 ,使用xlrd庫
整體思路為,打開文件,選定表格,讀取行列內容,讀取表格內數據
1 import xlrd 2 import os 3 path = os.path.join(os.path.dirname(__file__),'data.xls') 4 print(path) 5 6 def readExcel(): 7 excel = xlrd.open_workbook(path) 8 excel.sheet_names() #獲取所有的表格名稱 9 sheet1 = excel.sheet_by_index(0) #通過索引獲取表格 10 sheet2 = excel.sheet_by_name("測試") #通過名字獲取表格 11 row = sheet1.row_values(1) #獲取某行的內容,列表形式返回 12 col = sheet1.col_values(0) #獲取某列的內容,列表形式返回 13 data1 = sheet1.cell(1,3).value #方法1,獲取表格里的具體內容 14 data2 = sheet1.cell_value(2,3) #方法2,獲取表格里的具體內容 15 data3 = sheet1.row(3)[3].value #方法3,獲取表格里的具體內容 16 print(row) 17 print(col) 18 print(data1) 19 print(data2) 20 print(data3) 21 22 if __name__ == '__main__': 23 readExcel()
當單元格的數據為日期格式時,普通獲取后顯示的是浮點數
Python讀取Excel中單元格的內容返回的有5種類型,即上面例子中的ctype:
ctype : 0 empty,1 string,2 number, 3 date,4 boolean,5 error
即date的ctype=3,這時需要使用xlrd的xldate_as_tuple來處理為date格式
1 import xlrd 2 import os 3 from datetime import date,datetime 4 path = os.path.join(os.path.dirname(__file__),'data.xls') 5 print(path) 6 7 def readExcel(): 8 excel = xlrd.open_workbook(path) 9 sheet1 = excel.sheet_by_index(0) #通過索引獲取表格 10 if sheet1.cell(1,4).ctype ==3: #獲取單元格的ctype是否為3 11 value = xlrd.xldate_as_tuple(sheet1.cell_value(1,4),excel.datemode) 12 print(value) 13 print(date(*value[:3])) 14 print(date(*value[:3]).strftime('%Y/%m/%d')) 15 else: 16 value = sheet1.cell_value(1,4) 17 print(value) 18 19 if __name__ == '__main__': 20 readExcel()
2、Python寫入Excel表格,使用xlwt庫,xlwt庫是一種”無則創建,有則建新”的覆蓋寫入方式,也就是只能是新建
1 import xlwt 2 3 #設置表格樣式 4 def set_style(name,height,bold=False): 5 style = xlwt.XFStyle() 6 font = xlwt.Font() 7 font.name = name 8 font.bold = bold 9 font.color_index = 4 10 font.height = height 11 style.font = font 12 return style 13 14 #寫Excel 15 def write_excel(): 16 f = xlwt.Workbook() 17 sheet1 = f.add_sheet('學生',cell_overwrite_ok=True) 18 row0 = ["姓名","年齡","出生日期","愛好"] 19 colum0 = ["張三","李四","戀習Python","小明","小紅","無名"] 20 #寫第一行 21 for i in range(0,len(row0)): 22 sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) 23 #寫第一列 24 for i in range(0,len(colum0)): 25 sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True)) 26 27 sheet1.write(1,2,'2006/12/12') 28 # sheet1.write_merge(6,6,1,3,'未知')#合並行單元格 29 # sheet1.write_merge(1,2,3,3,'打游戲')#合並列單元格 30 # sheet1.write_merge(4,5,3,3,'打籃球') 31 32 f.save('test.xls') 33 34 if __name__ == '__main__': 35 write_excel()
3、Python實現向Excel表格中填寫內容,那么就要用到xlutils庫,首先以“只讀”方式用xlrd打開頁面,再用xlutils.copy復制,再調用.write方法寫入內容。
1 import xlrd 2 import os 3 from xlutils.copy import copy 4 path = os.path.join(os.path.dirname(__file__),'data.xls') 5 print(path) 6 7 def addExcel(): 8 excel = xlrd.open_workbook(path,formatting_info=True) #formatting_info=True保留原有的數據格式 9 new_excel = copy(excel) 10 sheet = new_excel.get_sheet(0) # 通過索引獲取表格 11 sheet.write(3,4,'2019-8-28') 12 new_excel.save(path) 13 14 if __name__ == '__main__': 15 addExcel()