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装饰器使用实例:验证参数合法性
Jun 24 Python
python获取局域网占带宽最大3个ip的方法
Jul 09 Python
python编写朴素贝叶斯用于文本分类
Dec 21 Python
wxPython实现窗口用图片做背景
Apr 25 Python
Python数据类型之Number数字操作实例详解
May 08 Python
ML神器:sklearn的快速使用及入门
Jul 11 Python
Python3 chardet模块查看编码格式的例子
Aug 14 Python
Python多线程thread及模块使用实例
Apr 28 Python
解决Python Matplotlib绘图数据点位置错乱问题
May 16 Python
.img/.hdr格式转.nii格式的操作
Jul 01 Python
python 如何调用远程接口
Sep 11 Python
Python txt文件如何转换成字典
Nov 03 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
Yii框架在页面输出执行sql语句以方便调试的实现方法
2014/12/24 PHP
编写Js代码要注意的几条规则
2010/09/10 Javascript
jquery自定义类似$.ajax()的方法实现代码
2013/08/13 Javascript
常见浏览器多长时间会提示“脚本运行时间过长”总结
2014/04/29 Javascript
javascript中Math.random()使用详解
2015/04/15 Javascript
jquery动态增加删减表格行特效
2015/11/20 Javascript
JavaScript面试开发常用的知识点总结
2016/08/08 Javascript
RGB和YUV 多媒体编程基础详细介绍
2016/11/04 Javascript
关于Vue.js一些问题和思考学习笔记(1)
2016/12/02 Javascript
vue.js实现请求数据的方法示例
2017/02/07 Javascript
Vue.js原理分析之observer模块详解
2017/02/17 Javascript
详解vue-cli脚手架build目录中的dev-server.js配置文件
2017/11/24 Javascript
vue中简单弹框dialog的实现方法
2018/02/26 Javascript
vue-router权限控制(简单方式)
2018/10/29 Javascript
js String.prototype.trim字符去前后空格的扩展
2020/08/23 Javascript
vue cli4.0项目引入typescript的方法
2020/07/17 Javascript
[01:01:52]完美世界DOTA2联赛PWL S2 GXR vs Magma 第二场 11.25
2020/11/26 DOTA
使用python提取html文件中的特定数据的实现代码
2013/03/24 Python
python模块restful使用方法实例
2013/12/10 Python
CSS3常用的几种颜色渐变模式总结
2016/11/18 HTML / CSS
HTML5 本地存储之如果没有数据库究竟会怎样
2013/04/25 HTML / CSS
斯凯奇澳大利亚官网:SKECHERS澳大利亚
2018/03/31 全球购物
意大利巧克力店:Chocolate Shop
2019/07/24 全球购物
试用期转正鉴定评语
2014/01/27 职场文书
年度评优评先方案
2014/06/03 职场文书
重大事项社会稳定风险评估方案
2014/06/15 职场文书
自我介绍演讲稿范文
2014/08/21 职场文书
小学教师2014年度工作总结
2014/12/03 职场文书
2014保险公司个人工作总结
2014/12/09 职场文书
离职感谢信怎么写
2015/01/22 职场文书
全国助残日活动总结
2015/05/11 职场文书
海上钢琴师观后感
2015/06/03 职场文书
创业计划书之酒厂
2019/10/14 职场文书
Python使用protobuf序列化和反序列化的实现
2021/05/19 Python
Django实现聊天机器人
2021/05/31 Python
win10双系统怎么删除一个系统?win10电脑有两个系统删除一个的操作方法
2022/07/15 数码科技