Python处理excel数据

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python处理excel数据

行走的算法   2022-05-23 我要评论

一、基础、常用方法

1. 读取excel

1、导入模块:

import xlrd

2、打开文件:

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

3、获取sheet:

sheet是指工作表的名称,因为一个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:

https:

二、提高

三、出错

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')

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们