-
Notifications
You must be signed in to change notification settings - Fork 2
/
csvToXls.js
113 lines (89 loc) · 2.62 KB
/
csvToXls.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
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
"use strict";
let Stream = require("stream");
let path = require("path");
let gutil = require("gulp-util");
let plexer = require("plexer");
let csv = require("csv-parser");
let excelbuilder = require("msexcel-builder");
function buildFilename(file) {
let fullpath = file.history[0];
return path.basename(fullpath, path.extname(fullpath));
}
module.exports = function(PLUGIN_NAME) {
return function(options) {
options = options || {};
let inputStream = new Stream.Transform({objectMode: true});
let outputStream = new Stream.PassThrough({objectMode: true});
let stream = plexer({objectMode: true}, inputStream, outputStream);
inputStream._transform = function(file, encoding, done) {
if (file.isNull()) {
outputStream.write(file);
done();
return;
}
if (path.extname(file.history[0]) !== ".csv") {
outputStream.emit("error", new gutil.PluginError(PLUGIN_NAME, `Extension ".csv" expected but ${path.extname(file.history[0])} was found`));
done();
return;
}
let keys;
let data = [];
let maxColumns = 0;
let xlsStream;
let filename = options.filename || buildFilename(file);
if (file.isBuffer()) {
xlsStream = new Stream.PassThrough();
xlsStream.push(file.contents);
xlsStream.end();
}
if (file.isStream()) {
xlsStream = file.contents;
}
let xlsFile = new gutil.File({
cwd: file.cwd,
base: file.base,
path: `${path.join(file.base, filename)}.xlsx`
});
xlsStream
.pipe(csv())
.on("data", (row) => {
if (!keys) {
keys = Object.keys(row);
maxColumns = keys.length;
}
data.push(row);
})
.on("error", (err) => {
outputStream.emit("error", new gutil.PluginError(PLUGIN_NAME, `Error while reading the stream! ${err.message}`));
})
.on("end", () => {
let maxRows = data.length;
let workbook = excelbuilder.createWorkbook(file.base, `${path.join(file.base, filename)}.xlsx`);
let sheet1 = workbook.createSheet("Sheet 1", maxColumns, maxRows + 1);
keys.forEach((key, j) => {
sheet1.set(j + 1, 1, key);
});
for (let i = 0; i < maxRows; i++) {
let line = data[i];
keys.forEach((key, j) => {
let cell = line[key];
sheet1.set(j + 1, i + 2, cell);
});
}
workbook.generate((err, zip) => {
if (err) {
outputStream.emit("error", new gutil.PluginError(PLUGIN_NAME, "Error while generating workbook!"));
done();
}
xlsFile.contents = zip.generate({
type: "nodebuffer"
});
outputStream.push(xlsFile);
outputStream.end();
});
});
done();
};
return stream;
};
};