简体   繁体   English

使用 xlrd - Python 读取范围内的行数

[英]Read the number of rows in a range with xlrd - Python

I want to read the number of rows within a range.我想读取一个范围内的行数。 I have a file that has a lot of rows.我有一个包含很多行的文件。 I want to know the number of rows in a column range, let´s say, from column A through D.我想知道列范围中的行数,比如说从 A 列到 D 列。

workbook = xlrd.open_workbook(file)
sheet = workbook.sheet_by_index(0)
sheet.nrows[0:4] #I want to know the number of rows within that range, or "A{}:D{}"

If anyone knows a method to do this, please help me.如果有人知道这样做的方法,请帮助我。 Thank You!谢谢你!

You can Iterate through columns... Use loop:您可以遍历列...使用循环:

for col_idx in range(0, num_cols):  # Iterate through columns 
        cell_obj = xl_sheet.cell(row_idx, col_idx)  # Get cell object by row, col

There isn't anything wrong with using xlrd, it's what I used first as well.使用 xlrd 没有任何问题,这也是我首先使用的。 However, I recommend using the pandas library, as it's much more used throughout the python community.但是,我建议使用pandas库,因为它在整个 Python 社区中使用得更多。

import pandas

dataframe = pandas.read_excel(file, usecols='A:D')
print(len(dataframe))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM