1.使用Python统计Excel表中的行数
import xlrd # 计算一个工作簿中所有Sheet表的行数
def count_book(work_book):
workbook = xlrd.open_workbook(work_book) # 打开excel工作薄
sheets = workbook.sheet_names() # 读取所有sheet表,组成list列表
count = 0
for sheet in sheets:
sheet_name = workbook.sheet_by_name(sheet) # 实例化电子表对象sheet_name
single_count = sheet_name.nrows # sheet_name.nrows 单个sheet表的行数
count += single_count # count 工作薄所有sheet的行数
return count excel_book = 'D:/test.xlsx'
print(count_book(excel_book))
执行结果:
2.
import xlrd # 统计sheet表中某一列数据
def count_rows(work_book):
workbook = xlrd.open_workbook(work_book) # 打开excel工作薄
m = 0
f = 0
single_sheet = workbook.sheet_by_index(0) # 实例化第一个sheet页,index为0
for i in range(single_sheet.nrows): # 遍历sheet页中每一行
rows = single_sheet.row_values(i) # row_values 每一行的所有数据
if rows[2] == '男':
m += 1
elif rows[2] == '女':
f += 1
print('男生数量:', m, '女生数量:', f) excel_book = 'D:/test.xlsx'
count_rows(excel_book)
执行结果:
excel表test.xlsx内容如下: