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 相关文章推荐
Pyhton中防止SQL注入的方法
Feb 05 Python
Python在不同目录下导入模块的实现方法
Oct 27 Python
Python实现识别手写数字 Python图片读入与处理
Mar 23 Python
使用django-guardian实现django-admin的行级权限控制的方法
Oct 30 Python
python程序控制NAO机器人行走
Apr 29 Python
Python 正则表达式爬虫使用案例解析
Sep 23 Python
python 实现图片上传接口开发 并生成可以访问的图片url
Dec 18 Python
Python matplotlib可视化实例解析
Jun 01 Python
pycharm设置默认的UTF-8编码模式的方法详解
Jun 01 Python
Python实现寻找回文数字过程解析
Jun 09 Python
在CentOS7下安装Python3教程解析
Jul 09 Python
Python可视化学习之matplotlib内置单颜色
Feb 24 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
解析PHP将对象转换成数组的方法(兼容多维数组类型)
2013/06/21 PHP
php防止sql注入的方法详解
2017/02/20 PHP
javascript获取当前日期时间及其它操作函数
2011/01/11 Javascript
jquery中ajax学习笔记一
2011/10/16 Javascript
js获取当月最后一天实例代码
2013/11/19 Javascript
Javascript代码实现仿实例化类
2015/04/03 Javascript
JavaScript实现强制重定向至HTTPS页面
2015/06/10 Javascript
基于百度地图实现产品销售的单位位置查看功能设计与实现
2016/10/21 Javascript
ionic开发中点击input时键盘自动弹出
2016/12/23 Javascript
js获取浏览器和屏幕的各种宽度高度
2017/02/22 Javascript
JavaScript创建对象的常用方式总结
2018/08/10 Javascript
JS添加或删除HTML dom元素的方法实例分析
2019/03/05 Javascript
vue-model实现简易计算器
2020/08/17 Javascript
windows如何把已安装的nodejs高版本降级为低版本(图文教程)
2020/12/14 NodeJs
[02:47]3.19DOTA2发布会 国服成长历程回顾
2014/03/25 DOTA
使用python实现baidu hi自动登录的代码
2013/02/10 Python
解决pip install的时候报错timed out的问题
2018/06/12 Python
python-itchat 获取微信群用户信息的实例
2019/02/21 Python
Django处理多用户类型的方法介绍
2019/05/18 Python
pytorch梯度剪裁方式
2020/02/04 Python
python属于解释语言吗
2020/06/11 Python
可自定义箭头样式的CSS3气泡提示框
2016/03/16 HTML / CSS
时尚设计师手表:The Watch Cabin
2018/10/06 全球购物
保卫科工作岗位职责
2014/03/01 职场文书
店面销售职位的职责
2014/03/09 职场文书
工伤事故赔偿协议书
2014/04/15 职场文书
中学教师暑期培训方案
2014/08/27 职场文书
2014年银行员工年终自我评价
2014/09/19 职场文书
二手房购房意向书
2015/05/09 职场文书
企业催款函范本
2015/06/24 职场文书
中学生国庆节演讲稿2015
2015/07/30 职场文书
幼儿园小班教师随笔
2015/08/14 职场文书
小学生安全教育心得体会
2016/01/15 职场文书
Python中使用Lambda函数的5种用法
2021/04/01 Python
OpenCV项目实践之停车场车位实时检测
2022/04/11 Python
微软Win11 全新照片应用面向 Dev预览版推出 新版本上手体验图集
2022/09/23 数码科技