前言
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')
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】