Home > Article > Backend Development > How to read data from excel file in python
There are 6 steps to use Python to read Excel file data: Install a third-party library (such as OpenPyXL or xlrd). Import library. Open the Excel file. Get the worksheet object. Read cell data. Iterate through the worksheet to read data from all cells.
How to read Excel file data in Python
In order to use Python to read data in Excel files, you need to Use a third-party library such as OpenPyXL or xlrd.
The following are the steps to read Excel file data in Python:
1. Install OpenPyXL or xlrd
<code class="python">pip install openpyxl # or pip install xlrd</code>
2. Import Library
<code class="python">import openpyxl as opxl # or import xlrd</code>
3. Open Excel file
Using OpenPyXL:
<code class="python">wb = opxl.load_workbook('file.xlsx')</code>
Use xlrd:
<code class="python">wb = xlrd.open_workbook('file.xlsx')</code>
4. Get the worksheet
Get the worksheet object, It contains the data from the file.
Using OpenPyXL:
<code class="python">sheet = wb['Sheet1']</code>
Using xlrd:
<code class="python">sheet = wb.sheet_by_index(0)</code>
5. Read cell data
Use OpenPyXL:
<code class="python">cell_value = sheet['A1'].value</code>
Use xlrd:
<code class="python">cell_value = sheet.cell_value(0, 0)</code>
6. Traverse the worksheet
You can usefor
Loop through all rows or columns in the worksheet and read the data of each cell.
Using OpenPyXL:
<code class="python">for row in sheet.iter_rows(): for cell in row: cell_value = cell.value</code>
Using xlrd:
<code class="python">for row_index in range(sheet.nrows): for col_index in range(sheet.ncols): cell_value = sheet.cell_value(row_index, col_index)</code>
Tip:
file.xlsx
with the actual Excel file name. wb['MySheet']
. sheet['A1:D5']
. The above is the detailed content of How to read data from excel file in python. For more information, please follow other related articles on the PHP Chinese website!