網站首頁 編程語言 正文
一、安裝xlrd模塊:
1、mac下打開終端輸入命令:
pip install xlrd
2、驗證安裝是否成功:
- 在mac終端輸入 python ?進入python環境
- 然后輸入 import xlrd
不報錯說明模塊安裝成功
二、常用方法:
1、導入模塊:
import xlrd
2、打開文件:
x1 = xlrd.open_workbook("data.xlsx")
3、獲取sheet:
- 獲取所有sheet名字:x1.sheet_names()
- 獲取sheet數量: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數量 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: [, , , ] By_name: By_index:
4、獲取sheet的匯總數據:
- 獲取sheet名:sheet1.name
- 獲取總行數:sheet1.nrows
- 獲取總列數: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的匯總數據 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、單元格批量讀取:
?a)行操作:
- sheet1.row_values(0)? # 獲取第一行所有內容,合并單元格,首行顯示值,其它為空。
- sheet1.row(0)???????? # 獲取單元格值類型和內容
- sheet1.row_types(0)?? # 獲取單元格數據類型
# -*- 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) # 獲取第一行所有內容,合并單元格,首行顯示值,其它為空。 print sheet1.row(0) # 獲取單元格值類型和內容 print sheet1.row_types(0) # 獲取單元格數據類型
輸出:
[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)???? # 獲取單元格值類型和內容
- sheet1.row_types(1, 0, 2)?? # 獲取單元格數據類型
# -*- 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) # 獲取單元格值類型和內容,同sheet1.row(0) print sheet1.row_types(1, 0, 2) # 獲取單元格數據類型
輸出:
[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].ctype
7、(0,0)轉換A1:
- xlrd.cellname(0, 0)?? # (0,0)轉換成A1
- xlrd.cellnameabs(0, 0) # (0,0)轉換成$A$1
- xlrd.colname(30)? # 把列由數字轉換為字母表示
# -*- 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)轉換成A1 print xlrd.cellname(0, 0) # (0,0)轉換成A1 print xlrd.cellnameabs(0, 0) # (0,0)轉換成$A$1 print xlrd.colname(30) # 把列由數字轉換為字母表示
輸出:
A1 $A$1 AE
8、數據類型:
- 空:0
- 字符串:1
- 數字:2
- 日期:3
- 布爾:4
- error:5
附:寫一個自動獲取excel表內容的類
本代碼已實現自動轉換單元格數據類型,不會發生整形數字以浮點數顯示,布爾型True或False顯示為1,0;日期時間顯示為一連串的小數問題
import xlrd from xlrd import xldate_as_tuple import datetime ''' xlrd中單元格的數據類型 數字一律按浮點型輸出,日期輸出成一串小數,布爾型輸出0或1,所以我們必須在程序中做判斷處理轉換 成我們想要的數據類型 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表讀取數據 self.data = xlrd.open_workbook(self.data_path) # 根據工作表的名稱獲取工作表中的內容(方式①) self.table = self.data.sheet_by_name(self.sheetname) # 根據工作表的索引獲取工作表的內容(方式②) # self.table = self.data.sheet_by_name(0) # 獲取第一行所有內容,如果括號中1就是第二行,這點跟列表索引類似 self.keys = self.table.row_values(0) # 獲取工作表的有效行數 self.rowNum = self.table.nrows # 獲取工作表的有效列數 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): # 獲取單元格數據類型 c_type = self.table.cell(i,j).ctype # 獲取單元格數據 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: # 轉成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 # 循環每一個有效的單元格,將字段與值對應存儲到字典中 # 字典的key就是excel表中每列第一行的字段 # sheet_data[self.keys[j]] = self.table.row_values(i)[j] # 再將字典追加到列表中 datas.append(sheet_data) # 返回從excel中獲取到的數據:以列表存字典的形式返回 return datas if __name__ == "__main__": data_path = "ttt.xlsx" sheetname = "Sheet1" get_data = ExcelData(data_path, sheetname) datas = get_data.readExcel() print(datas)
總結?
原文鏈接:https://www.cnblogs.com/zhang-jun-jie/p/9273721.html
相關推薦
- 2022-04-07 一篇文章帶你學習Python3的高級特性(2)_python
- 2022-09-13 Python實現創建模塊的方法詳解_python
- 2022-11-05 python中的bisect模塊與二分查找詳情_python
- 2022-06-06 ASP.NET的Core?AD域登錄過程示例_ASP.NET
- 2022-10-28 Python圖形用戶界面與游戲開發實例詳解_python
- 2022-06-01 C語言超詳細講解棧與隊列實現實例_C 語言
- 2022-05-26 Python借助with語句實現代碼段只執行有限次_python
- 2023-03-01 Shell?$[]對整數進行數學運算實現_linux shell
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支