Python读取xlsx文件的实现方法


Posted in Python onJuly 04, 2019

脚本如下:

from openpyxl import load_workbook

workbook = load_workbook(u'/tmp/test.xlsx')  #找到需要xlsx文件的位置
booksheet = workbook.active         #获取当前活跃的sheet,默认是第一个sheet

#如果想获取别的sheet页采取下面这种方式,先获取所有sheet页名,在通过指定那一页。
# sheets = workbook.get_sheet_names() # 从名称获取sheet
# booksheet = workbook.get_sheet_by_name(sheets[0])

#获取sheet页的行数据
rows = booksheet.rows
#获取sheet页的列数据
columns = booksheet.columns


i = 0
# 迭代所有的行
for row in rows:
  i = i + 1
  line = [col.value for col in row]
  cell_data_1 = booksheet.cell(row=i, column=3).value        #获取第i行1 列的数据
  cell_data_2 = booksheet.cell(row=i, column=4).value        #获取第i行 2 列的数据
  cell_data_3 = booksheet.cell(row=i, column=8).value          #获取第i行 3 列的数据
  cell_data_4 = booksheet.cell(row=i, column=18).value          #获取第i行 4 列的数据
  print (cell_data_1, cell_data_2, cell_data_3, cell_data_4)

实例:python读取excel数据做分类统计

某excel中记录了某个人的通话记录,下面程序将按照通话地点,通话类型等统计通话时间

# -*- coding:utf-8 -*-
import xlrd
import datetime
infos=[]
info_file=xlrd.open_workbook('src.xls')#打开excel文件
info_sheet=info_file.sheets()[0]#通过索引顺序获取工作表
row_count=info_sheet.nrows#获取行数,列数ncols
for row in range(1,row_count):
  time_string=info_sheet.cell(row,3).value
  time_s_sp=time_string.split(':')
  infos.append(#该数组里放了row_count个字典
    {
      'type':info_sheet.cell(row,2).value,#获取单元格,通话类型,主叫被叫
      'other_cellphone':info_sheet.cell(row,0).value,#对方号码,
      'timespan':datetime.timedelta(seconds=int(time_s_sp[2]),minutes=int(time_s_sp[1]),hours=int(time_s_sp[0])),
      'gpscity':info_sheet.cell(row,5).value#通话是本地还是外地
    }
  )
time_all=datetime.timedelta(seconds=0)#初始化
time_types={}
time_classes={}
time_numbers={}
for infor in infos:#取出该数组里的字典
  time_all +=infor['timespan']#求总通话次数
  infor_type=infor['type']
  if infor_type in time_types:
    time_types[infor_type]+=infor['timespan']
  else:
    time_types[infor_type]=infor['timespan']#按通话类型统计通话时间
  infor_class=infor['gpscity']
  if infor_class in time_classes:
    time_classes[infor_class]+=infor['timespan']
  else:
    time_classes[infor_class]=infor['timespan']#这里相当于先分类赋值再++,按归属地统计通话时间
  infor_number=infor['other_cellphone']
  if infor_number in time_numbers:
    time_numbers[infor_number]+=infor['timespan']
  else:
    time_numbers[infor_number]=infor['timespan']#根据号码统计通话时间

print '总通话时间:%s' % time_all
print
print '总通话方式分类'
for k,v in time_types.items():
  print k.encode('utf-8'),v
print
print '通话类型分类:'
for k,v in time_classes.items():
  print k.encode('utf-8'),v
print
print '对方号码分类:'
for k,v in time_numbers.items():
  print k,v

再优化下代码

# -*- coding:utf-8 -*-
import xlrd
from datetime import timedelta
def read_excel(file_excel):#读excel并将需要的数据分类放在数组里
  infos=[]
  info_file=xlrd.open_workbook(file_excel)
  info_sheet=info_file.sheets()[0]
  row_count=info_sheet.nrows
  for row in range(1,row_count):
    time_string=info_sheet.cell(row,3).value
    time_s_sp=time_string.split(':')
    infos.append(
      {
        'type':info_sheet.cell(row,2).value,
        'other_cellphone':info_sheet.cell(row,0).value,
        'timespan':timedelta(seconds=int(time_s_sp[2]),minutes=int(time_s_sp[1]),hours=int(time_s_sp[0])),
        'gpscity':info_sheet.cell(row,5).value

      }
    )
  return infos
def count_cell(list_dirs,infotype):#统计总通话及分类统计结果,存在字典里
  result_dir={}
  time_all=timedelta(seconds=0)
  for list_dir in list_dirs:
    time_all +=list_dir['timespan']
    info_type = list_dir[infotype]
    if info_type not in result_dir:
      result_dir[info_type]=list_dir['timespan']
    else:
      result_dir[info_type]+=list_dir['timespan']
  return time_all,result_dir
