1. 程式人生 > >python介面自動化--Excel

python介面自動化--Excel

1.操作步驟:


(1)安裝python官方Excel庫-->xlrd

(2)獲取Excel檔案位置並讀取

(3)讀取sheet

(4)讀取指定rows和cols內容

2.示例程式碼

# -*- coding: utf-8 -*-
import xlrd

from datetime import date,datetime

def read_excel():
    ExcelFile=xlrd.open_workbook(r'C:\Users\Administrator\Documents\autoTest\testexcel.xlsx')

#獲取目標EXCEL檔案sheet名 print (ExcelFile.sheet_names()) #------------------------------------ #若有多個sheet,則需要指定讀取目標sheet例如讀取sheet2 #sheet2_name=ExcelFile.sheet_names()[1] #------------------------------------ #獲取sheet內容【1.根據sheet索引2.根據sheet名稱】 #sheet=ExcelFile.sheet_by_index(1) sheet
=ExcelFile.sheet_by_name('Sheet1') #列印sheet的名稱,行數,列數 print("name===rows==cols") print(sheet.name,sheet.nrows,sheet.ncols) #獲取整行或者整列的值 rows=sheet.row_values(2)#第3行內容 cols=sheet.col_values(1)#第二列內容 print(cols,rows) #獲取單元格內容 print(sheet.cell(1,0).value.encode('
utf-8')) print(sheet.row(1)[0].value.encode('utf-8')) print(sheet.row(1)[1].value.encode('utf-8')) print(sheet.row(6)[1].value.encode('utf-8')) if __name__ =="__main__": read_excel()

 

ctype介紹 :

0empty    1string     2number    3date    4boolean    5error

操作方式

sheet.row(6)[1].ctype(1)