python操作Excel讀寫 使用xlrd

2022-07-30 05:21:12 字數 2826 閱讀 8261

一、安裝xlrd模組

二、使用介紹

1、匯入模組

import xlrd

2、開啟excel檔案讀取資料

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

3、使用技巧

獲取乙個工作表

table = data.sheets()[0]          #通過索引順序獲取

table = data.sheet_by_index(0) #通過索引順序獲取

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資料。

#

-*- coding: utf-8 -*-

import

xdrlib ,sys

import

xlrd

def open_excel(file= '

file.xls'):

try:

data =xlrd.open_workbook(file)

return

data

except

exception,e:

print

str(e)

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

def excel_table_byindex(file= '

file.xls

',colnameindex=0,by_index=0):

data =open_excel(file)

table =data.sheets()[by_index]

nrows = table.nrows #

行數 ncols = table.ncols #

列數 colnames = table.row_values(colnameindex) #

某一行資料

list =

for rownum in range(1,nrows):

row =table.row_values(rownum)

ifrow:

for i in

range(len(colnames)):

return

list

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

def excel_table_byname(file= '

file.xls

',colnameindex=0,by_name=u'

sheet1'):

data =open_excel(file)

table =data.sheet_by_name(by_name)

nrows = table.nrows #

行數 colnames = table.row_values(colnameindex) #

某一行資料

list =

for rownum in range(1,nrows):

row =table.row_values(rownum)

ifrow:

for i in

range(len(colnames)):

return

list

defmain():

tables =excel_table_byindex()

for row in

tables:

print

row tables =excel_table_byname()

for row in

tables:

print

rowif

__name__=="

__main__":

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 會有不同的加...