python设置excel的格式_python使用xlrd与xlwt对excel的读写和格式设定
前言
python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。本文主要介紹了python使用xlrd與xlwt對excel的讀寫和格式設定,下面話不多說,來看看詳細的實現過程。
腳本里先注明# -*- coding:utf-8 -*-
1. 確認源excel存在并用xlrd讀取第一個表單中每行的第一列的數值。
1
2
3
4
5
6
7
8
9
10
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 rowsin range(sheet.nrows):
value= sheet.cell(rows,0).value
2. 用xlwt準備將從源表中讀出的數據寫入新表,并設定行寬和表格的格式。合并單元格2行8列后寫入標題,并設定格式為之前定義的tittle_style。
使用的是write_merge。
1
2
3
4
5
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.
1
2
3
4
5
check_num= 0
def check_data(sheet):
global check_num
check_num=check_num+1
4. 寫入日期和帶格式的數值。原來從sheet中讀取的日期格式為2014/4/10,處理后只保留日期并做成數組用逗號分隔后寫入新的excel。
1
2
3
4
5
6
date_arr= []
date=sheet.cell(row,2).value.rsplit('/')[-1]
if datenot 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")
1
2
3
4
5
6
7
from datetimeimport date,datetime
from xlrdimport 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. 最后保存新寫的表
1
wbk.save('new_excel.xls')
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
總結
以上是生活随笔為你收集整理的python设置excel的格式_python使用xlrd与xlwt对excel的读写和格式设定的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python增加工作日列_将工作日添加到
- 下一篇: 什么函数是回调函数?