python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫可從這里下載https://pypi.python.org/pypi。下面分別記錄python讀和寫excel.
python讀excel——xlrd
import xlrd data = xlrd.open_workbook('host_list02.xlsx') # 獲取sheets數目: print (data.nsheets) # 獲取sheets列表: print(data.sheets()) # 獲取sheets name列表: print(data.sheet_names()) # #sheets返回一個sheet列表 sheet = data.sheets()[0] sheet = data.sheet_by_index(0) #通過索引順序獲取 sheet = data.sheet_by_name(u'Sheet1')#通過名稱獲取 # 第幾行的數據內容,索引是從0開始的 print(sheet.row_values(0)) # 第幾列的數據,這列所有的數據 print(sheet.col_values(3)) # 獲取列數 print(sheet.ncols) # 獲取行數 print(sheet.nrows) # 獲取名字 print(sheet.name) # 可以循環獲取行內容 for i in range(sheet.nrows): print(sheet.row_values(i))
現有一份表格文件:
其中sheet1 的內容是
sheet2 的內容是
寫python代碼操作表格:
def read_excel(): # 打開文件 workbook = xlrd.open_workbook(r'host_list02.xlsx') # 獲取所有的sheet的名字 print(workbook.sheet_names()) # 獲取第二個sheet的表名 sheet2_name = workbook.sheet_names()[1] # sheet1,索引是從0開始,得到sheet1表的句柄.用這個可以操作表 sheet1 = workbook.sheet_by_index(0) print(sheet1.cell(1, 0).value.encode('utf-8')) # 得到第一行,第一列的數據是二進制的數據 s = sheet1.cell(0, 0).value.encode('utf-8') # 1 ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error print(sheet1.cell(1,0).ctype) # 將二進制的數據轉換成utf-8編碼 print(s.decode('utf-8')) # 獲取整行和整列的數據 # 獲取第二行的數據 row2 = sheet1.row_values(1) # 獲取第二列的數據 cols2 = sheet1.col_values(1) sheet1 = workbook.sheet_by_index(0) # 循環得到sheet1表的內容 for i in range(sheet1.nrows): print(sheet1.row_values(i)) read_excel()
運行的結果:
['Sheet1', 'Sheet2', 'Sheet3'] b'10.127.0.2' 1 10.127.0.1 ['10.127.0.1', 'ceshi', 43466.0] ['10.127.0.2', 'ceshi', 43467.0] ['10.127.0.3', 'ceshi', 43468.0] ['10.127.0.4', 'ceshi', 43469.0] ['10.127.0.5', 'ceshi', 43470.0] ['10.127.0.6', 'ceshi', 43471.0] ['10.127.0.7', 'ceshi', 43472.0] ['10.127.0.8', 'ceshi', 43473.0] ['10.127.0.9', 'ceshi', 43474.0] ['10.127.0.10', 'ceshi', 43475.0] ['10.127.0.11', 'ceshi', 43476.0] ['10.127.0.12', 'ceshi', 43477.0] ['10.127.0.13', 'ceshi', 43478.0] ['10.127.0.14', 'ceshi', 43479.0] ['10.127.0.15', 'ceshi', 43480.0]
從上面的結果,我們可以看出,在操作時間類型的數據時,結果不是我們想要的
1、python讀取excel中單元格內容為日期的方式
python讀取excel中單元格的內容返回的有5種類型,即上面例子中的ctype:
1 ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
即date的ctype=3,這時需要使用xlrd的xldate_as_tuple來處理為date格式,先判斷表格的ctype=3時xldate才能開始操作。現在命令行看下:
代碼:
import xlrd import xlwt from datetime import date from datetime import datetime def read_excel(): # 打開文件 workbook = xlrd.open_workbook(r'host_list02.xlsx') # sheet1,索引是從0開始,得到sheet1表的句柄.用這個可以操作表 sheet1 = workbook.sheet_by_index(0) # 循環得到sheet1表的內容 for i in range(sheet1.nrows): for j in range(sheet1.ncols): # 當表格中的內容是date的時間類型是換成python的時間類型 if sheet1.cell(i,j).ctype == 3: d = xlrd.xldate_as_tuple(sheet1.cell_value(i, j), workbook.datemode) print(date(*d[:3]),end=' ') else: print(sheet1.cell(i,j).value,end=' ') print() read_excel()
結果:
10.127.0.1 ceshi 2019-01-01 10.127.0.2 ceshi 2019-01-02 10.127.0.3 ceshi 2019-01-03 10.127.0.4 ceshi 2019-01-04 10.127.0.5 ceshi 2019-01-05 10.127.0.6 ceshi 2019-01-06 10.127.0.7 ceshi 2019-01-07 10.127.0.8 ceshi 2019-01-08 10.127.0.9 ceshi 2019-01-09 10.127.0.10 ceshi 2019-01-10 10.127.0.11 ceshi 2019-01-11 10.127.0.12 ceshi 2019-01-12 10.127.0.13 ceshi 2019-01-13 10.127.0.14 ceshi 2019-01-14 10.127.0.15 ceshi 2019-01-15
那么問題又來了,print(sheet1.cell(2,2).value)是空,但這是合並后的單元格print(sheet1.cell(2,2).ctype)返回的值是0,說明這個單元格的值是空值,明明是合並的單元格內容"ceshi",這個是我覺得這個包功能不完善的地方,如果是合並的單元格那么應該合並的單元格的內容一樣,但是它只是合並的第一個單元格的有值,其它的為空。
2、讀取合並單元格的內容
這個是真沒技巧,只能獲取合並單元格的第一個cell的行列索引,才能讀到值,讀錯了就是空值。
即合並行單元格讀取行的第一個索引,合並列單元格讀取列的第一個索引,如上述,讀取行合並單元格"好朋友"和讀取列合並單元格"暫無"只能如下方式:
1、獲取合並的單元格
讀取文件的時候需要將formatting_info參數設置為True,默認是False,所以上面獲取合並的單元格數組為空,,早python當中,這個字段是False但可以通print(sheet1.merged_cells)查看是否有合並的單元格
def read_excel(): # 打開文件 workbook = xlrd.open_workbook(r'host_list02.xlsx') # sheet1,索引是從0開始,得到sheet1表的句柄.用這個可以操作表 sheet1 = workbook.sheet_by_index(0) # 獲取是否有合並的單元格,空是沒有,不為空是有 print(sheet1.merged_cells) read_excel()
結果:
[(14, 15, 1, 3), (8, 9, 1, 3), (9, 10, 1, 3), (10, 11, 1, 3), (11, 12, 1, 3), (12, 13, 1, 3), (13, 14, 1, 3), (0, 1, 1, 3), (1, 2, 1, 3), (2, 3, 1, 3), (3, 4, 1, 3), (4, 5, 1, 3), (5, 6, 1, 3), (6, 7, 1, 3), (7, 8, 1, 3)]
是說第二列到第三列合並,merged_cells返回的這四個參數的含義是:(row,row_range,col,col_range),其中[row,row_range)包括row,不包括row_range,col也是一樣
發現規律了沒?是的,獲取merge_cells返回的row和col低位的索引即可! 於是可以這樣一勞永逸:
1 >>> merge = [] 2 >>> for (rlow,rhigh,clow,chigh) in sheet1.merged_cells: 3 merge.append([rlow,clow]) 4 5 >>> merge 6 [[14,1], [8, 1], [9, 1]'......] 7 >>> for index in merge: 8 print sheet2.cell_value(index[0],index[1])
python寫excel——xlwt
def set_style(name,height,bold=False): # 初始化樣式 style = xlwt.XFStyle() font = xlwt.Font() # 創建字體 font.bold = bold font.color_index = 4 font.height = height font.name = name style.font = font return style def write_execl(): 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 sheet2 = f.add_sheet(u'sheet2',cell_overwrite_ok=True) #創建sheet2 row0 = [u'姓名',u'年齡',u'出生日期',u'愛好',u'關系'] column0 = [u'小傑',u'小胖',u'小明',u'大神',u'大仙',u'小敏',u'無名'] #生成第一行 for i in range(0,len(row0)): sheet2.write(0,i,row0[i],set_style('Times New Roman',220,True)) #生成第一列 for i in range(0,len(column0)): sheet2.write(i+1,0,column0[i],set_style('Times New Roman',220)) sheet2.write(1,2,'1991/11/11') sheet2.write_merge(7,7,2,4,u'暫無') #合並列單元格 sheet2.write_merge(1,2,4,4,u'好朋友') #合並行單元格 f.save('demo1.xls') write_execl()
需要稍作解釋的就是write_merge方法:
write_merge(x, x + m, y, w + n, string, sytle)
x表示行,y表示列,m表示跨行個數,n表示跨列個數,string表示要寫入的單元格內容,style表示單元格樣式。其中,x,y,w,h,都是以0開始計算的。
這個和xlrd中的讀合並單元格的不太一樣。
如上述:sheet1.write_merge(21,21,0,1,u'合計',set_style('Times New Roman',220,True))
即在22行合並第1,2列,合並后的單元格內容為"合計",並設置了style。
如果需要創建多個sheet,則只要f.add_sheet即可。
如在上述write_excel函數里f.save('demo1.xlsx')
效果: