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
基本操作:
- # encoding : utf-8 #設置編碼方式
- import xlrd #導入xlrd模塊
- #打開指定文件路徑的excel文件
- xlsfile = r'D:\AutoPlan\apisnew.xls'
- book = xlrd.open_workbook(xlsfile) #獲得excel的book對象
- #獲取sheet對象,方法有2種:
- sheet_name=book.sheet_names()[0] #獲得指定索引的sheet名字
- print sheet_name
- sheet1=book.sheet_by_name(sheet_name) #通過sheet名字來獲取,當然如果你知道sheet名字了可以直接指定
- sheet0=book.sheet_by_index(0) #通過sheet索引獲得sheet對象
- #獲取行數和列數:
- nrows = sheet.nrows #行總數
- ncols = sheet.ncols #列總數
- #獲得指定行、列的值,返回對象爲一個值列表
- row_data = sheet.row_values(0) #獲得第1行的數據列表
- col_data = sheet.col_values(0) #獲得第一列的數據列表,然後就可以迭代裏面的數據了
- #通過cell的位置座標獲得指定cell的值
- cell_value1 = sheet.cell_value(0,1) ##只有cell的值內容,如:http://xxx.xxx.xxx.xxx:8850/2/photos/square/
- print cell_value1
- cell_value2 = sheet.cell(0,1) ##除了cell值內容外還有附加屬性,如:text:u'http://xxx.xxx.xxx.xxx:8850/2/photos/square/'
- print cell_value2
是不是很方便啊,恩,比用vbs調用的excel COM對象簡便多了。而且這個支持linux平臺。
=====================================xls的寫方法使用xlwt模塊===================================================
- #encoding:utf-8 #設置編碼方式
- import xlwt
- wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)
- sheet = wbk.add_sheet('sheet 1', cell_overwrite_ok=True) ##第二參數用於確認同一個cell單元是否可以重設值。
- sheet.write(0,0,'some text')
- sheet.write(0,0,'this should overwrite') ##重新設置,需要cell_overwrite_ok=True
- style = xlwt.XFStyle()
- font = xlwt.Font()
- font.name = 'Times New Roman'
- font.bold = True
- style.font = font
- sheet.write(0, 1, 'some bold Times text', style)
- wbk.save('D:\TestData2.xls') ##該文件名必須存在