Python讀寫Excel表格


最近在做一些數據處理和計算的工作,因為數據是以.CSV格式保存的,因此剛開始直接用Excel來處理。

但是做着做着發現重復的勞動,其實並沒有多大的意義,於是就想着寫個小工具幫着處理。

以前正好在一本書上看到過,使用Python來處理Excel表格,可惜沒有仔細看。

於是我到處查找資料,基本解決了日常所需,終於算是完成了任務,因此撰寫此文就算是總結吧,主要記錄使用過程的常見問題及解決。

Python操作Excel,主要用到xlrd和xlwt這兩個庫,即xlrd是讀Excel,xlwt是寫Excel的庫。

可從這里下載https://pypi.python.org/pypi。下面分別記錄Python讀和寫Excel。

640?wx_fmt=png

  • Python寫Excel——xlwt

Python寫Excel的難點,不在構造一個Workbook的本身,而是填充的數據,不過這不在范圍內。

在寫Excel的操作中,也有棘手的問題,比如寫入合並的單元格,就是比較麻煩的,另外寫入還有不同的樣式。

詳細代碼如下:

 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,3,'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')if __name__ == '__main__':    write_excel()

 

 

結果圖:

640?wx_fmt=png

在此,對write_merge()的用法稍作解釋,如上述:sheet1.write_merge(1,2,3,3,'打游戲'),即在四列合並第2,3列,合並后的單元格內容為"合計",並設置了style。其中,里面所有的參數都是以0開始計算的。

640?wx_fmt=png

  • Python讀Excel——xlrd

Python讀取Excel表格,相比xlwt來說,xlrd提供的接口比較多,但過程也有幾個比較麻煩的問題,比如讀取日期、讀合並單元格內容。

下面先看看基本的操作:

640?wx_fmt=png

 

 

 

 

 

 

 

 

 

 

整體思路為,打開文件,選定表格,讀取行列內容,讀取表格內數據

詳細代碼如下:

 1 import xlrd
 2 from datetime import date,datetime
 3 
 4 file = 'test3.xlsx'
 5 
 6 def read_excel():
 7 
 8     wb = xlrd.open_workbook(filename=file)#打開文件
 9     print(wb.sheet_names())#獲取所有表格名字
10 
11     sheet1 = wb.sheet_by_index(0)#通過索引獲取表格
12     sheet2 = wb.sheet_by_name('年級')#通過名字獲取表格
13     print(sheet1,sheet2)
14     print(sheet1.name,sheet1.nrows,sheet1.ncols)
15 
16     rows = sheet1.row_values(2)#獲取行內容
17     cols = sheet1.col_values(3)#獲取列內容
18     print(rows)
19     print(cols)
20 
21     print(sheet1.cell(1,0).value)#獲取表格里的內容,三種方式
22     print(sheet1.cell_value(1,0))
23     print(sheet1.row(1)[0].value)

運行結果如下:

640?wx_fmt=png

那么問題來了,上面的運行結果中紅框框中的字段明明是出生日期,可顯示的確實浮點數;同時合並單元格里面應該是有內容的,結果不能為空。

別急,我們來一一解決這兩個問題:

1.Python讀取Excel中單元格內容為日期的方式

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格式,先判斷表格的ctype=3時xldate才能開始操作。

詳細代碼如下:

1 import xlrd
2 from datetime import date,datetime
3 
4 print(sheet1.cell(1,2).ctype)
5 date_value = xlrd.xldate_as_tuple(sheet1.cell_value(1,2),wb.datemode)
6 print(date_value)
7 print(date(*date_value[:3]))
8 print(date(*date_value[:3]).strftime('%Y/%m/%d'))

運行結果如下:

640?wx_fmt=png

2.獲取合並單元格的內容

在操作之前,先介紹一下merged_cells()用法,merged_cells返回的這四個參數的含義是:(row,row_range,col,col_range),其中[row,row_range)包括row,不包括row_range,col也是一樣,即(1, 3, 4, 5)的含義是:第1到2行(不包括3)合並,(7, 8, 2, 5)的含義是:第2到4列合並。

詳細代碼如下:

print(sheet1.merged_cells)
print(sheet1.cell_value(1,3))
print(sheet1.cell_value(4,3))
print(sheet1.cell_value(6,1))

運行結果如下:

640?wx_fmt=png

發現規律了沒?是的,獲取merge_cells返回的row和col低位的索引即可! 於是可以這樣批量獲取:

詳細代碼如下:

merge = []
print(sheet1.merged_cells)
for (rlow,rhigh,clow,chigh) in sheet1.merged_cells:
    merge.append([rlow,clow])
for index in merge:
    print(sheet1.cell_value(index[0],index[1]))

運行結果跟上圖一樣,如下:

640?wx_fmt=png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM