python处理excel表格

来源:互联网 发布:ps淘宝图片排版教程 编辑:程序博客网 时间:2024/04/29 16:08

一、可使用的第三方库

python中处理excel表格,常用的库有xlrd(读excel)表、xlwt(写excel)表、openpyxl(可读写excel表)等。xlrd读数据较大的excel表时效率高于openpyxl,所以我在写脚本时就采用了xlrd和xlwt这两个库。介绍及下载地址为:http://www.python-excel.org/ 这些库文件都没有提供修改现有excel表格内容的功能。一般只能将原excel中的内容读出、做完处理后,再写入一个新的excel文件。

二、常见问题

使用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中,时间和日期都使用浮点数表示。可看到,当‘2013年3月20日’所在单元格使用‘常规’格式表示后,内容变为‘41353’;当其单元格格式改变为日期后,内容又变为了‘2013年3月20日’。而使用xlrd读出excel中的日期和时间后,得到是的一个浮点数。所以当向excel中写入的日期和时间为一个浮点数也不要紧,只需将表格的表示方式改为日期和时间,即可得到正常的表示方式。excel中,用浮点数1表示1899年12月31日。

三、常用函数

以下主要介绍xlrd、xlwt、datetime中与日期相关的函数。

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()
0 0
原创粉丝点击