python的神器pandas库就可以非常方便地处理excel,csv,矩阵,表格 等数据,下面这篇文章主要给大家介绍了关于python使用xlsx和pandas处理Excel表格的操作步骤,文中通过图文介绍的非常详细,需要的朋友可以参考下
一、使用xls和xlsx处理Excel表格
xls是excel2003及以前版本所生成的文件格式;
xlsx是excel2007及以后版本所生成的文件格式;
(excel 2007之后版本可以打开上述两种格式,但是excel2013只能打开xls格式);
1.1 用openpyxl模块打开Excel文档,查看所有sheet表
openpyxl.load_workbook()函数接受文件名,返回一个workbook数据类型的值。这个workbook对象代表这个Excel文件,这个有点类似File对象代表一个打开的文本文件。
1 2 3 4 5 |
|
或者
1 2 3 4 5 |
|
1.2 通过sheet名称获取表格
1 2 3 4 5 6 7 8 |
|
1.3 获取活动表的获取行数和列数
方法1:自己写一个for循环
方法2:使用
- sheet.max_row 获取行数
- sheet.max_column 获取列数
1 2 3 4 5 |
|
◼ 读取xlsx文件错误:xlrd.biffh.XLRDError: Excel xlsx file; not supported
运行代码时,会出现以下报错。
xlrd.biffh.XLRDError: Excel xlsx file; not supported
(1)检查第三方库xlrd的版本:
我这里的版本为xlrd2.0.1最新版本,问题就出在这里,我们需要卸载最新版本,安装旧版本,卸载安装过程如下。
(2)在File-Settings下的Project-Python Interpreter中重新按照旧版本xlrd2,
按照上述步骤卸载xlrd后再安装xlrd2后,
可以看到错误解决了。
二、使用pandas读取xlsx
pyCharm pip安装pandas库,请移步到python之 pyCharm pip安装pandas库失败_水w的博客-CSDN博客_pandas安装失败
2.1 读取数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
读取特定的某几列的数据:
1 2 3 4 |
|
2.2 使用pandas查找两个列表中相同的元素
解决:查找两个列表中相同的元素,可以把列表转为元祖/集合,进行交运算。
1 2 3 4 5 6 7 8 9 10 11 12 |
|
◼ 解决ValueError: Excel file format cannot be determined, you must specify an engine manually.
报错:我在使用python的pandas读取表格的数据,但是报错了,
1 2 3 4 5 |
|
问题:问题在于原表格格式可能有些问题。
解决:最直接的办法就是把表格的内容复制到一个自己新建的表格中,然后改成之前表格的路径,
然后再安装这个openpyxl第三方库。
1 |
|
重新运行代码,
ok,问题解决。
◼ 解决but no encoding declared; see https://python.org/dev/peps/pep-0263/ for details
报错:
but no encoding declared; see https://python.org/dev/peps/pep-0263/ for details
问题:xxx文件里有中文字符。
解决:在py文件的代码第一行 加上,
1 |
|
◼ 解决MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
报错:在使用pandas读取文件时,显示错误。
MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
问题:matplotlib3.2以后就把mpl-data分离出去了 。
解决:卸载原来的版本,安装3.1版本。
1 2 |
|
总结
到此这篇关于python使用xlsx和pandas处理Excel表格的文章就介绍到这了。
50G+学习视频教程
100+Python初阶、中阶、高阶电子书籍
点击拿去