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\test_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\test_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\test_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