1) 遍历一个SHEET,无非就是两个循环,rows属性是取得所有行。
fn = 'data3_16.xlsx' wb = openpyxl.load_workbook(fn) ws = wb.active for row in ws.rows:for cell in row:print(cell.value, end=' ')print() 2) 返回工作表的最小行数和最小列数
fn = 'data3_19_1.xlsx' wb = openpyxl.load_workbook(fn) ws = wb.active print(f"工作表有资料最小行数 = {ws.min_row}") print(f"工作表有资料最大行数 = {ws.max_row}") print(f"工作表有资料最小列数 = {ws.min_column}") print(f"工作表有资料最大列数 = {ws.max_column}")3)用values_only=True,可以显示遍历每个行中的单元格内容: 比如EXCEL:则:
fn = 'data3_19_1.xlsx' wb = openpyxl.load_workbook(fn) ws = wb.active for row in ws.iter_rows(values_only=True):print(type(row))print(row)输出: <class 'tuple'> (1, 5, 9, 13) <class 'tuple'> (2, 6, 10, 14) <class 'tuple'> (3, 7, 11, 15) <class 'tuple'> (4, 8, 12, 16)
4) 获得指定行或列的值:
fn = 'data3_16.xlsx' wb = openpyxl.load_workbook(fn) ws = wb.active for cell in ws['A']: # A列print(cell.value) for cell in ws[5]: # 索引是5,输出第5行的所有内容。print(cell.value, end=' ')