python讀取excel檔案

2021-07-25 21:54:15 字數 2751 閱讀 6035

一、安裝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資料。

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檔案

coding utf 8 import xlrd 路徑前加 r,讀取的檔案路徑 file path r f test.xlsx 檔案路徑的中文轉碼 file path file path.decode utf 8 獲取資料 data xlrd.open workbook file path 獲取sh...

python讀取excel檔案

週末師姐讓我幫忙處理一下之前的醫療資料,資料都存放在excel檔案中,需要從裡面提取出部分資料並轉化為她指定的格式。總共有20幾個檔案,如果手動處理的話,不僅效率低下而且很繁雜,於是我編寫了python指令碼來完成了本次的工作,下面記錄一下相關的知識,並做乙個總結。我用到的庫是 openpyxl 首...

python讀取EXCEL檔案

coding utf 8 author liuqingzheng data 2018 11 27 17 26 匯入模組 import xlrd from datetime import datetime,date 開啟要讀的excel tt xlrd.open workbook tt.xlsx 列印...