forked from dilshod/xlsx2csv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxlsx2csv.py
executable file
·485 lines (451 loc) · 18.3 KB
/
xlsx2csv.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/env python
#
# Copyright information
#
# Copyright (C) 2010-2012 Dilshod Temirkhodjaev <[email protected]>
#
# License
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Dilshod Temirkhodjaev <[email protected]>"
__license__ = "GPL-2+"
import csv, datetime, zipfile, string, sys, os, re
import xml.parsers.expat
from xml.dom import minidom
from optparse import OptionParser
# see also ruby-roo lib at: http://github.com/hmcgowan/roo
FORMATS = {
'general' : 'float',
'0' : 'float',
'0.00' : 'float',
'#,##0' : 'float',
'#,##0.00' : 'float',
'0%' : 'percentage',
'0.00%' : 'percentage',
'0.00e+00' : 'float',
'mm-dd-yy' : 'date',
'd-mmm-yy' : 'date',
'd-mmm' : 'date',
'mmm-yy' : 'date',
'h:mm am/pm' : 'date',
'h:mm:ss am/pm' : 'date',
'h:mm' : 'time',
'h:mm:ss' : 'time',
'm/d/yy h:mm' : 'date',
'#,##0 ;(#,##0)' : 'float',
'#,##0 ;[red](#,##0)' : 'float',
'#,##0.00;(#,##0.00)' : 'float',
'#,##0.00;[red](#,##0.00)' : 'float',
'mm:ss' : 'time',
'[h]:mm:ss' : 'time',
'mmss.0' : 'time',
'##0.0e+0' : 'float',
'@' : 'float',
'yyyy\\-mm\\-dd' : 'date',
'dd/mm/yy' : 'date',
'hh:mm:ss' : 'time',
"dd/mm/yy\\ hh:mm" : 'date',
'dd/mm/yyyy hh:mm:ss' : 'date',
'yy-mm-dd' : 'date',
'd-mmm-yyyy' : 'date',
'm/d/yy' : 'date',
'm/d/yyyy' : 'date',
'dd-mmm-yyyy' : 'date',
'dd/mm/yyyy' : 'date',
'mm/dd/yy hh:mm am/pm' : 'date',
'mm/dd/yyyy hh:mm:ss' : 'date',
'yyyy-mm-dd hh:mm:ss' : 'date',
}
STANDARD_FORMATS = {
0 : 'general',
1 : '0',
2 : '0.00',
3 : '#,##0',
4 : '#,##0.00',
9 : '0%',
10 : '0.00%',
11 : '0.00e+00',
12 : '# ?/?',
13 : '# ??/??',
14 : 'mm-dd-yy',
15 : 'd-mmm-yy',
16 : 'd-mmm',
17 : 'mmm-yy',
18 : 'h:mm am/pm',
19 : 'h:mm:ss am/pm',
20 : 'h:mm',
21 : 'h:mm:ss',
22 : 'm/d/yy h:mm',
37 : '#,##0 ;(#,##0)',
38 : '#,##0 ;[red](#,##0)',
39 : '#,##0.00;(#,##0.00)',
40 : '#,##0.00;[red](#,##0.00)',
45 : 'mm:ss',
46 : '[h]:mm:ss',
47 : 'mmss.0',
48 : '##0.0e+0',
49 : '@',
}
#
# usage: xlsx2csv("test.xslx", open("test.csv", "w+"))
# parameters:
# sheetid - sheet no to convert (0 for all sheets)
# dateformat - override date/time format
# delimiter - csv columns delimiter symbol
# sheet_delimiter - sheets delimiter used when processing all sheets
# skip_empty_lines - skip empty lines
#
def xlsx2csv(infilepath, outfile, outfilename, sheetid=1, dateformat=None, delimiter=",", sheetdelimiter="--------", skip_empty_lines=False):
try:
ziphandle = zipfile.ZipFile(infilepath)
except zipfile.BadZipfile:
sys.stderr.write("Invalid xlsx file: " + infilepath + os.linesep)
return
try:
shared_strings = parse(ziphandle, SharedStrings, "xl/sharedStrings.xml")
styles = parse(ziphandle, Styles, "xl/styles.xml")
workbook = parse(ziphandle, Workbook, "xl/workbook.xml")
if sheetid > 0:
outfile = outfilename and open(outfilename, 'w+b') or outfile
try:
writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL, delimiter=delimiter, lineterminator=os.linesep)
sheet = None
for s in workbook.sheets:
if s['id'] == sheetid:
sheetfile = ziphandle.open("xl/worksheets/sheet%i.xml" %s['id'], "r")
sheet = Sheet(workbook, shared_strings, styles, sheetfile)
break
if not sheet:
raise Exception("Sheet %i Not Found" %sheetid)
sheet.set_dateformat(dateformat)
sheet.set_skip_empty_lines(skip_empty_lines)
sheet.to_csv(writer)
sheetfile.close()
finally:
if outfilename:
outfile.close()
else:
if outfilename:
if not os.path.exists(outfilename):
os.makedirs(outfilename)
elif os.path.isfile(outfilename):
sys.stderr.write("File " + outfilename + " already exists!" + os.linesep)
sys.exit(1)
#sheetnames = []
for s in workbook.sheets:
sheetname = s['name'].encode('utf-8')
#sheetnames.append(sheetname + '.csv')
outfile = outfilename and open(os.path.join(outfilename, sheetname + '.csv'), 'w+b') or outfile
try:
writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL, delimiter=delimiter, lineterminator=os.linesep)
if not outfilename and sheetdelimiter != "":
outfile.write(sheetdelimiter + " " + str(s['id']) + " - " + s['name'].encode('utf-8') + os.linesep)
sheetfile = ziphandle.open("xl/worksheets/sheet%i.xml" %s['id'], "r")
sheet = Sheet(workbook, shared_strings, styles, sheetfile)
sheet.set_dateformat(dateformat)
sheet.set_skip_empty_lines(skip_empty_lines)
sheet.to_csv(writer)
sheetfile.close()
finally:
if outfilename:
outfile.close()
#if outfilename:
# f = open(os.path.join(outfilename, "sheets.txt"), "w+b")
# f.write(string.join(sheetnames, "\n"))
# f.close()
finally:
ziphandle.close()
def parse(ziphandle, klass, filename):
instance = klass()
if not filename in ziphandle.namelist():
filename = filter(lambda f: f.lower() == filename.lower(), ziphandle.namelist())[0]
if filename:
f = ziphandle.open(filename, "r")
instance.parse(f)
f.close()
return instance
class Workbook:
def __init__(self):
self.sheets = []
self.date1904 = False
def parse(self, filehandle):
workbookDoc = minidom.parseString(filehandle.read())
if len(workbookDoc.firstChild.getElementsByTagName("fileVersion")) == 0:
self.appName = 'unknown'
else:
self.appName = workbookDoc.firstChild.getElementsByTagName("fileVersion")[0]._attrs['appName'].value
try:
self.date1904 = workbookDoc.firstChild.getElementsByTagName("workbookPr")[0]._attrs['date1904'].value.lower().strip() != "false"
except:
pass
sheets = workbookDoc.firstChild.getElementsByTagName("sheets")[0]
for sheetNode in sheets.getElementsByTagName("sheet"):
attrs = sheetNode._attrs
name = attrs["name"].value
if self.appName == 'xl':
if attrs.has_key('r:id'): id = int(attrs["r:id"].value[3:])
else: id = int(attrs['sheetId'].value)
else:
if attrs.has_key('sheetId'): id = int(attrs["sheetId"].value)
else: id = int(attrs['r:id'].value[3:])
self.sheets.append({'name': name, 'id': id})
class Styles:
def __init__(self):
self.numFmts = {}
self.cellXfs = []
def parse(self, filehandle):
styles = minidom.parseString(filehandle.read()).firstChild
# numFmts
numFmtsElement = styles.getElementsByTagName("numFmts")
if len(numFmtsElement) == 1:
for numFmt in numFmtsElement[0].childNodes:
if numFmt.nodeType == minidom.Node.ELEMENT_NODE:
numFmtId = int(numFmt._attrs['numFmtId'].value)
formatCode = numFmt._attrs['formatCode'].value.lower().replace('\\', '')
self.numFmts[numFmtId] = formatCode
# cellXfs
cellXfsElement = styles.getElementsByTagName("cellXfs")
if len(cellXfsElement) == 1:
for cellXfs in cellXfsElement[0].childNodes:
if cellXfs.nodeType != minidom.Node.ELEMENT_NODE or cellXfs.nodeName != "xf":
continue
if cellXfs._attrs.has_key('numFmtId'):
numFmtId = int(cellXfs._attrs['numFmtId'].value)
self.cellXfs.append(numFmtId)
else:
self.cellXfs.append(None)
class SharedStrings:
def __init__(self):
self.parser = None
self.strings = []
self.si = False
self.t = False
self.rPh = False
self.value = ""
def parse(self, filehandle):
self.parser = xml.parsers.expat.ParserCreate()
self.parser.CharacterDataHandler = self.handleCharData
self.parser.StartElementHandler = self.handleStartElement
self.parser.EndElementHandler = self.handleEndElement
self.parser.ParseFile(filehandle)
def handleCharData(self, data):
if self.t:
self.value+= data
def handleStartElement(self, name, attrs):
if name == 'si':
self.si = True
self.value = ""
elif name == 't' and self.rPh:
self.t = False
elif name == 't' and self.si:
self.t = True
elif name == 'rPh':
self.rPh = True
def handleEndElement(self, name):
if name == 'si':
self.si = False
self.strings.append(self.value)
elif name == 't':
self.t = False
elif name == 'rPh':
self.rPh = False
class Sheet:
def __init__(self, workbook, sharedString, styles, filehandle):
self.parser = None
self.writer = None
self.sharedString = None
self.styles = None
self.in_sheet = False
self.in_row = False
self.in_cell = False
self.in_cell_value = False
self.in_cell_formula = False
self.columns = {}
self.rowNum = None
self.colType = None
self.s_attr = None
self.data = None
self.dateformat = None
self.skip_empty_lines = False
self.filehandle = filehandle
self.workbook = workbook
self.sharedStrings = sharedString.strings
self.styles = styles
def set_dateformat(self, dateformat):
self.dateformat = dateformat
def set_skip_empty_lines(self, skip):
self.skip_empty_lines = skip
def to_csv(self, writer):
self.writer = writer
self.parser = xml.parsers.expat.ParserCreate()
self.parser.CharacterDataHandler = self.handleCharData
self.parser.StartElementHandler = self.handleStartElement
self.parser.EndElementHandler = self.handleEndElement
self.parser.ParseFile(self.filehandle)
def handleCharData(self, data):
if self.in_cell_value:
self.collected_string+= data
self.data = self.collected_string
if self.colType == "s": # shared string
self.data = self.sharedStrings[int(self.data)]
elif self.colType == "b": # boolean
self.data = (int(data) == 1 and "TRUE") or (int(data) == 0 and "FALSE") or data
elif self.s_attr:
s = int(self.s_attr)
# get cell format
format = None
xfs_numfmt = self.styles.cellXfs[s]
if self.styles.numFmts.has_key(xfs_numfmt):
format = self.styles.numFmts[xfs_numfmt]
elif STANDARD_FORMATS.has_key(xfs_numfmt):
format = STANDARD_FORMATS[xfs_numfmt]
# get format type
if format and FORMATS.has_key(format):
format_type = FORMATS[format]
try:
if format_type == 'date': # date/time
if self.workbook.date1904:
date = datetime.datetime(1904, 01, 01) + datetime.timedelta(float(self.data))
else:
date = datetime.datetime(1899, 12, 30) + datetime.timedelta(float(self.data))
if self.dateformat:
# str(dateformat) - python2.5 bug, see: http://bugs.python.org/issue2782
self.data = date.strftime(str(self.dateformat))
else:
dateformat = format.replace("yyyy", "%Y").replace("yy", "%y"). \
replace("hh:mm", "%H:%M").replace("h", "%H").replace("%H%H", "%H").replace("ss", "%S"). \
replace("d", "%e").replace("%e%e", "%d"). \
replace("mmmm", "%B").replace("mmm", "%b").replace(":mm", ":%M").replace("m", "%m").replace("%m%m", "%m"). \
replace("am/pm", "%p")
self.data = date.strftime(str(dateformat)).strip()
elif format_type == 'time': # time
self.data = str(float(self.data) * 24*60*60)
elif format_type == 'float' and ('E' in self.data or 'e' in self.data):
self.data = ("%f" %(float(self.data))).rstrip('0').rstrip('.')
except (ValueError, OverflowError):
# invalid date format
pass
# does not support it
#elif self.in_cell_formula:
# self.formula = data
def handleStartElement(self, name, attrs):
if self.in_row and name == 'c':
self.colType = attrs.get("t")
self.s_attr = attrs.get("s")
cellId = attrs.get("r")
if cellId:
self.colNum = cellId[:len(cellId)-len(self.rowNum)]
self.colIndex = 0
else:
self.colIndex+= 1
#self.formula = None
self.data = ""
self.in_cell = True
elif self.in_cell and (name == 'v' or name == 'is'):
self.in_cell_value = True
self.collected_string = ""
#elif self.in_cell and name == 'f':
# self.in_cell_formula = True
elif self.in_sheet and name == 'row' and attrs.has_key('r'):
self.rowNum = attrs['r']
self.in_row = True
self.columns = {}
self.spans = None
if attrs.has_key('spans'):
self.spans = [int(i) for i in attrs['spans'].split(":")]
elif name == 'sheetData':
self.in_sheet = True
def handleEndElement(self, name):
if self.in_cell and name == 'v':
self.in_cell_value = False
#elif self.in_cell and name == 'f':
# self.in_cell_formula = False
elif self.in_cell and name == 'c':
t = 0
for i in self.colNum: t = t*26 + ord(i) - 64
self.columns[t - 1 + self.colIndex] = self.data
self.in_cell = False
if self.in_row and name == 'row':
if len(self.columns.keys()) > 0:
d = [""] * (max(self.columns.keys()) + 1)
for k in self.columns.keys():
d[k] = self.columns[k].encode("utf-8")
if self.spans:
l = self.spans[0] + self.spans[1] - 1
if len(d) < l:
d+= (l - len(d)) * ['']
# write line to csv
if not self.skip_empty_lines or d.count('') != len(d):
self.writer.writerow(d)
self.in_row = False
elif self.in_sheet and name == 'sheetData':
self.in_sheet = False
def convert_recursive(path, kwargs):
for name in os.listdir(path):
fullpath = os.path.join(path, name)
if os.path.isdir(fullpath):
convert_recursive(fullpath, kwargs)
else:
if fullpath.lower().endswith(".xlsx"):
outfilepath = fullpath[:-4] + 'csv'
print("Converting %s to %s" %(fullpath, outfilepath))
try:
xlsx2csv(fullpath, None, outfilepath, **kwargs)
except zipfile.BadZipfile:
print("File is not a zip file")
if __name__ == "__main__":
parser = OptionParser(usage = "%prog [options] infile [outfile]", version="0.11")
parser.add_option("-d", "--delimiter", dest="delimiter", default=",",
help="delimiter - csv columns delimiter, 'tab' or 'x09' for tab (comma is default)")
parser.add_option("-f", "--dateformat", dest="dateformat",
help="override date/time format (ex. %Y/%m/%d)")
parser.add_option("-i", "--ignoreempty", dest="skip_empty_lines", default=False, action="store_true",
help="skip empty lines")
parser.add_option("-p", "--sheetdelimiter", dest="sheetdelimiter", default="--------",
help="sheets delimiter used to separate sheets, pass '' if you don't want delimiters (default '--------')")
parser.add_option("-r", "--recursive", dest="recursive", default=False, action="store_true",
help="convert recursively")
parser.add_option("-s", "--sheet", dest="sheetid", default=1, type="int",
help="sheet no to convert (0 for all sheets)")
(options, args) = parser.parse_args()
if len(options.delimiter) == 1:
delimiter = options.delimiter
elif options.delimiter == 'tab':
delimiter = '\t'
elif options.delimiter == 'comma':
delimiter = ','
elif options.delimiter[0] == 'x':
delimiter = chr(int(options.delimiter[1:]))
else:
raise Exception("Invalid delimiter")
kwargs = {
'sheetid' : options.sheetid,
'delimiter' : delimiter,
'sheetdelimiter' : options.sheetdelimiter,
'dateformat' : options.dateformat,
'skip_empty_lines' : options.skip_empty_lines
}
if options.recursive:
if len(args) == 1:
convert_recursive(args[0], kwargs)
else:
parser.print_help()
else:
if len(args) < 1:
parser.print_help()
else:
if len(args) > 1:
xlsx2csv(args[0], None, args[1], **kwargs)
else:
xlsx2csv(args[0], sys.stdout, None, **kwargs)