python使用xlrd與xlwt對excel的讀寫和格式設定

高洛峰
發布: 2017-02-20 10:48:26
原創
1885 人瀏覽過

最近在用python處理excel表的時候出現了一些問題,所以想著記錄下最後的實作方式和問題解決方法。方便自己或大家在有需要的時候參考借鑒,以下這篇文章主要就介紹了python使用xlrd與xlwt對excel的讀寫和格式設定的相關資料,一起來學習學習吧。

前言

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使用xlrd與xlwt對excel的讀寫和格式設定相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!