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脚本实现12306火车票查询系统
Sep 30 Python
python制作websocket服务器实例分享
Nov 20 Python
深入理解 Python 中的多线程 新手必看
Nov 20 Python
Python pymongo模块用法示例
Mar 31 Python
快速解决安装python没有scripts文件夹的问题
Apr 03 Python
在VS Code上搭建Python开发环境的方法
Apr 06 Python
Python实现基于POS算法的区块链
Aug 07 Python
python 列表递归求和、计数、求最大元素的实例
Nov 28 Python
在Python中预先初始化列表内容和长度的实现
Nov 28 Python
Python栈的实现方法示例【列表、单链表】
Feb 22 Python
tensorflow常用函数API介绍
Apr 19 Python
用Python自动清理系统垃圾的实现
Jan 18 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测试成功的邮件发送案例
2015/10/26 PHP
PHP实现的线索二叉树及二叉树遍历方法详解
2016/04/25 PHP
判断多个元素(RADIO,CHECKBOX等)是否被选择的原理说明
2009/02/18 Javascript
js抽奖实现随机抽奖代码效果
2013/12/02 Javascript
深入分析jQuery的ready函数是如何工作的(工作原理)
2015/12/17 Javascript
js仿百度登录页实现拖动窗口效果
2016/03/11 Javascript
JavaScript必知必会(七)js对象继承
2016/06/08 Javascript
用JavaScript获取页面文档内容的实现代码
2016/06/10 Javascript
js实现界面向原生界面发消息并跳转功能
2016/11/22 Javascript
angular或者js怎么确定选中ul中的哪几个li
2017/08/16 Javascript
jQuery轻量级表单模型验证插件
2018/10/15 jQuery
JavaScript惰性载入函数实例分析
2019/03/27 Javascript
详解Vue中使用Axios拦截器
2019/04/22 Javascript
Vue分页效果与购物车功能
2019/12/13 Javascript
vue fetch中的.then()的正确使用方法
2020/04/17 Javascript
微信小程序自定义yPicker组件实现省市区三级联动功能
2020/10/29 Javascript
[01:06:54]DOTA2-DPC中国联赛 正赛 SAG vs DLG BO3 第二场 2月28日
2021/03/11 DOTA
Python排序搜索基本算法之堆排序实例详解
2017/12/08 Python
python实现嵌套列表平铺的两种方法
2018/11/08 Python
详解python校验SQL脚本命名规则
2019/03/22 Python
python装饰器代替set get方法实例
2019/12/19 Python
Python 中的pygame安装与配置教程详解
2020/02/10 Python
python 使用递归的方式实现语义图片分割功能
2020/07/16 Python
python logging模块的使用
2020/09/07 Python
Python SQLAlchemy库的使用方法
2020/10/13 Python
python邮件中附加文字、html、图片、附件实现方法
2021/01/04 Python
世界著名的顶级牛排:Omaha Steak(奥马哈牛排)
2016/09/20 全球购物
欧洲、亚洲、非洲和拉丁美洲的度假套餐:Great Value Vacations
2019/03/30 全球购物
安全生产先进个人材料
2014/02/06 职场文书
八项规定整改措施
2014/02/12 职场文书
怎么写好自荐书
2014/03/02 职场文书
中标通知书
2015/04/17 职场文书
2015年幼儿园中班下学期工作总结
2015/05/22 职场文书
安全学习心得体会范文
2016/01/18 职场文书
关于HTML编码导致的乱码问题
2021/09/04 HTML / CSS
详解Go语言中Get/Post请求测试
2022/06/01 Golang