-
Notifications
You must be signed in to change notification settings - Fork 0
/
toXlsx.js
87 lines (73 loc) · 1.8 KB
/
toXlsx.js
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
/**
* toXLSX - Converts json to xls
*
* Json structure:
* {
* label: 'text'
* label2: 'text2'
* }
*
* TODO:
* - validations
* - config json object format
* - append contents to a file (new sheet)
*/
const fs = require('fs')
const xlsx = require('node-xlsx')
const ARGV = require('minimist')(process.argv.slice(2))
if (Object.keys(ARGV).length === 1) exit(`Generates xlsx file from json.
Usage:
toXlsx --input <file> --output <filename>
--input (filename path)
Local file path to xlsx file.
--output (name)
Filename to save content to.
--sheetname (name)
Name for sheet to save content.
`)
if (!ARGV.input) exit('Include --input parameter with path to local json file.')
const FILE_INPUT = ARGV.input
const SHEETNAME = ARGV.SHEETNAME || 'Sheet'
let OUTPUT_NAME
// use same input filename for output
if (!ARGV.output) {
let file = FILE_INPUT
if (file.includes('/')) {
fileArray = FILE_INPUT.split('/')
file = fileArray[fileArray.length - 1]
}
OUTPUT_NAME = file.substr(0, file.lastIndexOf('.'))
} else {
OUTPUT_NAME = ARGV.output
}
// -- RUN {{{
const jsonData = fs.readFileSync(FILE_INPUT, 'utf8')
const headers = ['Etiqueta', 'Traducción'] // TODO: make it configurable
const content = toArray(JSON.parse(jsonData))
content.unshift(headers)
const buffer = xlsx.build([{
name: SHEETNAME,
data: content
}])
// output - file
const FILE = OUTPUT_NAME + '.xlsx'
const wstream = fs.createWriteStream(FILE)
.on('finish', () => console.log('File created: %s', FILE))
wstream.write(buffer)
wstream.end()
// }}}
// --- FNs {{{
/*
* Generate array from object
*/
function toArray (obj) {
return Object.keys(obj).map(k => [k, obj[k]])
}
/**
* Exit process with message, helper
*/
function exit (message, cb) {
console.log('\n' + message + '\n')
process.exit()
}
// }}}