xlrd学习使用
安裝xlrd
# windows 安裝 pip install xlrd # mac 安裝 pip3 install xlrd
使用xlrd
1.導入xlrd
import xlrd
2.打開excel
# 添加文件路徑 excel_path = os.path.join(os.path.dirname(__file__), r'data est_data.xlsx') # 打開excel excel_file = xlrd.open_workbook(excel_path)
3.獲取一個工作表
# 根據sheet索引或者名稱獲取sheet內容,同時獲取sheet名稱、行數、列數
# 通過索引順序獲取
sheet1_index = excel_file.sheet_by_index(0)
print(sheet1_index.name, sheet1_index.nrows, sheet1_index.ncols)
# 通過名稱獲取
sheet1_name = excel_file.sheet_by_name('Sheet1')
print(sheet1_name.name, sheet1_name.nrows, sheet1_name.ncols)x
4.獲取表單某行、某列的內容
# 根據sheet名稱或索引獲取整行和整列的值 rows = sheet1_name.row_values(0) cols = sheet1_index.col_values(0) print(rows) print(cols)
5.獲取指定單元格數據
print(sheet1_name.cell(1,0)) print(sheet1_name.cell_value(1,0)) print(sheet1_name.row(0)[3].value) print(sheet1_name.col(2)[1].value)
6.循環行列表數據
nrows = sheet1_name.nrows
for x in range(nrows):
print(sheet1_name.row_values(x))
讀取合并單元格的cell
測試合并單元格的.xlsx
用xlrd普通的做法操作合并單元格
import os
import xlrd
excel_path = os.path.join(os.path.dirname(__file__), r'data est_data.xlsx')
workbook = xlrd.open_workbook(excel_path)
sheet = workbook.sheet_by_name('Sheet1')
# 讀取數據
print('value1:',sheet.cell_value(0,0))
print('value2:',sheet.cell_value(1,0))
print('value3:',sheet.cell_value(2,0))
print('value4:',sheet.cell_value(3,0))
讀取內容
value1: 事件 value2: 學習python編程 value3: value4:
總結:每一個合并單元格,只有左上角的那個cell(行列最小)能夠讀出值,其它cell都是empty。這就是xlrd模塊讀取合并單元格的特點。
獲取merged_cells
import os
import xlrd
excel_path = os.path.join(os.path.dirname(__file__), r'data est_data.xlsx')
workbook = xlrd.open_workbook(excel_path)
sheet = workbook.sheet_by_name('Sheet1')
merged = sheet.merged_cells
print(merged)
打印內容:
[(1, 5, 0, 1), (3, 5, 3, 4)]
總結:merged_cells 返回的是一個列表,每一個元素是合并單元格的位置信息的數組,數組包含四個元素(起始行,結束行,起始列,結束列)
判斷cell是否在合并單元格內
def inMerged(row,col):
for merged in sheet.merged_cells:
if (row >= merged[0] and row <merged[1] and col >= merged[2] and col <merged[3]):
return True
return False
print(inMerged(1,0))
print(inMerged(2,0))
print(inMerged(0,0))
True True False
讀取合并單元格內的cell
def cell_real_value(row,col):
for merged in sheet.merged_cells:
if (row >= merged[0] and row < merged[1] and col >= merged[2] and col < merged[3]):
return sheet.cell_value(merged[0],merged[2])
return sheet.cell_value(row,col)
print(cell_real_value(0,0))
print(cell_real_value(1,0))
print(cell_real_value(2,0))
print(cell_real_value(3,3))
print(cell_real_value(4,3))
事件 學習python編程 學習python編程 100.0 100.0
總結:
if (row >= merged[0] and row < merged[1] and col >= merged[2] and col < merged[3])
代碼遍歷了合并單元格的index,如果在單元格內,就輸出合并單元格初始的merged_row_index和merged_col_index的值
如果不是,則輸出row , col 本身的index的值
參考地址:https://www.pynote.net/archives/744
https://www.cnblogs.com/dream66/p/13198686.html
總結
- 上一篇: clustalw2 使用简介
- 下一篇: 怎么瞬间关闭所有程序如何关闭电脑程序