python openpyxl 读取excel数据

该实现方法主要适用于存在表头的excel,自读判断excel的列数与行数,将excel中的数据以不同格式展示,使用的是openpyxl
入参:
filePath:excel文件的路径,只能导入xlsx的文件
Type:导出数据的格式,支持输入"list"、"list_dict"、"list_list"、"dict_dict"、"dict_list"
keyName:当Type为”dict_dict“、”dict_list“时使用


sheetIndex:需要获取数据的sheet,默认为第一个
titleIndex:sheet内表头的行数,默认第一行

返回参数内返回了
title:以列表形似返回表头
data:excel数据主要在此返回
import openpyxl
def getExcle_openpyxl(filePath,Type,keyName=None,sheetIndex=0,titleIndex=1):
    try:
        wb = openpyxl.load_workbook(filePath)
    except:
        raise Exception("读取文件失败")
    try:
        sheet = wb.worksheets[sheetIndex]
    except:
        raise Exception("不存在sheet")
    if Type in ['list','list_dict','list_list','dict_dict','dict_list']:
        if Type == "list":
            reType = 'list'
            rowType = None
        else:
            reType, rowType = Type.split("_")
    else:
        raise KeyError("输入类型失败,仅支持输入”list“、”list_dict“、”list_list“、”dict_dict“、”dict_list“")
    maxRow = sheet.max_row
    maxCol = sheet.max_column
    Re = {} if reType == "dict" else []
    titleList = []
    for rowIndex,row in enumerate(sheet.iter_rows(min_row=titleIndex,max_row=maxRow,max_col=maxCol)):
        keyData = None
        rowList_list = []
        rowList_dict = {}
        for colIndex, col in enumerate(row):
            value = col.value
            if rowIndex <= 0:
                titleList.append(value)
            else:
                if reType and reType == 'dict' and keyName not in titleList:
                    raise KeyError("主键不存在于表头中")
                if titleList[colIndex] == keyName:
                    keyData = value
                rowList_dict[titleList[colIndex]] = value
            rowList_list.append(value)
        if reType == 'dict':
            if rowIndex > 0:
                Re[keyData] = rowList_dict if rowType == "dict" else rowList_list
        else:
            if rowType:
                if rowIndex > 0:
                    Re.append(rowList_dict if rowType == "dict" else rowList_list)
            else:
                Re.append(rowList_list)
    return {
        "title": titleList,
        "data": Re
    }

本人仅测试小弟,非开发,如有更优写法或者有错误地方,欢迎大神们指点指点!!!

你可能感兴趣的:(python封装方法,python,excel,windows)