from Base.Class.Excel import *


def read_view_dict(filename=None, sheet=None,
                   area='', from_col=0, from_row=0, to_col=0, to_row=0, fields=None,
                   auto_truncate=False):
    view = Excel().open(filename=filename, read_only=True).select(sheet).cellGetView(
        area=area, from_col=from_col, from_row=from_row, to_col=to_col, to_row=to_row
    )
    tabs = []
    try:
        for i in range(len(view[0])):
            try:
                if not isinstance(fields[i], str):
                    raise TypeError()
                tabs.append(fields[i])
            except:
                tabs.append('col' + str(i))
    except:
        pass
    if len(tabs) != len(set(tabs)):
        raise Exception('字段存在重复项目 | There are duplicates in the field')
    data = []
    for line in view:
        if auto_truncate:
            none_number = 0
            for value in line:
                if value is None:
                    none_number += 1
            if len(line) == none_number:
                break
        line_dict = {}
        for i in range(len(line)):
            line_dict[tabs[i]] = line[i]
        data.append(line_dict)
    return data






if __name__ == '__main__':
    from Base.Class.Json import *
    from Base.Class.Yaml import *
    print(json_encode(read_view_dict(filename='../../example.xlsx', sheet='表一', area='A2:F530', fields=['id','name','age','city','mark1','mark2'], auto_truncate=True), 4, False))
