.xlsx格式是excel文件的格式,用Python读取excel文件的方法非常的简单,python有三种比较流行的模块,如xlrd, openpyxl,pandas模块读取excel都很简单,下面一一介绍一下如何用它们来读取excel表吧!
首先我们需要一张sales.xlsx表,数据如下:
| Sales Date | Sales Person | Amount |
|---|---|---|
| 12/05/18 | Sila Ahmed | 60000 |
| 06/12/19 | Mir Hossain | 50000 |
| 09/08/20 | Sarmin Jahan | 45000 |
| 07/04/21 | Mahmudul Hasan | 30000 |
案例一:使用xlrd模块读取excel文件
首先我们需要使用pip安装xlrd模块,代码如下:
$ pip install xlrd==1.2.0
xlrd模块的open_workbook()函数用来打开excel文件,workbook.sheet_by_index()是用来打开excel的工作表,而cell_value()则是用来获取excel单元格的值,代码如下:
# Import the xlrd module
import xlrd
# Open the Workbook
workbook = xlrd.open_workbook("sales.xlsx")
# Open the worksheet
worksheet = workbook.sheet_by_index(0)
# Iterate the rows and columns
for i in range(0, 5):
for j in range(0, 3):
# Print the cell values with tab space
print(worksheet.cell_value(i, j), end='\t')
print('')效果如图所示:

案例二:使用openpyxl模块读取excel文件
openpyxl模块是python另外一个读取xlsx文件比较有用的模块,先使用pip安装openpyxl模块,代码如下:
$ pip install openpyxl
openpyxl模块的load_workbook()函数是用来加载xlsx文件,wookbook.active方法能自动读取excel表的工作簿数和工作表的行数与列数,代码如下:
# Import openyxl module
import openpyxl
# Define variable to load the wookbook
wookbook = openpyxl.load_workbook("sales.xlsx")
# Define variable to read the active sheet:
worksheet = wookbook.active
# Iterate the loop to read the cell values
for i in range(0, worksheet.max_row):
for col in worksheet.iter_cols(1, worksheet.max_column):
print(col[i].value, end="\t\t")
print('')输出结果如下:

案例三:使用pandas模块读取excel文件
如果没有安装pandas模块,就先安装它,代码如下:
$ pip install pandas
python pandas模块读取excel的.xlsx文件最方便,pandas模块的read_excel()用来加载excel文件,pandas.DataFrame()函数用来读取xlsx文件的数据,代码如下:
# Import pandas
import pandas as pd
# Load the xlsx file
excel_data = pd.read_excel('sales.xlsx')
# Read the values of the file in the dataframe
data = pd.DataFrame(excel_data, columns=['Sales Date', 'Sales Person', 'Amount'])
# Print the content
print("The content of the file is:\n", data)效果如图所示:

总结:
python这xlrd, openpyxl,pandas三种模块读取excel xlsx文件都非常简单,自己选择一款适合自己的模块使用即可。