python使用xlrd模塊讀取excel的方法實例
一、安裝xlrd模塊:
1、mac下打開終端輸入命令:
pip install xlrd
2、驗證安裝是否成功:
- 在mac終端輸入 python 進入python環(huán)境
- 然后輸入 import xlrd
不報錯說明模塊安裝成功
二、常用方法:
1、導(dǎo)入模塊:
import xlrd
2、打開文件:
x1 = xlrd.open_workbook("data.xlsx")3、獲取sheet:
- 獲取所有sheet名字:x1.sheet_names()
- 獲取sheet數(shù)量:x1.nsheets
- 獲取所有sheet對象:x1.sheets()
- 通過sheet名查找:x1.sheet_by_name("test”)
- 通過索引查找:x1.sheet_by_index(3)
# -*- coding:utf-8 -*-
import xlrd
import os
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
print filePath
# 1、打開文件
x1 = xlrd.open_workbook(filePath)
# 2、獲取sheet對象
print 'sheet_names:', x1.sheet_names() # 獲取所有sheet名字
print 'sheet_number:', x1.nsheets # 獲取sheet數(shù)量
print 'sheet_object:', x1.sheets() # 獲取所有sheet對象
print 'By_name:', x1.sheet_by_name("test") # 通過sheet名查找
print 'By_index:', x1.sheet_by_index(3) # 通過索引查找輸出:
sheet_names: [u' plan', u'team building', u'modile', u'test'] sheet_number: 4 sheet_object: [<xlrd.sheet.Sheet object at 0x10244c190>, <xlrd.sheet.Sheet object at 0x10244c150>, <xlrd.sheet.Sheet object at 0x10244c110>, <xlrd.sheet.Sheet object at 0x10244c290>] By_name: <xlrd.sheet.Sheet object at 0x10244c290> By_index: <xlrd.sheet.Sheet object at 0x10244c290>
4、獲取sheet的匯總數(shù)據(jù):
- 獲取sheet名:sheet1.name
- 獲取總行數(shù):sheet1.nrows
- 獲取總列數(shù):sheet1.ncols
# -*- coding:utf-8 -*-
import xlrd
import os
from datetime import date,datetime
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
print filePath
# 打開文件
x1 = xlrd.open_workbook(filePath)
# 獲取sheet的匯總數(shù)據(jù)
sheet1 = x1.sheet_by_name("plan")
print "sheet name:", sheet1.name # get sheet name
print "row num:", sheet1.nrows # get sheet all rows number
print "col num:", sheet1.ncols # get sheet all columns number輸出:
sheet name: plan row num: 31 col num: 11
5、單元格批量讀?。?/h3>
a)行操作:
- sheet1.row_values(0) # 獲取第一行所有內(nèi)容,合并單元格,首行顯示值,其它為空。
- sheet1.row(0) # 獲取單元格值類型和內(nèi)容
- sheet1.row_types(0) # 獲取單元格數(shù)據(jù)類型
# -*- coding:utf-8 -*-
import xlrd
import os
from datetime import date,datetime
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
x1 = xlrd.open_workbook(filePath)
sheet1 = x1.sheet_by_name("plan")
# 單元格批量讀取
print sheet1.row_values(0) # 獲取第一行所有內(nèi)容,合并單元格,首行顯示值,其它為空。
print sheet1.row(0) # 獲取單元格值類型和內(nèi)容
print sheet1.row_types(0) # 獲取單元格數(shù)據(jù)類型輸出:
[u'learning plan', u'', u'', u'', u'', u'', u'', u'', 123.0, 42916.0, 0]
[text:u'learning plan', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', number:123.0, xldate:42916.0, bool:0]
array('B', [1, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4])b) 表操作
- sheet1.row_values(0, 6, 10) # 取第1行,第6~10列(不含第10表)
- sheet1.col_values(0, 0, 5) # 取第1列,第0~5行(不含第5行)
- sheet1.row_slice(2, 0, 2) # 獲取單元格值類型和內(nèi)容
- sheet1.row_types(1, 0, 2) # 獲取單元格數(shù)據(jù)類型
# -*- coding:utf-8 -*-
import xlrd
import os
from datetime import date,datetime
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
print filePath
# 1、打開文件
x1 = xlrd.open_workbook(filePath)
sheet1 = x1.sheet_by_name("plan")
# 列操作
print sheet1.row_values(0, 6, 10) # 取第1行,第6~10列(不含第10表)
print sheet1.col_values(0, 0, 5) # 取第1列,第0~5行(不含第5行)
print sheet1.row_slice(2, 0, 2) # 獲取單元格值類型和內(nèi)容,同sheet1.row(0)
print sheet1.row_types(1, 0, 2) # 獲取單元格數(shù)據(jù)類型輸出:
[u'', u'', 123.0, 42916.0]
[u'learning plan', u'\u7f16\u53f7', 1.0, 2.0, 3.0]
[number:1.0, text:u'\u7ba1\u7406\u5b66\u4e60']
array('B', [1, 1])6、特定單元格讀取:
a) 獲取單元格值:
- sheet1.cell_value(1, 2)
- sheet1.cell(1, 2).value
- sheet1.row(1)[2].value
b) 獲取單元格類型:
- sheet1.cell(1, 2).ctype
- sheet1.cell_type(1, 2)
- sheet1.row(1)[2].ctype
# -*- coding:utf-8 -*-
import xlrd
import os
from datetime import date,datetime
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
x1 = xlrd.open_workbook(filePath)
sheet1 = x1.sheet_by_name("plan")
# 特定單元格讀取
# 取值
print sheet1.cell_value(1, 2)
print sheet1.cell(1, 2).value
print sheet1.row(1)[2].value
#取類型
print sheet1.cell(1, 2).ctype
print sheet1.cell_type(1, 2)
print sheet1.row(1)[2].ctype7、(0,0)轉(zhuǎn)換A1:
- xlrd.cellname(0, 0) # (0,0)轉(zhuǎn)換成A1
- xlrd.cellnameabs(0, 0) # (0,0)轉(zhuǎn)換成$A$1
- xlrd.colname(30) # 把列由數(shù)字轉(zhuǎn)換為字母表示
# -*- coding:utf-8 -*-
import xlrd
import os
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
# 打開文件
x1 = xlrd.open_workbook(filePath)
sheet1 = x1.sheet_by_name("plan")
# (0,0)轉(zhuǎn)換成A1
print xlrd.cellname(0, 0) # (0,0)轉(zhuǎn)換成A1
print xlrd.cellnameabs(0, 0) # (0,0)轉(zhuǎn)換成$A$1
print xlrd.colname(30) # 把列由數(shù)字轉(zhuǎn)換為字母表示輸出:
A1 $A$1 AE
8、數(shù)據(jù)類型:
- 空:0
- 字符串:1
- 數(shù)字:2
- 日期:3
- 布爾:4
- error:5
附:寫一個自動獲取excel表內(nèi)容的類
本代碼已實現(xiàn)自動轉(zhuǎn)換單元格數(shù)據(jù)類型,不會發(fā)生整形數(shù)字以浮點數(shù)顯示,布爾型True或False顯示為1,0;日期時間顯示為一連串的小數(shù)問題
import xlrd
from xlrd import xldate_as_tuple
import datetime
'''
xlrd中單元格的數(shù)據(jù)類型
數(shù)字一律按浮點型輸出,日期輸出成一串小數(shù),布爾型輸出0或1,所以我們必須在程序中做判斷處理轉(zhuǎn)換
成我們想要的數(shù)據(jù)類型
0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
'''
class ExcelData():
# 初始化方法
def __init__(self, data_path, sheetname):
#定義一個屬性接收文件路徑
self.data_path = data_path
# 定義一個屬性接收工作表名稱
self.sheetname = sheetname
# 使用xlrd模塊打開excel表讀取數(shù)據(jù)
self.data = xlrd.open_workbook(self.data_path)
# 根據(jù)工作表的名稱獲取工作表中的內(nèi)容(方式①)
self.table = self.data.sheet_by_name(self.sheetname)
# 根據(jù)工作表的索引獲取工作表的內(nèi)容(方式②)
# self.table = self.data.sheet_by_name(0)
# 獲取第一行所有內(nèi)容,如果括號中1就是第二行,這點跟列表索引類似
self.keys = self.table.row_values(0)
# 獲取工作表的有效行數(shù)
self.rowNum = self.table.nrows
# 獲取工作表的有效列數(shù)
self.colNum = self.table.ncols
# 定義一個讀取excel表的方法
def readExcel(self):
# 定義一個空列表
datas = []
for i in range(1, self.rowNum):
# 定義一個空字典
sheet_data = {}
for j in range(self.colNum):
# 獲取單元格數(shù)據(jù)類型
c_type = self.table.cell(i,j).ctype
# 獲取單元格數(shù)據(jù)
c_cell = self.table.cell_value(i, j)
if c_type == 2 and c_cell % 1 == 0: # 如果是整形
c_cell = int(c_cell)
elif c_type == 3:
# 轉(zhuǎn)成datetime對象
date = datetime.datetime(*xldate_as_tuple(c_cell,0))
c_cell = date.strftime('%Y/%d/%m %H:%M:%S')
elif c_type == 4:
c_cell = True if c_cell == 1 else False
sheet_data[self.keys[j]] = c_cell
# 循環(huán)每一個有效的單元格,將字段與值對應(yīng)存儲到字典中
# 字典的key就是excel表中每列第一行的字段
# sheet_data[self.keys[j]] = self.table.row_values(i)[j]
# 再將字典追加到列表中
datas.append(sheet_data)
# 返回從excel中獲取到的數(shù)據(jù):以列表存字典的形式返回
return datas
if __name__ == "__main__":
data_path = "ttt.xlsx"
sheetname = "Sheet1"
get_data = ExcelData(data_path, sheetname)
datas = get_data.readExcel()
print(datas)
總結(jié)
到此這篇關(guān)于python使用xlrd模塊讀取excel的文章就介紹到這了,更多相關(guān)python xlrd讀取excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python中使用xlrd、xlwt操作excel表格詳解
- 解決python xlrd無法讀取excel文件的問題
- Python xlrd讀取excel日期類型的2種方法
- Python第三方庫xlrd/xlwt的安裝與讀寫Excel表格
- Python中使用第三方庫xlrd來寫入Excel文件示例
- 詳解python中xlrd包的安裝與處理Excel表格
- Python使用xlrd模塊操作Excel數(shù)據(jù)導(dǎo)入的方法
- python使用xlrd與xlwt對excel的讀寫和格式設(shè)定
- python使用xlrd和xlwt讀寫Excel文件的實例代碼
- python讀取excel進行遍歷/xlrd模塊操作
相關(guān)文章
詳解Python模塊化--模塊(Modules)和包(Packages)
這篇文章主要介紹了使用Python的模塊(Modules)和包(Packages),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08
Python連接SQLite數(shù)據(jù)庫并進行增冊改查操作方法詳解
這篇文章主要介紹了Python對SQLite數(shù)據(jù)庫進行增冊改查操作方法詳解,需要的朋友可以參考下2020-02-02
python如何繪制極坐標(biāo)輪廓圖contourf
這篇文章主要介紹了python如何繪制極坐標(biāo)輪廓圖contourf問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
Python?如何將?matplotlib?圖表集成進到PDF?中
這篇文章主要介紹了Python?如何將?matplotlib?圖表集成進到PDF?中,文章介紹內(nèi)容詳細(xì),具有一定的參考價值,需要的小伙伴可以參考一下,希望對你的學(xué)習(xí)有所幫助2022-03-03
Django-rest-framework中過濾器的定制實例
這篇文章主要介紹了Django-rest-framework中過濾器的定制實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

