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爬虫之抓取糗事百科代码分享
Nov 06 Python
探究Python中isalnum()方法的使用
May 18 Python
TensorFlow实现Logistic回归
Sep 07 Python
Selenium定时刷新网页的实现代码
Oct 31 Python
python实现名片管理系统
Nov 29 Python
python2和python3在处理字符串上的区别详解
May 29 Python
Djang的model创建的字段和参数详解
Jul 27 Python
利用python list完成最简单的DB连接池方法
Aug 09 Python
opencv 图像滤波(均值,方框,高斯,中值)
Jul 08 Python
django rest framework 自定义返回方式
Jul 12 Python
python中温度单位转换的实例方法
Dec 27 Python
python实现调用摄像头并拍照发邮箱
Apr 27 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
山进SANGEAN ATS-909X电路分析
2021/03/02 无线电
php下使用iconv需要注意的问题
2010/11/20 PHP
PHP学习笔记(二):变量详解
2015/04/17 PHP
Javascript MD4
2006/12/20 Javascript
JAVASCRIPT style 中visibility和display之间的区别
2010/01/22 Javascript
javascript 解析url的search方法
2010/02/09 Javascript
js分解url参数(面向对象-极简主义法应用)
2012/08/09 Javascript
对table和ul实现js分页示例分享
2014/02/24 Javascript
全面兼容的javascript时间格式化函数(比较实用)
2014/05/14 Javascript
第一章之初识Bootstrap
2016/04/25 Javascript
浅析Javascript中bind()方法的使用与实现
2016/04/29 Javascript
微信小程序新增的拖动组件movable-view使用教程
2017/05/20 Javascript
Vue.js 踩坑记之双向绑定
2018/05/03 Javascript
bootstrap treeview 树形菜单带复选框及级联选择功能
2018/06/08 Javascript
Vue常用指令详解分析
2018/08/19 Javascript
JS实现简单的点赞与踩功能示例
2018/12/05 Javascript
jQuery实现开关灯效果
2020/08/02 jQuery
微信小程序连续签到7天积分获得功能的示例代码
2020/08/20 Javascript
[01:04:39]OG vs Mineski 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
[53:10]Secret vs Pain 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
python解析json实例方法
2013/11/19 Python
Python HTTP客户端自定义Cookie实现实例
2017/04/28 Python
python正则实现计算器功能
2017/12/14 Python
python实现远程控制电脑
2019/05/23 Python
Python如何调用外部系统命令
2019/08/07 Python
Python图像处理库PIL的ImageEnhance模块使用介绍
2020/02/26 Python
一文带你了解Python 四种常见基础爬虫方法介绍
2020/12/04 Python
目前不被任何主流浏览器支持的CSS3属性汇总
2014/07/21 HTML / CSS
材料加工硕士生求职信
2013/10/10 职场文书
劳资员岗位职责
2013/11/11 职场文书
表扬信格式
2014/01/12 职场文书
大学生创业策划书
2014/02/02 职场文书
生产现场禁烟通知
2015/04/23 职场文书
运动会广播稿50字
2015/08/19 职场文书
详解Vue项目的打包方式(生成dist文件)
2022/01/18 Vue.js
Redis批量生成数据的实现
2022/06/05 Redis