1. 程式人生 > >python+xlrd+xlwt操作excel

python+xlrd+xlwt操作excel

xca 軟件下載 int() 獲取 shee def try 品牌 workbook

百度搜索:小強測試品牌

QQ群:522720170

介紹


xlrd(讀操作),xlwt(寫操作)

上述軟件下載後,分別解壓,之後在cmd命令下分別進入對應的目錄中運行

python setup.py install

如果運行過程中提示缺少setuptools,則先運行python ez_setup.py之後在重復上面的步驟

PS:office的版本不要用太高的,建議最好用03版本的,且後綴為xls的

源碼bug修復


安裝好xlwt3後,找到formula.py文件,將其中的

__slots__ = ["__init__", "__s", "__parser", "__sheet_refs", "__xcall_refs"]

修改為

__slots__ = [ "__s", "__parser", "__sheet_refs", "__xcall_refs"]

實戰


不廢話,碼起來~

import xlrd

import xlwt3

path = ‘excel所在的路徑-小強測試品牌‘

#打開excel

def open_excel(path):

try:

workbook = xlrd.open_workbook(path)

print("excel打開成功")

return workbook

except Exception as e:

print(str(e))

open_excel(path)

#讀取excel的信息

def show_excel(path):

workbook=xlrd.open_workbook(path)

#獲取sheet

sheets = workbook.sheet_names()

print("獲取excel中存在的sheet名稱", sheets)

sheet = workbook.sheets()[0] #通過索引順序獲取一個sheet

print("通過索引順序獲取一個sheet對象", sheet)

sheet = workbook.sheet_by_index(0) #通過索引順序獲取一個sheet

print("通過索引順序獲取一個sheet對象", sheet)

#sheet = workbook.sheet_by_name(‘Sheet1‘) #通過名稱獲取

#獲取行數、列數、單元格

print("獲取總行數", sheet.nrows) #總行數

print("獲取總列數", sheet.ncols) #總列數

print("第1行的值", sheet.row_values(0)) #獲取整行的內容

print("第2列的值", sheet.col_values(1)) #獲取整列的內容

print("第2行2列的值", sheet.cell_value(1,1)) #獲取單元格的值

show_excel(path)

#寫入數據

def write_excel(path):

wb=xlwt3.Workbook()#創建工作薄

sheet=wb.add_sheet("xlwt3數據測試表",cell_overwrite_ok=True)#創建工作表

value = [["名稱", "小強python自動化測試實戰", "小強性能測試實戰"], ["價格", "52.3", "45"]]

for i in range(0,2):

for j in range(0,len(value[i])):

sheet.write(i,j,value[i][j])#三個參數分表代表行、列、值

wb.save(path)

print("寫入數據成功")

write_excel(path)

#讀取數據

def read_excel(path,by_index=0):

workbook = open_excel(path)

table = workbook.sheets()[by_index]

nrows = table.nrows #行數

ncols = table.ncols #列數

print("第一種輸出形式")

for i in range(0,nrows):

row=table.row(i)

for j in range(0,ncols):

print(table.cell_value(i,j)," ",end="")#加上最後的參數end可以不換行

print()

print("第二種輸出形式")

for i in range(0,nrows):

ss = table.row_values(i)#獲取第i行的數據列表(整行)

print(‘ss=‘, ss)

for i in range(0, len(ss)):

print(ss[i])

print(‘------------------‘)

read_excel(path)

python+xlrd+xlwt操作excel