python 表格界面 可编辑_python处理excel表格

一、可使用的第三方库

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值