Python简单读写Xls格式文档的方法示例


Posted in Python onAugust 17, 2018

本文实例讲述了Python简单读写Xls格式文档的方法。分享给大家供大家参考,具体如下:

1. 模块安装

使用pip install命令安装,
即:

pip install xlrd
pip install xlwt

如下图:

Python简单读写Xls格式文档的方法示例

Python简单读写Xls格式文档的方法示例

2. python 代码

import xlrd
import xlwt
import datetime 
def set_style(name,height,format,bold=False):
  style = xlwt.XFStyle()
  if format.strip()!='':
    style.num_format_str =format
  font = xlwt.Font()
  font.name=name
  font.bold=bold
  font.color_index=4
  font.height=height
  alignment = xlwt.Alignment()
  #HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
  alignment.horz = xlwt.Alignment.HORZ_CENTER
  #VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
  alignment.vert = xlwt.Alignment.VERT_CENTER
  style.alignment = alignment
  style.font=font
  return style
def set_colstyle(sheet,cindex):
  col=sheet.col(cindex)
  col.width =256*20
  #col.height =100
def writeXls(path):
  wb = xlwt.Workbook()
  sheet = wb.add_sheet('测试',cell_overwrite_ok=True)
  set_colstyle(sheet,3)
  #标题
  heads=['姓名','学科','分数','日期']
  for h in range(0,len(heads)):
    sheet.write(0,h,heads[h],set_style('Arial',300,'',True))
  #数据
  sheet.write_merge(1,2,0,0,'张三',set_style('Arial',300,'',False))
  sheet.write(1,1,'语文',set_style('Arial',240,'',False))
  sheet.write(1,2,85,set_style('Arial',240,'',False))
  sheet.write(1,3,datetime.date.today(),set_style('Arial',240,'yyyy/mm/dd',False))
  sheet.write(2,1,'数学',set_style('Arial',240,'',False))
  sheet.write(2,2,85,set_style('Arial',240,'',False))
  sheet.write(2,3,datetime.date.today(),set_style('Arial',240,'yyyy/mm/dd',False))
  sheet.write_merge(3,4,0,0,'李四',set_style('Arial',300,'',False))
  sheet.write(3,1,'语文',set_style('Arial',240,'',False))
  sheet.write(3,2,95,set_style('Arial',240,'',False))
  sheet.write(3,3,datetime.date.today(),set_style('Arial',240,'yyyy/mm/dd',False))
  sheet.write(4,1,'数学',set_style('Arial',240,'',False))
  sheet.write(4,2,95,set_style('Arial',240,'',False))
  sheet.write(4,3,datetime.date.today(),set_style('Arial',240,'yyyy/mm/dd',False))
  wb.save(path)
def ismerge(sheet,merge,r,c):
  #merge=sheet.merged_cells
  for m in merge:
    if r>=m[0] and r<m[1] and c==m[2]:
      r=m[0]
      c==m[2]
      break
  return r,c
def readXls(path):
  wb=xlrd.open_workbook(path,formatting_info=True)
  #sheetname=wb.sheet_names()[0]
  sheet=wb.sheet_by_index(0)
  rows=sheet.nrows
  cols=sheet.ncols
  merge=sheet.merged_cells
  #merged_cells返回的这四个参数的含义是:(row,row_range,col,col_range),
  #其中[row,row_range)包括row,不包括row_range
  print('--------------------------------------------------------------------')
  for r in range(0,rows):
    listStr = []
    for c in range(0,cols):
      merg=ismerge(sheet,merge,r,c)
      if (sheet.cell(merg[0],merg[1]).ctype==3):
        data_value=xlrd.xldate_as_tuple(sheet.cell_value(merg[0],merg[1]),wb.datemode)
        #print(datetime.date(*data_value[:3]).strftime('%Y/%m/%d'))
        listStr.append(datetime.date(*data_value[:3]).strftime('%Y/%m/%d'))
      else:
        #print(sheet.cell_value(merg[0],merg[1]))
        listStr.append(sheet.cell_value(merg[0],merg[1]))
      #print(sheet.cell(merg[0],merg[1]).value)
      #print(sheet.cell(r,c).ctype)
    print(' |\t'.join(str(s) for s in listStr if s not in [None]))
    print('--------------------------------------------------------------------')
