python處理excel表格

1、可以使用的第三方庫python

python中處理excel表格,經常使用的庫有xlrd(讀excel)表、xlwt(寫excel)表、openpyxl(可讀寫excel表)等。xlrd讀數據較大的excel表時效率高於openpyxl,因此我在寫腳本時就採用了xlrd和xlwt這兩個庫。介紹及下載地址爲:http://www.python-excel.org/ 這些庫文件都沒有提供修改現有excel表格內容的功能。通常只能將原excel中的內容讀出、作完處理後,再寫入一個新的excel文件。windows

2、常見問題函數

使用python處理excel表格時,發現兩個個比較難纏的問題:unicode編碼和excel中記錄的時間。編碼

由於python的默認字符編碼都爲unicode,因此打印從excel中讀出的中文或讀取中文名的excel表或sheet時,程序提示錯誤UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)。這是因爲在windows中,中文使用了gb2312編碼方式,python將其看成unicode和ascii來解碼都不正確才報出的錯誤。使用VAR.encode('gb2312')便可解決打印中文的問題。(很奇怪,有的時候雖然能打印出結果,但顯示的不是中文,而是一堆編碼。)若要從中文文件名的excel表中讀取數據,可在文件名前加‘u’表示將該中文文件名採用unicode編碼。excel

有excel中,時間和日期都使用浮點數表示。可看到,當‘2013年3月20日’所在單元格使用‘常規’格式表示後,內容變爲‘41353’;當其單元格格式改變爲日期後,內容又變爲了‘2013年3月20日’。而使用xlrd讀出excel中的日期和時間後,獲得是的一個浮點數。因此當向excel中寫入的日期和時間爲一個浮點數也沒關係,只需將表格的表示方式改成日期和時間,便可獲得正常的表示方式。excel中,用浮點數1表示1899年12月31日。code

3、經常使用函數blog

如下主要介紹xlrd、xlwt、datetime中與日期相關的函數。ci

import xlrd
import xlwt
from datetime

def testXlrd(filename):
    book=xlrd.open_workbook(filename)
    sh=book.sheet_by_index(0)
    print "Worksheet name(s): ",book.sheet_names()[0]
    print 'book.nsheets',book.nsheets
    print 'sh.name:',sh.name,'sh.nrows:',sh.nrows,'sh.ncols:',sh.ncols
    print 'A1:',sh.cell_value(rowx=0,colx=1)
    #若是A3的內容爲中文
    print 'A2:',sh.cell_value(0,2).encode('gb2312')

def testXlwt(filename):
    book=xlwt.Workbook()
    sheet1=book.add_sheet('hello')
    book.add_sheet('word')
    sheet1.write(0,0,'hello')
    sheet1.write(0,1,'world')
    row1 = sheet1.row(1)
    row1.write(0,'A2')
    row1.write(1,'B2')
    
    sheet1.col(0).width = 10000
    
    sheet2 = book.get_sheet(1)
    sheet2.row(0).write(0,'Sheet 2 A1')
    sheet2.row(0).write(1,'Sheet 2 B1')
    sheet2.flush_row_data()
    
    sheet2.write(1,0,'Sheet 2 A3')
    sheet2.col(0).width = 5000
    sheet2.col(0).hidden = True
    
    book.save(filename)

if __name__=='__main__':
    testXlrd(u'你好。xls')
    testXlwt('helloWord.xls')
    base=datetime.date(1899,12,31).toordinal()
    tmp=datetime.date(2013,07,16).toordinal()
    print datetime.date.fromordinal(tmp+base-1).weekday()
相關文章
相關標籤/搜索