python操作excel之xlrd

xlrd是專門用來在python中讀取微軟execel的模塊,可以自己直接下載安裝,也可以通過包管理器安裝。


官方資料:

下載地址:http://pypi.python.org/pypi/xlrd

官網地址:http://www.python-excel.org/

文檔地址:https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html

文檔pdf下載:http://www.simplistix.co.uk/presentations/python-excel.pdf


基本操作:

[python] view plaincopy
  1. # encoding : utf-8       #設置編碼方式  
  2.   
  3. import xlrd                    #導入xlrd模塊  
  4.   
  5. #打開指定文件路徑的excel文件  
  6.   
  7. xlsfile = r'D:\AutoPlan\apisnew.xls'   
  8. book = xlrd.open_workbook(xlsfile)     #獲得excel的book對象  
  9.   
  10. #獲取sheet對象,方法有2種:  
  11. sheet_name=book.sheet_names()[0]          #獲得指定索引的sheet名字  
  12. print sheet_name  
  13. sheet1=book.sheet_by_name(sheet_name)  #通過sheet名字來獲取,當然如果你知道sheet名字了可以直接指定  
  14. sheet0=book.sheet_by_index(0)     #通過sheet索引獲得sheet對象  
  15.   
  16. #獲取行數和列數:  
  17.   
  18. nrows = sheet.nrows    #行總數  
  19. ncols = sheet.ncols   #列總數  
  20.   
  21. #獲得指定行、列的值,返回對象爲一個值列表  
  22.   
  23. row_data = sheet.row_values(0)   #獲得第1行的數據列表  
  24. col_data = sheet.col_values(0)  #獲得第一列的數據列表,然後就可以迭代裏面的數據了  
  25.   
  26. #通過cell的位置座標獲得指定cell的值  
  27. cell_value1 = sheet.cell_value(0,1)  ##只有cell的值內容,如:http://xxx.xxx.xxx.xxx:8850/2/photos/square/  
  28. print cell_value1  
  29. cell_value2 = sheet.cell(0,1##除了cell值內容外還有附加屬性,如:text:u'http://xxx.xxx.xxx.xxx:8850/2/photos/square/'  
  30. print cell_value2  

是不是很方便啊,恩,比用vbs調用的excel COM對象簡便多了。而且這個支持linux平臺。


=====================================xls的寫方法使用xlwt模塊===================================================

[python] view plaincopy
  1. #encoding:utf-8       #設置編碼方式    
  2.     
  3. import xlwt  
  4. wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)  
  5. sheet = wbk.add_sheet('sheet 1', cell_overwrite_ok=True)  ##第二參數用於確認同一個cell單元是否可以重設值。  
  6.   
  7. sheet.write(0,0,'some text')  
  8. sheet.write(0,0,'this should overwrite')   ##重新設置,需要cell_overwrite_ok=True  
  9.   
  10. style = xlwt.XFStyle()  
  11. font = xlwt.Font()  
  12. font.name = 'Times New Roman'  
  13. font.bold = True  
  14. style.font = font  
  15. sheet.write(01'some bold Times text', style)  
  16.   
  17. wbk.save('D:\TestData2.xls')    ##該文件名必須存在  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章