您的位置:首页 > 编程语言 > Python开发

使用Python实现读取Excel表格中的数据

2018-01-11 13:47 417 查看
本案例的实现是通过使用第三方xlrd,关于xlrd的相关文章请自行百度,教程很多,不做详解。

#-*- coding:utf-8 -*-

import  xdrlib ,sys
import xlrd
import setting
import bz

path = 'C:\\Users\\Desktop\\111.xls'

def get_score(sheet,grade,sex,score):
book = xlrd.open_workbook(path)
sh = book.sheet_by_index(sheet-1)
for j in xrange(2,sh.ncols):
# 因为使用了utf-8编码,自然要进行解码
tmp_grade_name = sh.cell_value(1,j).decode('utf-8')
tmp_sex = sh.cell_value(2,j)
# 判断两个对象的值是否相等,如果判断对象是否相等,可以使用is关键来进行判断,建议使用==,cmp好像要废弃掉了
if tmp_grade_name == grade and cmp(tmp_sex,sex) == 0:
for i in xrange(3,sh.nrows):
tmp_score = sh.cell_value(i,j)
if score <= float(tmp_score) and i>3 and i<21:
return sh.cell_value(i,1)
elif score <= float(tmp_score) and i == 3:
return sh.cell_value(3,1)
elif score >= float(tmp_score) and i >= 20:
return sh.cell_value(20,1)

if __name__ == '__main__':
tmp_str = raw_input()
tmp_array = tmp_str.split(' ')
if tmp_array[0]=='1':
tmp_score = get_score(int(tmp_array[0]),tmp_array[1].encode('utf-8'),
tmp_array[2].encode('utf-8'),float(tmp_array[3]))
print tmp_score
elif tmp_array[0] == '2':
tmp_score = get_score(int(tmp_array[0]),tmp_array[1].encode('utf-8'),
tmp_array[2].encode('utf-8'),float(tmp_array[3]))
print tmp_score
elif tmp_array[0] == '3':
tmp_score = get_score(int(tmp_array[0]),tmp_array[1].encode('utf-8'),
tmp_array[2].encode('utf-8'),float(tmp_array[3]))
print tmp_score
elif tmp_array[0] == '4':
tmp_score = get_score(int(tmp_array[0]),tmp_array[1].encode('utf-8'),
tmp_array[2].encode('utf-8'),float(tmp_array[3]))
print tmp_score
else:
print "Error!!!"


1、如果使用的是Windows的cmd命令行,对于中文会出现编码问题,因为cmd支持的是GBK的编码,解决方案:将Excel文件重新导出时,更改编码为ut-8的编码方式

2、如果是从cmd命令行输入的编码问题,解决方案为:在cmd命令行下,输入chcp 65001,此时cmd的编码方式就变为utf-8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: