1. 程式人生 > >【python】讀寫excel

【python】讀寫excel

轉載:http://blog.csdn.net/majordong100/article/details/50708365

學習Python的過程中,我們會遇到Excel的讀寫問題。通過搜尋得知,我們可以使用xlwt module將資料寫入Excel表格,使用xlrd module從Excel讀取資料。下面介紹如何實現使用Python對Excel進行讀寫操作。


Python版本:2.7.11

通過pip安裝xlwt, xlrd這兩個模組,如果沒有安裝的話:

pip install xlwt

pip insall xlrd


對Excel檔案進行寫入操作:

[python]  view plain  copy
  1. # -*- coding: UTF-8 -*-  
  2. # How to write to an Excel using xlwt module  
  3. import xlwt  
  4. # 建立一個Workbook物件,這就相當於建立了一個Excel檔案
      
  5. book = xlwt.Workbook(encoding='utf-8', style_compression=0)  
  6.   
  7. # 建立一個sheet物件,一個sheet物件對應Excel檔案中的一張表格。  
  8. # 在電腦桌面右鍵新建一個Excel檔案,其中就包含sheet1,sheet2,sheet3三張表  
  9. sheet = book.add_sheet('aa', cell_overwrite_ok=
    True)    # 其中的aa是這張表的名字  
  10.   
  11. # 向表aa中新增資料  
  12. sheet.write(00'EnglishName')    # 其中的'0, 0'指定表中的單元,'EnglishName'是向該單元寫入的內容  
  13. sheet.write(10'Marcovaldo')  
  14. txt1 = '中文名字'  
  15. sheet.write(01, txt1.decode('utf-8')) # 此處需要將中文字串解碼成unicode碼,否則會報錯  
  16. txt2 = '馬可瓦多'  
  17. sheet.write(11, txt2.decode('utf-8'))  
  18.   
  19. # 最後,將以上操作儲存到指定的Excel檔案中  
  20. book.save(r'e:\try1.xls'#在字串前加r,宣告為raw字串,這樣就不會處理其中的轉義了。否則,可能會報錯  


對Excel檔案進行讀取操作:

[python]  view plain  copy
  1. # -*- coding: UTF-8 -*-  
  2. # How to read from an Excel using xlrd module  
  3. import xlrd  
  4. # 開啟指定路徑中的xls檔案  
  5. xlsfile = r'e:\try1.xls'  
  6. book = xlrd.open_workbook(xlsfile)  # 得到Excel檔案的book物件  
  7.   
  8. # 得到sheet物件  
  9. sheet0 = book.sheet_by_index(0)     # 通過sheet索引獲得sheet物件  
  10. sheet_name = book.sheet_names()[0]  # 獲得指定索引的sheet名字  
  11. print sheet_name  
  12. sheet1 = book.sheet_by_name(sheet_name)     # 通過sheet名字來獲取,當然如果知道sheet名字就可以直接指定  
  13.   
  14. # 獲得行數和列數  
  15. nrows = sheet0.nrows    # 行總數  
  16. ncols = sheet0.ncols    # 列總數  
  17.   
  18. # 獲得指定行、列的值,返回物件為一個值列表  
  19. row_data = sheet0.row_values(0)     # 獲得第1行的資料列表  
  20. print row_data  
  21. col_data = sheet0.col_values(0)     # 獲得第1列的資料列表  
  22.   
  23. # 通過座標讀取表格中的資料  
  24. cell_value1 = sheet0.cell_value(00)  
  25. print cell_value1  
  26. cell_value2 = sheet0.cell_value(01)  
  27. print cell_value2