-
Notifications
You must be signed in to change notification settings - Fork 1
/
excel2toml.py
218 lines (203 loc) · 8.47 KB
/
excel2toml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#! /usr/bin/python3
import os
import re
import sys
import getopt
import xlrd
import pytablewriter
REGEXP_FIRST_UPPERCASE = re.compile(r"^[A-Z]+[a-zA-Z0-9]*$")
def create_file(name, rows, header, lowercase, objectname, cellname, is_print):
# remove old file
if os.path.exists(name):
os.remove(name)
# print header
row_num = len(rows)
column_num = len(rows[0])
data_begin = header # data begin row
fields = rows[0]
types = rows[1]
descs = rows[2]
# descs[0] = fields[0] + "_Desc" # the first column is in english
if is_print:
print("create file: ", name)
print("fields: ", fields)
print("types : ", types)
print("descs : ", descs)
print("row_num: %d, column_num: %d, data_begin: %d" %
(row_num, column_num, data_begin))
# check header
for n in range(column_num):
field_name = fields[n]
type_name = types[n]
if field_name.isspace():
print("create file: %s fail, field name is empty column=%d" %
(name, n + 1))
return
if type_name.isspace():
print("create file: %s fail, type name is empty column=%d field_name=%s" % (
name, n + 1, field_name))
return
if type_name != "STRING" and type_name != "INT" and type_name != "FLOAT":
print("create file: %s fail, type invalid column=%d field_name=%s type_name=%s" % (
name, n + 1, field_name, type_name))
return
# out toml
writer = pytablewriter.TomlTableWriter()
writer.table_name = cellname
# set headers
for f in fields:
writer.headers.append(f.lower() if lowercase else f)
# set type_hints
for n in range(column_num):
if types[n] == "STRING":
writer.type_hints.append(pytablewriter.typehint.String)
elif types[n] == "INT":
writer.type_hints.append(pytablewriter.typehint.Integer)
elif types[n] == "FLOAT":
writer.type_hints.append(pytablewriter.typehint.RealNumber)
try:
for r in range(row_num):
row_data = rows[r]
if is_print:
print(row_data)
cell = []
for c in range(column_num):
# field data
field_name = fields[c]
type_name = types[c]
field_data = row_data[c]
if r < data_begin:
continue
else:
if type_name == "STRING":
assert (type(field_data) == str), "data is not a string type file: %s row=%d field_name=%s type_name=%s field_data=%s" % (
name, r + 1, field_name, type_name, str(field_data))
cell.append(field_data)
elif type_name == "INT":
assert (type(field_data) == float), "data is not a number type file: %s row=%d field_name=%s type_name=%s field_data=%s" % (
name, r + 1, field_name, type_name, str(field_data))
assert (field_data - int(field_data) == 0), "data is not a int type file: %s row=%d field_name=%s type_name=%s field_data=%s" % (
name, r + 1, field_name, type_name, str(field_data))
cell.append(int(field_data))
elif type_name == "FLOAT":
assert (type(field_data) == float), "data is not a float type file: %s row=%d field_name=%s type_name=%s field_data=%s" % (
name, r + 1, field_name, type_name, str(field_data))
if field_data - int(field_data) == 0:
cell.append(int(field_data))
else:
cell.append(round(field_data, 4))
else:
assert False, "unknown type file: %s row=%d field_name=%s type_name=%s field_data=%s" % (
name, r + 1, field_name, type_name, str(field_data))
if len(cell) > 0:
writer.value_matrix.append(cell)
finally:
# write file
file = open(name, "w", encoding="utf-8")
file.write("[" + objectname + "]\n")
# replace [["abc.list"]] => [[abc.list]]
if True:
text = writer.dumps()
if text.find("[[\"") != -1:
text = text.replace("[[\"", "[[").replace("\"]]", "]]")
file.write(text)
else:
writer.dump(file, False)
file.close()
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def help():
print("""
Help info
-i, --input-dir input file directory
-o, --output-dir output file directory
-e, --filename-ext filename extension, default is \".toml\"
--header table header, default is 3
--lowercase field name lowercase, default is 1
--cellname-ext cellname extension, default is \".list\"
""")
def main(argv=None):
if argv is None:
argv = sys.argv
count = 0
try:
current_dir = os.getcwd()
input_dir = "."
output_dir = "."
filename_ext = ".toml"
header = 3
lowercase = 1
cellname_ext = ".list"
try:
opts, args = getopt.getopt(argv[1:], "hi:o:e:", [
"help", "input-dir=", "output-dir=", "filename-ext=", "header=", "lowercase=", "cellname-ext="])
for opt_name, opt_value in opts:
if opt_name in ("-h", "--help"):
help()
return 0
elif opt_name in ("-i", "--input-dir"):
input_dir = opt_value
elif opt_name in ("-o", "--output-dir"):
output_dir = opt_value
elif opt_name in ("-e", "--filename-ext"):
filename_ext = opt_value
elif opt_name == "--header":
header = int(opt_value)
elif opt_name == "--lowercase":
lowercase = int(opt_value)
elif opt_name == "--cellname-ext":
cellname_ext = opt_value
except getopt.error as msg:
raise Usage(msg)
for name in os.listdir(input_dir):
# excel
if name.endswith(".xlsx") or name.endswith(".xlsm"):
table = xlrd.open_workbook(input_dir + "/" + name)
# print("table: ", name)
# sheet
sheet_num = len(table.sheets())
for sheet in table.sheets():
# print("sheet: ", sheet.name)
count += 1
# row count
nrows = sheet.nrows
# row data
rows = []
for i in range(nrows):
rows.append(sheet.row_values(i))
# check header
if len(rows) < header or (rows[1][0] != "INT" and rows[1][0] != "STRING"):
print("[%d] table: %s, sheet: %s, nrows: %d, ignore ! ! ! ! ! !" % (
count, name, sheet.name, nrows))
continue
# create file
file_name = name.split(".", 1)[0]
if sheet.name.startswith("Sheet") == False:
file_name = sheet.name
objectname = file_name
if objectname.istitle() == False and REGEXP_FIRST_UPPERCASE.search(objectname) is None:
objectname = objectname.title()
if objectname.find("_") != -1:
objectname = objectname.replace("_", "")
create_file(output_dir + "/" + file_name +
filename_ext, rows, header, lowercase, objectname, objectname + cellname_ext, False)
# print("[%d] table: %s, sheet: %s, nrows: %d, ok." % (count, name, sheet.name, nrows))
except Usage as err:
print(err.msg)
help()
# os.system("pause")
return 2
except AssertionError as err:
print("Assertion:", err)
# os.system("pause")
return 2
except:
print("Unexpected error:", sys.exc_info()[0])
# os.system("pause")
return 2
print("excel2toml: ", count)
# os.system("pause")
return 0
if __name__ == "__main__":
sys.exit(main())