一、基础、常用方法
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)
import xlrd
import os
filename = "demo.xlsx"
filePath = os.path.join(os.getcwd(), filename)
print filePath
x1 = xlrd.open_workbook(filePath)
print 'sheet_names:', x1.sheet_names()
print 'sheet_number:', x1.nsheets
print 'sheet_object:', x1.sheets()
print 'By_name:', x1.sheet_by_name("test")
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
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)
sheet1 = x1.sheet_by_name("plan")
print "sheet name:", sheet1.name
print "row num:", sheet1.nrows
print "col num:", sheet1.ncols
输出:
sheet name: plan
row num: 31
col num: 11
资料
- https://www.cnblogs.com/zhang-jun-jie/p/9273721.html
- https://www.cnblogs.com/insane-Mr-Li/p/9092619.html
二、提高
三、出错
1.无法打开.xlsx文件
- pandas无法打开.xlsx文件,xlrd.biffh.XLRDError: Excel xlsx file; not supported
安装的版本太高,低版本支持 https://blog.csdn.net/weixin_44073728/article/details/111054157
|