Home >Backend Development >Python Tutorial >How to read excel file using Python? (code example)

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

藏色散人
藏色散人Original
2019-03-30 14:18:583717browse

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

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)

Output:


'NAME'

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)

Output:

4

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)

Output:


3

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))

Output:

NAME
SEMESTER
ROLL NO

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))

Output:


NAME
ALEX
CLAY
JUSTIN

Code #6: Extract specific rows Value

Output:

['ALEX', 4.0, 2011272.0]]

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!

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