Python2 读取 Excel 文件数据

表格示例 a.xlsx:

网站host 详细url 类型 主机位置
zhouweiwei.com www.zhouweiwei.com 个人 国内
qq.com qzone.qq.com 企业 香港
facebook.com 政府 美国
121.42.86.217 121.42.86.217/product 个人 美国

?代码示例 xlrd-simple.py:

#!/usr/bin/env python
#coding:utf-8

import os
import sys
import xlrd
import chardet
 
#xlrd模块下载https://pypi.python.org/pypi/xlrd 解压出来>setup.py install安装
reload(sys) sys.setdefaultencoding('utf-8')
def gbkstring(s):
    if type(s)==unicode:        
        s=s.encode("gb2312",'ignore')
    else:    
        if chardet.detect(s)['encoding']=='utf-8':
            s=s.decode("utf-8",'ignore').encode("gb2312",'ignore')
    return s
#根据索引获取Excel表格中的数据
localDir = os.getcwd()
def excel_table_byindex(filepath = localDir + "\\a.xlsx",by_index=0):
    filepath=gbkstring(filepath)
    data = xlrd.open_workbook(filepath)
    table = data.sheets()[by_index]
    print table.nrows,table.ncols
    urllist=[]
    for row in xrange(1,table.nrows):
        hostvalue=''
        dict={"url":"","host":""}
        if (str(table.cell(row,2).value)=='个人' or str(table.cell(row,2).value)=='企业') and (str(table.cell(row,1).value).split('/')[0].strip().find(str(table.cell(row,0).value).strip())!=-1):
            dict['url']=str(table.cell(row,1).value)
        elif str(table.cell(row,2).value)=='政府':
            dict['url']=str(table.cell(row,0).value)
        elif str(table.cell(row,2).value) not in ['个人','企业','政府']:
            return "error--01 excel 中第%d行类型这一列有问题,不是期望的个人或者企业或者政府,实际值为%s"%(row+1,str(table.cell(row,2).value))
 
        elif (str(table.cell(row,2).value)=='个人' or str(table.cell(row,2).value)=='企业') and (str(table.cell(row,1).value).split('/')[0].strip().find(str(table.cell(row,0).value).strip())==-1):
            return "error---02 excel 中单元格中%s这一数据有问题,与第一列中网站host不匹配!"%str(table.cell(row,1).value)
 
        if '国内' ==str(table.cell(row,3).value).strip():
            hostvalue='国内' 
        elif '美国' == str(table.cell(row,3).value).strip():
            hostvalue='美国'
        elif '香港' == str(table.cell(row,3).value).strip():
            hostvalue='香港'
        else:
            return  "error--03 excel 中第%d行主机位置这一列的这个值有问题,不是期望的国内或者美国或者香港,实际值为 %s"%(row+1,str(table.cell(row,3).value).strip())
 
        dict['host']=hostvalue
        urllist.append(dict)
    return urllist
print excel_table_byindex()