Get values of all rows in a particular column in openpyxl – Python
In this article, we will explore how to get the values of all rows in a particular column in a spreadsheet using openpyxl in Python. We will start by discussing the basics of openpyxl and how to install and import it. Then, we will walk through for example, how to extract the values of a particular column from a spreadsheet and store them in a list.
To install openpyxl using pip, open a terminal window or command prompt and enter the following command:
pip install openpyxl
Raw Spreadsheet Data
For example, suppose you have a spreadsheet with the following data:
Extracting the Values of a Particular Column
Now that you know how to read a spreadsheet and access the rows and cells in a sheet, you can extract the values of a particular column from the sheet. To do this, you can simply iterate over the rows in the sheet and check the value of the cell in the column you are interested in. You can then store the values in a list or other data structure for further processing.
To extract the values of the “Name” column, you could use the following code:
['Name', 'John', 'Jane', 'Bob', 'Alice']
Note that the first row in the sheet contains the column names, so it is included in the list. If you want to exclude the column names from the list, you can add a check to skip the first row:
['John', 'Jane', 'Bob', 'Alice']
Extracting the Values of a Particular Column Name
In the previous example, we extracted the values of a particular column by specifying the index of the column. However, in some cases, it may be more convenient to extract the values of a column by its name, rather than its index. To do this, you can use the iter_cols() method of the Sheet object to iterate over the columns in the sheet, and check the value of the first cell in each column to determine the column name.
To extract the values of the “Name” column by its name, you could use the following code:
['Age', 30.0, 25.0, 35.0, 28.0]
To exclude the column name from the list, you can add a check to skip the first cell:
[30.0, 25.0, 35.0, 28.0]
Please Login to comment...