def print_result(result_dir):#打印数据
  for k,v in result_dir.items():
    print k.encode('utf-8'),v

if __name__=="__main__":
  list_dirs=read_excel('src.xls')
  time_all,result_type=count_cell(list_dirs,'type')
  result_cell=count_cell(list_dirs,'other_cellphone')
  result_gpscity = count_cell(list_dirs, 'gpscity')
  print '总通话时间:%s' % time_all
  print '按照通话类型分类:'
  print_result(result_type)
  print '按照号码分类:'
  print_result(result_cell[1])
  print '按照归属地分类:'
  print_result(result_gpscity[1])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
使用Python脚本来控制Windows Azure的简单教程
Apr 16 Python
深入解析Python设计模式编程中建造者模式的使用
Mar 02 Python
Python判断文件或文件夹是否存在的三种方法
Jul 27 Python
Python3中的列表,元组,字典,字符串相关知识小结
Nov 10 Python
使用Selenium破解新浪微博的四宫格验证码
Oct 19 Python
python之消除前缀重命名的方法
Oct 21 Python
Python进程,多进程,获取进程id,给子进程传递参数操作示例
Oct 11 Python
Python3.5 win10环境下导入kera/tensorflow报错的解决方法
Dec 19 Python
2020版Python学习路线图(附学习资料)
Sep 15 Python
Python 使用xlwt模块将多行多列数据循环写入excel文档的操作
Nov 10 Python
python 用pandas实现数据透视表功能
Dec 21 Python
matplotlib阶梯图的实现(step())
Mar 02 Python
使用python进行广告点击率的预测的实现
Jul 04 #Python
python命令行工具Click快速掌握
Jul 04 #Python
python 设置输出图像的像素大小方法
Jul 04 #Python
python变量命名的7条建议
Jul 04 #Python
Django生成PDF文档显示在网页上以及解决PDF中文显示乱码的问题
Jul 04 #Python
python批量修改图片尺寸,并保存指定路径的实现方法
Jul 04 #Python
python代理工具mitmproxy使用指南
Jul 04 #Python
You might like
丧钟首部独立剧集《丧钟:骑士与龙》北美正式开播,场面血腥
2020/04/09 欧美动漫
Zend Studio 无法启动的问题解决方法
2008/12/04 PHP
php split汉字
2009/06/05 PHP
php 判断访客是否为搜索引擎蜘蛛的函数代码
2011/07/29 PHP
PHP实现把文本中的URL转换为链接的auolink()函数分享
2014/07/29 PHP
JScript的条件编译
2007/05/29 Javascript
jQuery设置div一直在页面顶部显示的方法
2013/10/24 Javascript
jquery+css3打造一款ajax分页插件(自写)
2014/06/18 Javascript
JS 使用for循环遍历子节点查找元素
2014/09/06 Javascript
JQuery勾选指定name的复选框集合并显示的方法
2015/05/18 Javascript
jQuery实现TAB风格的全国省份城市滑动切换效果代码
2015/08/24 Javascript
javascript实现图片延迟加载方法汇总(三种方法)
2015/08/27 Javascript
javascript如何写热点图
2015/12/08 Javascript
JavaScript之iterable_动力节点Java学院整理
2017/06/29 Javascript
代码详解javascript模块加载器
2018/03/04 Javascript
React学习笔记之高阶组件应用
2018/06/02 Javascript
浅谈Vue.js 中的 v-on 事件指令的使用
2018/11/25 Javascript
详解微信图片防盗链“此图片来自微信公众平台 未经允许不得引用”的解决方案
2019/04/04 Javascript
Python转码问题的解决方法
2008/10/07 Python
Python重新引入被覆盖的自带function
2014/07/16 Python
python获取元素在数组中索引号的方法
2015/07/15 Python
Python实现将DOC文档转换为PDF的方法
2015/07/25 Python
Python入门必须知道的11个知识点
2018/03/21 Python
如何优雅地改进Django中的模板碎片缓存详解
2018/07/04 Python
Python微信操控itchat的方法
2019/05/31 Python
python tools实现视频的每一帧提取并保存
2020/03/20 Python
Django自定义用户表+自定义admin后台中的字段实例
2019/11/18 Python
销售员岗位职责范本
2014/02/03 职场文书
小学毕业典礼主持词
2014/03/27 职场文书
协议书样本
2014/04/23 职场文书
高中教师评语大全
2014/04/25 职场文书
机关领导干部作风整顿整改措施
2014/09/19 职场文书
行政执法作风整顿剖析材料
2014/10/11 职场文书
酒店工程部岗位职责
2015/02/12 职场文书
Nginx 负载均衡是什么以及该如何配置
2021/03/31 Servers
「地球外少年少女」BD发售宣传CM公开
2022/03/21 日漫