python 读取excel

2016/07/17 11:18
阅读数 286

读取excel, 返回列表,列表的每一项是一个子典,包含一项记录

def get_data_from_excel(self, f, colnameindex=0,by_index=0):
        """从excel读取数据, 返回字典形式记录的列表
        colnameindex: 表头
        """
        try:
            data = xlrd.open_workbook(f)
        except Exception as e:
            return None

        sheet = data.sheets()[by_index]
        nrows = sheet.nrows #行数
        ncols = sheet.ncols #列数
        colnames =  sheet.row_values(colnameindex) #第一行数据,表头
        list =[] 
        for rownum in range(1,nrows):
             row = sheet.row_values(rownum)
             if row:
                 app = {}
                 for i in range(len(colnames)):
                    value = row[i]
                    if type(value) == float and int(value) == value:
                        value = str(int(value))
                    app[colnames[i]] = value
                 list.append(app)
        return list

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
2 收藏
分享
打赏
1 评论
2 收藏
0
分享
返回顶部
顶部