How to read excel file using Python? (code example)

藏色散人
Release: 2019-03-30 14:18:58
Original
3673 people have browsed it

Using the xlrd module, information can be retrieved from spreadsheets. For example, you can use Python to read, write, or modify data. Additionally, the user may have to traverse various tables and retrieve data based on some criteria, or modify some rows and columns and perform a lot of work.

xlrd module is used to extract data from spreadsheets.

Install xlrd module command:

pip install xlrd
Copy after login

Input file:

How to read excel file using Python? (code example)

##Code #1:

# 使用Python读取excel文件
import xlrd 
  
# 给出文件的位置
loc = ("path of file") 
  
# 打开Workbook 
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 
  
# 对于第0行和第0列
sheet.cell_value(0, 0)
Copy after login

Output:


'NAME'
Copy after login

Code #2: Extract row number

# 使用Python提取行数
import xlrd 
  
#给出文件的位置
loc = ("path of file") 
  
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 
sheet.cell_value(0, 0) 
  
#提取行数 
print(sheet.nrows)
Copy after login

Output:

4
Copy after login

Code #3 :Extract column numbers

# 用Python程序提取列数
import xlrd 
  
loc = ("path of file") 
  
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 
  
# 对于第0行和第0列
sheet.cell_value(0, 0) 
  
# 提取列数
print(sheet.ncols)
Copy after login

Output:


3
Copy after login

Code #4:Extract all column names

# 提取所有列名
import xlrd 
  
loc = ("path of file") 
  
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 
  
sheet.cell_value(0, 0) 
  
for i in range(sheet.ncols): 
    print(sheet.cell_value(0, i))
Copy after login

Output:

NAME
SEMESTER
ROLL NO
Copy after login

Code #5: Extract the first column

# 提取第一列
import xlrd 
  
loc = ("path of file") 
  
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 
sheet.cell_value(0, 0) 
  
for i in range(sheet.nrows): 
    print(sheet.cell_value(i, 0))
Copy after login

Output:


NAME
ALEX
CLAY
JUSTIN
Copy after login

Code #6: Extract specific rows Value

Output:

['ALEX', 4.0, 2011272.0]]
Copy after login
Related recommendations: "

Python Tutorial"

This article is about how to read excel files in Python Introduction, I hope it will be helpful to friends in need!

The above is the detailed content of How to read excel file using Python? (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template