if __name__ == '__main__':
  #writeXls('H:\测试.xls')
  readXls('H:\测试.xls')

3.效果展示

Python简单读写Xls格式文档的方法示例

Python简单读写Xls格式文档的方法示例

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python实现将HTML转成PDF的方法分析
May 04 Python
Python 使用 attrs 和 cattrs 实现面向对象编程的实践
Jun 12 Python
python3 selenium自动化 frame表单嵌套的切换方法
Aug 23 Python
python中使用you-get库批量在线下载bilibili视频的教程
Mar 10 Python
Django如何在不停机的情况下创建索引
Aug 02 Python
python实现暗通道去雾算法的示例
Sep 27 Python
Django+Django-Celery+Celery的整合实战
Jan 20 Python
python爬虫--selenium模块
Mar 31 Python
Python利器openpyxl之操作excel表格
Apr 17 Python
Python的这些库,你知道多少?
Jun 09 Python
Python游戏开发实例之graphics实现AI五子棋
Nov 01 Python
Python使用openpyxl模块处理Excel文件
Jun 05 Python
Python实现的连接mssql数据库操作示例
Aug 17 #Python
Python SQL查询并生成json文件操作示例
Aug 17 #Python
python3 flask实现文件上传功能
Mar 20 #Python
Python爬取qq空间说说的实例代码
Aug 17 #Python
django进阶之cookie和session的使用示例
Aug 17 #Python
Django 登陆验证码和中间件的实现
Aug 17 #Python
python读取Excel实例详解
Aug 17 #Python
You might like
配置Apache2.2+PHP5+CakePHP1.2+MySQL5运行环境
2009/04/25 PHP
php实现购物车功能(下)
2016/01/05 PHP
php常用数组array函数实例总结【赋值,拆分,合并,计算,添加,删除,查询,判断,排序】
2016/12/07 PHP
不常用但很实用的PHP预定义变量分析
2019/06/25 PHP
jquery默认校验规则整理
2014/03/24 Javascript
js闭包所用的场合以及优缺点分析
2015/06/22 Javascript
jQuery在线选座位插件seat-charts特效代码分享
2015/08/27 Javascript
第五章之BootStrap 栅格系统
2016/04/25 Javascript
vuejs2.0运用原生js实现简单的拖拽元素功能示例
2017/02/24 Javascript
JavaScript通过filereader接口读取文件
2017/05/10 Javascript
Node.js  REPL (交互式解释器)实例详解
2017/08/06 Javascript
select标签设置默认选中的选项方法
2018/03/02 Javascript
详解vue的diff算法原理
2018/05/20 Javascript
用Node提供静态文件服务的方法
2018/07/06 Javascript
koa-router路由参数和前端路由的结合详解
2019/05/19 Javascript
微信小程序 多行文本显示...+显示更多按钮和收起更多按钮功能
2019/09/26 Javascript
javascript操作元素的常见方法小结
2019/11/13 Javascript
Vue+Element-UI实现上传图片并压缩
2019/11/26 Javascript
微信小程序如何加载数据库真实数据的实现
2020/03/04 Javascript
Vue双向绑定实现原理与方法详解
2020/05/07 Javascript
[45:25]完美世界DOTA2联赛循环赛 PXG vs IO 第一场 11.06
2020/11/09 DOTA
python复制文件代码实现
2013/12/23 Python
python3模拟百度登录并实现百度贴吧签到示例分享(百度贴吧自动签到)
2014/02/24 Python
Python 模拟登陆的两种实现方法
2017/08/10 Python
Python多进程与服务器并发原理及用法实例分析
2018/08/21 Python
Python设计模式之享元模式原理与用法实例分析
2019/01/11 Python
Python常见数据结构之栈与队列用法示例
2019/01/14 Python
pandas 对日期类型数据的处理方法详解
2019/08/08 Python
Python 格式化打印json数据方法(展开状态)
2020/02/27 Python
SportsDirect.com马来西亚:英国第一体育零售商
2018/11/21 全球购物
双立人美国官方商店:ZWILLING集团餐具和炊具
2020/05/07 全球购物
三年级科学教学反思
2014/01/29 职场文书
运动会解说词200字
2014/02/06 职场文书
家电业务员岗位职责
2014/03/10 职场文书
春季运动会开幕词
2015/01/28 职场文书
幼儿园中班教育随笔
2015/08/14 职场文书