温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用Python处理excel表格中的数据

发布时间:2022-03-07 11:56:14 来源:亿速云 阅读:276 作者:小新 栏目:开发技术

这篇文章主要介绍怎么用Python处理excel表格中的数据,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

一、基础、常用方法

1. 读取excel

1、导入模块:

import xlrd

2、打开文件:

x1 = xlrd.open_workbook("data.xlsx")

3、获取sheet:

sheet是指工作表的名称,因为一个excel有多个工作表

怎么用Python处理excel表格中的数据


获取所有sheet名字:x1.sheet_names()

获取sheet数量:x1.nsheets

获取所有sheet对象:x1.sheets()

通过sheet名查找:x1.sheet_by_name("test”)

通过索引查找:x1.sheet_by_index(3)

# -*- coding:utf-8 -*-

import xlrd
import os

filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)

print filePath

# 1、打开文件
x1 = xlrd.open_workbook(filePath)

# 2、获取sheet对象
print 'sheet_names:', x1.sheet_names()  # 获取所有sheet名字
print 'sheet_number:', x1.nsheets        # 获取sheet数量
print 'sheet_object:', x1.sheets()       # 获取所有sheet对象
print 'By_name:', x1.sheet_by_name("test")  # 通过sheet名查找
print 'By_index:', x1.sheet_by_index(3)  # 通过索引查找

输出:

sheet_names: [u' plan', u'team building', u'modile', u'test']
sheet_number: 4
sheet_object: [<xlrd.sheet.Sheet object at 0x10244c190>, <xlrd.sheet.Sheet object at 0x10244c150>, <xlrd.sheet.Sheet object at 0x10244c110>, <xlrd.sheet.Sheet object at 0x10244c290>]
By_name: <xlrd.sheet.Sheet object at 0x10244c290>
By_index: <xlrd.sheet.Sheet object at 0x10244c290>

4、获取sheet的汇总数据:

获取sheet名:sheet1.name

获取总行数:sheet1.nrows

获取总列数:sheet1.ncols

# -*- coding:utf-8 -*-

import xlrd
import os
from datetime import date,datetime

filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
print filePath

# 打开文件
x1 = xlrd.open_workbook(filePath)

# 获取sheet的汇总数据
sheet1 = x1.sheet_by_name("plan")
print "sheet name:", sheet1.name   # get sheet name
print "row num:", sheet1.nrows  # get sheet all rows number
print "col num:", sheet1.ncols  # get sheet all columns number

输出:

sheet name: plan
row num: 31
col num: 11

资料:https://www.yisu.com/article/239873.htm

怎么用Python处理excel表格中的数据

https://www.yisu.com/article/187025.htm

怎么用Python处理excel表格中的数据

二、提高

三、出错

1.无法打开.xlsx文件 pandas无法打开.xlsx文件,xlrd.biffh.XLRDError: Excel xlsx file; not supported

安装的版本太高,低版本支持

可以安装旧版xlrd,在cmd中运行:

pip uninstall xlrd
pip install xlrd==1.2.0

也可以用openpyxl代替xlrd打开.xlsx文件:

df=pandas.read_excel(‘data.xlsx',engine=‘openpyxl')

以上是“怎么用Python处理excel表格中的数据”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI