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网络编程学习笔记(10):webpy框架
Jun 09 Python
python计算方程式根的方法
May 07 Python
Python中List.index()方法的使用教程
May 20 Python
总结python爬虫抓站的实用技巧
Aug 09 Python
python用户管理系统的实例讲解
Dec 23 Python
python使用socket创建tcp服务器和客户端
Apr 12 Python
python-itchat 统计微信群、好友数量,及原始消息数据的实例
Feb 21 Python
python检查目录文件权限并修改目录文件权限的操作
Mar 11 Python
Python多进程编程常用方法解析
Mar 26 Python
PyCharm设置Ipython交互环境和宏快捷键进行数据分析图文详解
Apr 23 Python
Python接口测试结果集实现封装比较
May 01 Python
python高级特性简介
Aug 13 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
第五节 克隆 [5]
2006/10/09 PHP
PHP输出图像imagegif、imagejpeg与imagepng函数用法分析
2016/11/14 PHP
Thinkphp 框架扩展之Widget扩展实现方法分析
2020/04/23 PHP
Mootools 1.2教程(21)——类(二)
2009/09/15 Javascript
深入理解JSON数据源格式
2014/01/10 Javascript
自己使用js/jquery写的一个定制对话框控件
2014/05/02 Javascript
Linux下使用jq友好的打印JSON技巧分享
2014/11/18 Javascript
angularJS 中$attrs方法使用指南
2015/02/09 Javascript
JavaScript计算某一天是星期几的方法
2015/08/05 Javascript
javascript跨域总结之window.name实现的跨域数据传输
2015/11/01 Javascript
JavaScript原型链与继承操作实例总结
2018/08/24 Javascript
详解如何使用router-link对象方式传递参数?
2019/05/02 Javascript
vue自定义插件封装,实现简易的elementUi的Message和MessageBox的示例
2020/11/20 Vue.js
jquery实现图片放大镜效果
2020/12/23 jQuery
[03:46]显微镜下的DOTA2第七期——满血与残血
2014/06/20 DOTA
[00:48]食人魔魔法师至宝“金鹏之幸”全新模型和自定义特效展示
2019/12/19 DOTA
python处理csv中的空值方法
2018/06/22 Python
pandas 按照特定顺序输出的实现代码
2018/07/10 Python
python内存监控工具memory_profiler和guppy的用法详解
2019/07/29 Python
在django中自定义字段Field详解
2019/12/03 Python
pytorch构建多模型实例
2020/01/15 Python
关于Python字符串显示u...的解决方式
2020/03/06 Python
Selenium使用Chrome模拟手机浏览器方法解析
2020/04/10 Python
keras topN显示,自编写代码案例
2020/07/03 Python
pycharm 配置svn的图文教程(手把手教你)
2021/01/15 Python
HTML5新特性之type=file文件上传功能
2018/02/02 HTML / CSS
美国钻石商店:Zales
2016/11/20 全球购物
ONLY德国官方在线商店:购买时尚女装
2017/09/21 全球购物
经贸日语专业个人求职信
2013/12/13 职场文书
初中毕业典礼演讲稿
2014/09/09 职场文书
专题民主生活会对照检查材料思想汇报
2014/09/29 职场文书
2014年基建工作总结
2014/12/12 职场文书
违纪检讨书
2015/01/27 职场文书
2015年党日活动总结范文
2015/03/25 职场文书
红十字会救护培训简讯
2015/07/20 职场文书
总结一下关于在Java8中使用stream流踩过的一些坑
2021/06/24 Java/Android