python使用xlrd与xlwt对excel的读写和格式设定

yipeiwu_com6年前Python基础

前言

python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。本文主要介绍了python使用xlrd与xlwt对excel的读写和格式设定,下面话不多说,来看看详细的实现过程。

脚本里先注明# -*- coding:utf-8 -*-   

1.  确认源excel存在并用xlrd读取第一个表单中每行的第一列的数值。

import xlrd, xlwt 
import os 
 
assert os.path.isfile('source_excel.xls'),"There is no timesheet exist. Exit..." 
 
book = xlrd.open_workbook('source_excel.xls') 
sheet=book.sheet_by_index(0) 
 
for rows in range(sheet.nrows): 
 value = sheet.cell(rows,0).value 

2. 用xlwt准备将从源表中读出的数据写入新表,并设定行宽和表格的格式。合并单元格2行8列后写入标题,并设定格式为之前定义的tittle_style。

使用的是write_merge。

wbk = xlwt.Workbook(encoding='utf-8') 
sheet_w = wbk.add_sheet('write_after', cell_overwrite_ok=True) 
sheet_w.col(3).width = 5000 
tittle_style = xlwt.easyxf('font: height 300, name SimSun, colour_index red, bold on; align: wrap on, vert centre, horiz center;') 
sheet_w.write_merge(0,2,0,8,u'这是标题',tittle_style) 

3. 当函数中要用到全局变量时,注意加global。否则会出现UnboundLocalError:local variable'xxx' referenced before assignment.

check_num = 0 
 
def check_data(sheet): 
 global check_num 
 check_num=check_num+1 

4. 写入日期和带格式的数值。原来从sheet中读取的日期格式为2014/4/10,处理后只保留日期并做成数组用逗号分隔后写入新的excel。

date_arr = [] 
date=sheet.cell(row,2).value.rsplit('/')[-1] 
if date not in date_arr: 
  date_arr.append(date) 
sheet_w.write_merge(row2,row2,6,6,date_num, normal_style) 
sheet_w.write_merge(row2,row2,7,7,','.join(date_arr), normal_style) 

5. 当从excel中读取的日期格式为xldate时,就需要使用xlrd的xldate_as_tuple来处理为date格式。先判断表格的ctype确实是xldate才能开始操作,否则会报错。之后date格式可以使用strftime来转化为string。如:date.strftime("%Y-%m-%d-%H")

from datetime import date,datetime 
from xlrd import xldate_as_tuple 
 
if (sheet.cell(rows,3).ctype == 3): 
  num=num+1 
  date_value = xldate_as_tuple(sheet.cell_value(rows,3),book.datemode) 
  date_tmp = date(*date_value[:3]).strftime("%d") 

6. 最后保存新写的表

wbk.save('new_excel.xls') 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

相关文章

Python批量修改文件后缀的方法

Python批量修改文件后缀的方法

近期下载了很多各种教程, 但是不幸的是后缀名都是 ".mp4", 而本人喜欢 ".rmvb" 后缀,由于有轻微洁癖, 受不了后面的 ".mp4" 缀, 但是手动修改又太过繁琐, 所以用近...

使用python实现简单五子棋游戏

使用python实现简单五子棋游戏

用python实现五子棋简单人机模式的练习过程,供大家参考,具体内容如下 第一次写博客,我尽力把它写好。 最近在初学python,今天就用自己的一些粗浅理解,来记录一下这几天的pytho...

详解Python map函数及Python map()函数的用法

详解Python map函数及Python map()函数的用法

python map函数 map()函数 map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到...

Python中os和shutil模块实用方法集锦

复制代码 代码如下:# os 模块os.sep 可以取代操作系统特定的路径分隔符。windows下为 '\\'os.name 字符串指示你正在使用的平台。比如对于Wi...

python使用itchat实现手机控制电脑

python使用itchat实现手机控制电脑

本文实例为大家分享了python使用itchat实现手机控制电脑的具体代码,供大家参考,具体内容如下 1.准备材料 首先电脑上需要安装了python,安装了opencv更好(非必需) 如...