python读取excel格式

如题所述

Python读写EXCEL文件常用方法大全
Huny 信息网络工程研究中心 2020-12-19

1 前言
python读写excel的方式有很多,不同的模块在读写的讲法上稍有区别,这里我主要介绍几个常用的方式。

用xlrd和xlwt进行excel读写;

用openpyxl进行excel读写;

用pandas进行excel读写;
参考:
https://www.python-excel.org/
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html#pandas.read_excel
https://www.jianshu.com/p/19219542bf23

2 数据准备

为了方便演示,我这里新建了一个data.xls和data.xlsx文件,第一个工作表sheet1区域“A1:E5”的内容如下,用于测试读写excel的代码:


3 xlrd和xlwt

xlrd是一个库,用于从Excel文件中以.xls格式读取数据和格式化信息
xlwt是一个库,用于将数据和格式化信息写入较旧的Excel文件(例如:.xls)。

示例

pip install xlrd
pip install xlwt


我们开始来读取文件的内容

import xlrd
import os

file_path = os.path.dirname(os.path.abspath(__file__))
base_path = os.path.join(file_path, 'data.xlsx')
book = xlrd.open_workbook(base_path)
sheet1 = book.sheets()[0]
nrows = sheet1.nrows
print('表格总行数', nrows)
ncols = sheet1.ncols
print('表格总列数', ncols)
row3_values = sheet1.row_values(2)
print('第3行值', row3_values)
col3_values = sheet1.col_values(2)
print('第3列值', col3_values)
cell_3_3
温馨提示:答案为网友推荐,仅供参考
相似回答