53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
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, object_cell=False):
|
|
excel_object = Excel().open(filename=filename)
|
|
view = excel_object.select(sheet).cellGetView(
|
|
area=area, from_col=from_col, from_row=from_row, to_col=to_col, to_row=to_row,
|
|
ocell=object_cell
|
|
)
|
|
tabs = []
|
|
try:
|
|
for i in range(len(view[0])):
|
|
try:
|
|
if not isinstance(fields[i], (str, tuple, list)):
|
|
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)):
|
|
fiel = tabs[i]
|
|
if isinstance(fiel, str):
|
|
fiel = [fiel]
|
|
for v in fiel:
|
|
line_dict[v] = line[i]
|
|
data.append(line_dict)
|
|
return {'excel_object': excel_object, 'data': 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))
|