python操作Excel讀寫 使用xlrd

2022-04-15 10:11:12 字數 2716 閱讀 8715

一、安裝xlrd模組

二、使用介紹

1、匯入模組

import xlrd

2、開啟excel檔案讀取資料

data = xlrd.open_workbook('excelfile.xls')

3、使用技巧

獲取乙個工作表

table = data.sheet_by_name(u'sheet1')#通過名稱獲取

獲取整行和整列的值(陣列)

table.row_values(i)

table.col_values(i)

獲取行數和列數

nrows = table.nrows

ncols = table.ncols

迴圈行列表資料

for i in range(nrows ):

print table.row_values(i)

單元格

cell_a1 = table.cell(0,0).value

cell_c4 = table.cell(2,3).value

使用行列索引

cell_a1 = table.row(0)[0].value

cell_a2 = table.col(1)[0].value

簡單的寫入

row = 0

col = 0

# 型別 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

ctype = 1

value = '單元格的值'

xf = 0

table.put_cell(row, col, ctype, value, xf)

table.cell(0,0)  #單元格的值'

table.cell(0,0).value #單元格的值'

三、demo**

demo**其實很簡單,就是讀取excel資料。

1

#-*- coding: utf-8 -*-

2import xdrlib ,sys

3import xlrd

4def open_excel(file= '

file.xls

'):5

try:

6 data = xlrd.open_workbook(file)

7return data

8except exception,e:

9print str(e)10#

根據索引獲取excel**中的資料 引數:file:excel檔案路徑 colnameindex:表頭列名所在行的所以 ,by_index:表的索引

11def excel_table_byindex(file= '

file.xls

',colnameindex=0,by_index=0):

12 data = open_excel(file)

13 table = data.sheets()[by_index]

14 nrows = table.nrows #

行數15 ncols = table.ncols #

列數16 colnames = table.row_values(colnameindex) #

某一行資料

17 list =

18for rownum in range(1,nrows):

1920 row = table.row_values(rownum)

21return list

2728

#根據名稱獲取excel**中的資料 引數:file:excel檔案路徑 colnameindex:表頭列名所在行的所以 ,by_name:sheet1名稱

29def excel_table_byname(file= '

file.xls

',colnameindex=0,by_name=u'

sheet1

'):30 data = open_excel(file)

31 table = data.sheet_by_name(by_name)

32 nrows = table.nrows #

行數 33 colnames = table.row_values(colnameindex) #

某一行資料

34 list =

35for rownum in range(1,nrows):

36 row = table.row_values(rownum)

37return list

4344

def main():

45 tables = excel_table_byindex()

46for row in tables:

47print row

4849 tables = excel_table_byname()

50for row in tables:

51print row

5253

if__name__=="

__main__

":54 main()

Python 對Excel操作讀寫

最近公司專案需要寫大量的測試案例,分析案例時發現,案例的前提條件是可以互相排列組合的,人工操作太過繁瑣,可以考慮使用python來實現自動生成案例xlwt xlrd xlutils pip install xlutils 安裝xlutils模組,聯網狀態下cmd直接輸入pip install xlu...

python讀寫excel表操作

file xlrd.open workbook sample.xlsx 此時file是整個檔案物件,獲取某個工作表可以用序號或者表名 print 表名 t sheet 1.name print 錶行數 t sheet 1.nrows print 表列數 t sheet 1.ncols 表名 shee...

python讀寫操作excel資料

今天教務老師給我發來了一堆excel表 需要我處理一些資料 都是一些基礎的資料,這是今年來同濟參加夏令營的申請材料 在我按部就班的處理了幾個之後,覺得這樣處理實在是效率太低下了,於是我就寫了下面這個程式,用python 來批量化處理excel資料 首先 本科學校級別不同,985 211 會有不同的加...