如何利用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 xlrdimport osfilename = "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: 4sheet_object: [, , , ]By_name: By_index:

4、获取sheet的汇总数据:
获取sheet名:sheet1.name
获取总行数:sheet1.nrows
获取总列数:sheet1.ncols
# -*- coding:utf-8 -*-import xlrdimport osfrom datetime import date,datetimefilename = "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 nameprint "row num:", sheet1.nrows# get sheet all rows numberprint "col num:", sheet1.ncols# get sheet all columns number

输出:
sheet name: plan
row num: 31
col num: 11
资料:https://www.jb51.net/article/239873.htm
如何利用Python处理excel表格中的数据
文章图片

https://www.jb51.net/article/187025.htm
如何利用Python处理excel表格中的数据
文章图片


二、提高
三、出错 1.无法打开.xlsx文件 pandas无法打开.xlsx文件,xlrd.biffh.XLRDError: Excel xlsx file; not supported
安装的版本太高,低版本支持
可以安装旧版xlrd,在cmd中运行:
pip uninstall xlrdpip install xlrd==1.2.0

也可以用openpyxl代替xlrd打开.xlsx文件:
df=pandas.read_excel(‘data.xlsx',engine=‘openpyxl')


总结 【如何利用Python处理excel表格中的数据】到此这篇关于如何利用Python处理excel表格中数据的文章就介绍到这了,更多相关Python处理excel数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读