Home  >  Article  >  Backend Development  >  How to read data from excel file in python

How to read data from excel file in python

下次还敢
下次还敢Original
2024-03-29 06:57:38644browse

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 data from excel file in python

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 useforLoop 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:

  • Replace file.xlsx with the actual Excel file name.
  • If you need to read a worksheet with a different worksheet name, please specify the worksheet name, such as wb['MySheet'].
  • To read data in a specific area, you can use slicing syntax such as 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn