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使用webbrowser浏览指定url的方法
Apr 04 Python
Python中使用pprint函数进行格式化输出的教程
Apr 07 Python
用python写扫雷游戏实例代码分享
May 27 Python
解决PyCharm不运行脚本,而是运行单元测试的问题
Jan 17 Python
python实现简单聊天室功能 可以私聊
Jul 12 Python
django 类视图的使用方法详解
Jul 24 Python
python实现图片插入文字
Nov 26 Python
使用Python 自动生成 Word 文档的教程
Feb 13 Python
Python代码一键转Jar包及Java调用Python新姿势
Mar 10 Python
python 如何调用 dubbo 接口
Sep 24 Python
Python Pandas读取Excel日期数据的异常处理方法
Feb 28 Python
Python中re模块的元字符使用小结
Apr 07 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中“简单工厂模式”实例代码讲解
2012/09/04 PHP
php实现图形显示Ip地址的代码及注释
2014/01/20 PHP
smarty缓存用法分析
2014/12/16 PHP
改写一个简单的菜单 弹性大小
2010/12/02 Javascript
javascript计算用户打开网页的停留时间
2014/01/09 Javascript
jQuery中:checkbox选择器用法实例
2015/01/03 Javascript
Bootstrap3学习笔记(三)之表格
2016/05/20 Javascript
vue双向绑定的简单实现
2016/12/22 Javascript
BootStrap Table 设置height表头与内容无法对齐的问题
2016/12/28 Javascript
基于jQuery实现简单人工智能聊天室
2017/02/10 Javascript
jQuery实现文章图片弹出放大效果
2017/04/06 jQuery
jQuery异步提交表单实例
2017/05/30 jQuery
基于jquery日历价格、库存等设置插件
2020/07/05 jQuery
jQuery实现返回顶部按钮和scroll滚动功能[带动画效果]
2017/07/05 jQuery
JS+H5 Canvas实现时钟效果
2018/07/20 Javascript
jQuery实现判断滚动条滚动到document底部的方法分析
2019/08/27 jQuery
Python中MySQLdb和torndb模块对MySQL的断连问题处理
2015/11/09 Python
解决python文件字符串转列表时遇到空行的问题
2017/07/09 Python
Python 读写文件的操作代码
2018/09/20 Python
关于python下cv.waitKey无响应的原因及解决方法
2019/01/10 Python
python实现剪切功能
2019/01/23 Python
使用python的pexpect模块,实现远程免密登录的示例
2019/02/14 Python
Django 实现admin后台显示图片缩略图的例子
2019/07/28 Python
Django框架中序列化和反序列化的例子
2019/08/06 Python
Python爬虫图片懒加载技术 selenium和PhantomJS解析
2019/09/18 Python
使用python求斐波那契数列中第n个数的值示例代码
2020/07/26 Python
Pycharm 跳转回之前所在页面的操作
2021/02/05 Python
基于css3实现漂亮便签样式
2013/03/18 HTML / CSS
澳大利亚礼品篮网站:Macarthur Baskets
2019/10/14 全球购物
物业管理应届生求职信
2013/10/28 职场文书
后勤部长岗位职责
2013/12/14 职场文书
全民健身日活动方案
2014/01/29 职场文书
夫妻分居协议书范文
2014/11/26 职场文书
工厂采购员岗位职责
2015/04/07 职场文书
党员心得体会范文2016
2016/01/23 职场文书
Python matplotlib 利用随机函数生成变化图形
2022/04/26 Python