Python openpyxl 读excel xlsx文件

示例

# excel库
import openpyxl
# python GUI库
import tkinter.filedialog as filedialog


def parseXLSX(filename, sheetNum=1):
    """
    解析excel文件, 并返回列表
    param: filename 文件名, sheetNum sheet页序号
    return:[{title:value},{title:value}]
    """
    rslt = []
    try:
        # 通过 openpyxl 加载
        wb = openpyxl.load_workbook(filename)
        # 获取sheet页对象 编号从0开始
        sheet = wb._sheets[sheetNum-1]
        print(sheet.max_row, sheet.max_column)

        title = []
        # 获取列标题
        for y in range(0, sheet.max_column):
            colname = str(sheet[1][y].value)
            title.append(colname)
        # print(title)
        # 遍历
        for row in sheet.rows:
            i = 0
            tmp = {}
            for cell in row:
                tmp[title[i]] = cell.value
                i = i+1
            rslt.append(tmp)
    except Exception as e:
        print(e)
    return rslt


if __name__ == "__main__":
    # 手动选择文件, 获取文件名
    vfilename = filedialog.askopenfilename(initialdir="d:\\")
    # print(vfilename)
    data = parseXLSX(vfilename)
    print(data)

上一篇:python中的openpyxl


下一篇:Python接口自动化测试—读写excel(openpyxl库)