標籤:python excel import 微軟 下載安裝
xlrd是專門用來在python中讀取微軟execel的模組,可以自己直接下載安裝,也可以通過包管理器安裝。組件的官網地址:http://www.python-excel.org/
基本操作:
#-*-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)
heet = 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‘) ##該檔案名稱必須存在
python操作excel之xlrd