How to read data from excel file in python

下次还敢
Release: 2024-03-29 06:57:38
Original
672 people have browsed it

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>
Copy after login

2. Import Library

<code class="python">import openpyxl as opxl
# or
import xlrd</code>
Copy after login

3. Open Excel file

  • Using OpenPyXL:

    <code class="python">wb = opxl.load_workbook('file.xlsx')</code>
    Copy after login
  • Use xlrd:

    <code class="python">wb = xlrd.open_workbook('file.xlsx')</code>
    Copy after login

4. Get the worksheet

Get the worksheet object, It contains the data from the file.

  • Using OpenPyXL:

    <code class="python">sheet = wb['Sheet1']</code>
    Copy after login
  • Using xlrd:

    <code class="python">sheet = wb.sheet_by_index(0)</code>
    Copy after login

5. Read cell data

  • Use OpenPyXL:

    <code class="python">cell_value = sheet['A1'].value</code>
    Copy after login
  • Use xlrd:

    <code class="python">cell_value = sheet.cell_value(0, 0)</code>
    Copy after login

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>
    Copy after login
  • 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>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template