js-xlsx-rails 0.3.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0d8568130aa77c3bd630f74ba8ec1f88086a07b4
4
+ data.tar.gz: d2333492c564432a03d557bf4e9a75350ea968dd
5
+ SHA512:
6
+ metadata.gz: 356aecadfd8626fdc8e2ccb994d7d6210575bed152721f84bffe2f5a0c534b008ba6e0612172e5be6d6a3c536996248700f592bb5c0275faf2e23794fd429d95
7
+ data.tar.gz: 306fa7fcfdacf276c22f834f60ba6b854b31cfc68d555a503d6a4202cc04743448461e6f4754366217a85b00253751b45f9edda5609c9e6f25efceefe48ec381
@@ -0,0 +1,8 @@
1
+ require "js-xlsx-rails/version"
2
+
3
+ module Jsxlsx
4
+ module Rails
5
+ class Engine < ::Rails::Engine
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,5 @@
1
+ module Jsxlsx
2
+ module Rails
3
+ VERSION = "0.3.6"
4
+ end
5
+ end
@@ -0,0 +1,1260 @@
1
+ /* xlsx.js (C) 2013 SheetJS -- http://sheetjs.com */
2
+ /* vim: set ts=2: */
3
+ /*jshint eqnull:true */
4
+ /* Spreadsheet Format -- jump to XLSX for the XLSX code */
5
+ /* ssf.js (C) 2013 SheetJS -- http://sheetjs.com */
6
+ var SSF = {};
7
+ var make_ssf = function(SSF){
8
+ String.prototype.reverse=function(){return this.split("").reverse().join("");};
9
+ var _strrev = function(x) { return String(x).reverse(); };
10
+ function fill(c,l) { return new Array(l+1).join(c); }
11
+ function pad(v,d,c){var t=String(v);return t.length>=d?t:(fill(c||0,d-t.length)+t);}
12
+ function rpad(v,d,c){var t=String(v);return t.length>=d?t:(t+fill(c||0,d-t.length));}
13
+ /* Options */
14
+ var opts_fmt = {};
15
+ function fixopts(o){for(var y in opts_fmt) if(o[y]===undefined) o[y]=opts_fmt[y];}
16
+ SSF.opts = opts_fmt;
17
+ opts_fmt.date1904 = 0;
18
+ opts_fmt.output = "";
19
+ opts_fmt.mode = "";
20
+ var table_fmt = {
21
+ 1: '0',
22
+ 2: '0.00',
23
+ 3: '#,##0',
24
+ 4: '#,##0.00',
25
+ 9: '0%',
26
+ 10: '0.00%',
27
+ 11: '0.00E+00',
28
+ 12: '# ?/?',
29
+ 13: '# ??/??',
30
+ 14: 'm/d/yy',
31
+ 15: 'd-mmm-yy',
32
+ 16: 'd-mmm',
33
+ 17: 'mmm-yy',
34
+ 18: 'h:mm AM/PM',
35
+ 19: 'h:mm:ss AM/PM',
36
+ 20: 'h:mm',
37
+ 21: 'h:mm:ss',
38
+ 22: 'm/d/yy h:mm',
39
+ 37: '#,##0 ;(#,##0)',
40
+ 38: '#,##0 ;[Red](#,##0)',
41
+ 39: '#,##0.00;(#,##0.00)',
42
+ 40: '#,##0.00;[Red](#,##0.00)',
43
+ 45: 'mm:ss',
44
+ 46: '[h]:mm:ss',
45
+ 47: 'mmss.0',
46
+ 48: '##0.0E+0',
47
+ 49: '@'
48
+ };
49
+ var days = [
50
+ ['Sun', 'Sunday'],
51
+ ['Mon', 'Monday'],
52
+ ['Tue', 'Tuesday'],
53
+ ['Wed', 'Wednesday'],
54
+ ['Thu', 'Thursday'],
55
+ ['Fri', 'Friday'],
56
+ ['Sat', 'Saturday']
57
+ ];
58
+ var months = [
59
+ ['J', 'Jan', 'January'],
60
+ ['F', 'Feb', 'February'],
61
+ ['M', 'Mar', 'March'],
62
+ ['A', 'Apr', 'April'],
63
+ ['M', 'May', 'May'],
64
+ ['J', 'Jun', 'June'],
65
+ ['J', 'Jul', 'July'],
66
+ ['A', 'Aug', 'August'],
67
+ ['S', 'Sep', 'September'],
68
+ ['O', 'Oct', 'October'],
69
+ ['N', 'Nov', 'November'],
70
+ ['D', 'Dec', 'December']
71
+ ];
72
+ var frac = function frac(x, D, mixed) {
73
+ var sgn = x < 0 ? -1 : 1;
74
+ var B = x * sgn;
75
+ var P_2 = 0, P_1 = 1, P = 0;
76
+ var Q_2 = 1, Q_1 = 0, Q = 0;
77
+ var A = B|0;
78
+ while(Q_1 < D) {
79
+ A = B|0;
80
+ P = A * P_1 + P_2;
81
+ Q = A * Q_1 + Q_2;
82
+ if((B - A) < 0.0000000001) break;
83
+ B = 1 / (B - A);
84
+ P_2 = P_1; P_1 = P;
85
+ Q_2 = Q_1; Q_1 = Q;
86
+ }
87
+ if(Q > D) { Q = Q_1; P = P_1; }
88
+ if(Q > D) { Q = Q_2; P = P_2; }
89
+ if(!mixed) return [0, sgn * P, Q];
90
+ var q = Math.floor(sgn * P/Q);
91
+ return [q, sgn*P - q*Q, Q];
92
+ };
93
+ var general_fmt = function(v) {
94
+ if(typeof v === 'boolean') return v ? "TRUE" : "FALSE";
95
+ if(typeof v === 'number') {
96
+ var o, V = v < 0 ? -v : v;
97
+ if(V >= 0.1 && V < 1) o = v.toPrecision(9);
98
+ else if(V >= 0.01 && V < 0.1) o = v.toPrecision(8);
99
+ else if(V >= 0.001 && V < 0.01) o = v.toPrecision(7);
100
+ else if(V >= 0.0001 && V < 0.001) o = v.toPrecision(6);
101
+ else if(V >= Math.pow(10,10) && V < Math.pow(10,11)) o = v.toFixed(10).substr(0,12);
102
+ else if(V > Math.pow(10,-9) && V < Math.pow(10,11)) {
103
+ o = v.toFixed(12).replace(/(\.[0-9]*[1-9])0*$/,"$1").replace(/\.$/,"");
104
+ if(o.length > 11+(v<0?1:0)) o = v.toPrecision(10);
105
+ if(o.length > 11+(v<0?1:0)) o = v.toExponential(5);
106
+ }
107
+ else {
108
+ o = v.toFixed(11).replace(/(\.[0-9]*[1-9])0*$/,"$1");
109
+ if(o.length > 11 + (v<0?1:0)) o = v.toPrecision(6);
110
+ }
111
+ o = o.replace(/(\.[0-9]*[1-9])0+e/,"$1e").replace(/\.0*e/,"e");
112
+ return o.replace("e","E").replace(/\.0*$/,"").replace(/\.([0-9]*[^0])0*$/,".$1").replace(/(E[+-])([0-9])$/,"$1"+"0"+"$2");
113
+ }
114
+ if(typeof v === 'string') return v;
115
+ throw "unsupported value in General format: " + v;
116
+ };
117
+ SSF._general = general_fmt;
118
+ var parse_date_code = function parse_date_code(v,opts) {
119
+ var date = Math.floor(v), time = Math.round(86400 * (v - date)), dow=0;
120
+ var dout=[], out={D:date, T:time, u:86400*(v-date)-time}; fixopts(opts = (opts||{}));
121
+ if(opts.date1904) date += 1462;
122
+ if(date === 60) {dout = [1900,2,29]; dow=3;}
123
+ else if(date === 0) {dout = [1900,1,0]; dow=6;}
124
+ else {
125
+ if(date > 60) --date;
126
+ /* 1 = Jan 1 1900 */
127
+ var d = new Date(1900,0,1);
128
+ d.setDate(d.getDate() + date - 1);
129
+ dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
130
+ dow = d.getDay();
131
+ if(opts.mode === 'excel' && date < 60) dow = (dow + 6) % 7;
132
+ }
133
+ out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
134
+ out.S = time % 60; time = Math.floor(time / 60);
135
+ out.M = time % 60; time = Math.floor(time / 60);
136
+ out.H = time;
137
+ out.q = dow;
138
+ return out;
139
+ };
140
+ SSF.parse_date_code = parse_date_code;
141
+ var write_date = function(type, fmt, val) {
142
+ if(val < 0) return "";
143
+ switch(type) {
144
+ case 'y': switch(fmt) { /* year */
145
+ case 'y': case 'yy': return pad(val.y % 100,2);
146
+ default: return val.y;
147
+ } break;
148
+ case 'm': switch(fmt) { /* month */
149
+ case 'm': return val.m;
150
+ case 'mm': return pad(val.m,2);
151
+ case 'mmm': return months[val.m-1][1];
152
+ case 'mmmm': return months[val.m-1][2];
153
+ case 'mmmmm': return months[val.m-1][0];
154
+ default: throw 'bad month format: ' + fmt;
155
+ } break;
156
+ case 'd': switch(fmt) { /* day */
157
+ case 'd': return val.d;
158
+ case 'dd': return pad(val.d,2);
159
+ case 'ddd': return days[val.q][0];
160
+ case 'dddd': return days[val.q][1];
161
+ default: throw 'bad day format: ' + fmt;
162
+ } break;
163
+ case 'h': switch(fmt) { /* 12-hour */
164
+ case 'h': return 1+(val.H+11)%12;
165
+ case 'hh': return pad(1+(val.H+11)%12, 2);
166
+ default: throw 'bad hour format: ' + fmt;
167
+ } break;
168
+ case 'H': switch(fmt) { /* 24-hour */
169
+ case 'h': return val.H;
170
+ case 'hh': return pad(val.H, 2);
171
+ default: throw 'bad hour format: ' + fmt;
172
+ } break;
173
+ case 'M': switch(fmt) { /* minutes */
174
+ case 'm': return val.M;
175
+ case 'mm': return pad(val.M, 2);
176
+ default: throw 'bad minute format: ' + fmt;
177
+ } break;
178
+ case 's': switch(fmt) { /* seconds */
179
+ case 's': return val.S;
180
+ case 'ss': return pad(val.S, 2);
181
+ case 'ss.0': return pad(val.S,2) + "." + Math.round(10*val.u);
182
+ default: throw 'bad second format: ' + fmt;
183
+ } break;
184
+ case 'Z': switch(fmt) {
185
+ case '[h]': return val.D*24+val.H;
186
+ default: throw 'bad abstime format: ' + fmt;
187
+ } break;
188
+ /* TODO: handle the ECMA spec format ee -> yy */
189
+ case 'e': { return val.y; } break;
190
+ case 'A': return (val.h>=12 ? 'P' : 'A') + fmt.substr(1);
191
+ default: throw 'bad format type ' + type + ' in ' + fmt;
192
+ }
193
+ };
194
+ String.prototype.reverse = function() { return this.split("").reverse().join(""); };
195
+ var commaify = function(s) { return s.reverse().replace(/.../g,"$&,").reverse().replace(/^,/,""); };
196
+ var write_num = function(type, fmt, val) {
197
+ if(type === '(') {
198
+ var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
199
+ if(val >= 0) return write_num('n', ffmt, val);
200
+ return '(' + write_num('n', ffmt, -val) + ')';
201
+ }
202
+ var mul = 0, o;
203
+ fmt = fmt.replace(/%/g,function(x) { mul++; return ""; });
204
+ if(mul !== 0) return write_num(type, fmt, val * Math.pow(10,2*mul)) + fill("%",mul);
205
+ if(fmt.indexOf("E") > -1) {
206
+ var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
207
+ if(fmt == '##0.0E+0') {
208
+ var ee = Number(val.toExponential(0).substr(3))%3;
209
+ o = (val/Math.pow(10,ee%3)).toPrecision(idx+1+(ee%3)).replace(/^([+-]?)([0-9]*)\.([0-9]*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,ee) + "." + $3.substr(ee) + "E"; });
210
+ } else o = val.toExponential(idx);
211
+ if(fmt.match(/E\+00$/) && o.match(/e[+-][0-9]$/)) o = o.substr(0,o.length-1) + "0" + o[o.length-1];
212
+ if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
213
+ return o.replace("e","E");
214
+ }
215
+ if(fmt[0] === "$") return "$"+write_num(type,fmt.substr(fmt[1]==' '?2:1),val);
216
+ var r, ff, aval = val < 0 ? -val : val, sign = val < 0 ? "-" : "";
217
+ if((r = fmt.match(/# (\?+) \/ (\d+)/))) {
218
+ var den = Number(r[2]), rnd = Math.round(aval * den), base = Math.floor(rnd/den);
219
+ var myn = (rnd - base*den), myd = den;
220
+ return sign + (base?base:"") + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[2].length) : pad(myn,r[1].length," ") + "/" + pad(myd,r[2].length));
221
+ }
222
+ if(fmt.match(/^00*$/)) return (val<0?"-":"")+pad(Math.round(Math.abs(val)), fmt.length);
223
+ if(fmt.match(/^####*$/)) return "dafuq";
224
+ switch(fmt) {
225
+ case "0": return Math.round(val);
226
+ case "0.0": o = Math.round(val*10);
227
+ return String(o/10).replace(/^([^\.]+)$/,"$1.0").replace(/\.$/,".0");
228
+ case "0.00": o = Math.round(val*100);
229
+ return String(o/100).replace(/^([^\.]+)$/,"$1.00").replace(/\.$/,".00").replace(/\.([0-9])$/,".$1"+"0");
230
+ case "0.000": o = Math.round(val*1000);
231
+ return String(o/1000).replace(/^([^\.]+)$/,"$1.000").replace(/\.$/,".000").replace(/\.([0-9])$/,".$1"+"00").replace(/\.([0-9][0-9])$/,".$1"+"0");
232
+ case "#,##0": return sign + commaify(String(Math.round(aval)));
233
+ case "#,##0.0": r = Math.round((val-Math.floor(val))*10); return val < 0 ? "-" + write_num(type, fmt, -val) : commaify(String(Math.floor(val))) + "." + r;
234
+ case "#,##0.00": r = Math.round((val-Math.floor(val))*100); return val < 0 ? "-" + write_num(type, fmt, -val) : commaify(String(Math.floor(val))) + "." + (r < 10 ? "0"+r:r);
235
+ case "# ? / ?": ff = frac(aval, 9, true); return sign + (ff[0]||"") + " " + (ff[1] === 0 ? " " : ff[1] + "/" + ff[2]);
236
+ case "# ?? / ??": ff = frac(aval, 99, true); return sign + (ff[0]||"") + " " + (ff[1] ? pad(ff[1],2," ") + "/" + rpad(ff[2],2," ") : " ");
237
+ case "# ??? / ???": ff = frac(aval, 999, true); return sign + (ff[0]||"") + " " + (ff[1] ? pad(ff[1],3," ") + "/" + rpad(ff[2],3," ") : " ");
238
+ default:
239
+ }
240
+ throw new Error("unsupported format |" + fmt + "|");
241
+ };
242
+ function split_fmt(fmt) {
243
+ var out = [];
244
+ var in_str = -1;
245
+ for(var i = 0, j = 0; i < fmt.length; ++i) {
246
+ if(in_str != -1) { if(fmt[i] == '"') in_str = -1; continue; }
247
+ if(fmt[i] == "_" || fmt[i] == "*" || fmt[i] == "\\") { ++i; continue; }
248
+ if(fmt[i] == '"') { in_str = i; continue; }
249
+ if(fmt[i] != ";") continue;
250
+ out.push(fmt.slice(j,i));
251
+ j = i+1;
252
+ }
253
+ out.push(fmt.slice(j));
254
+ if(in_str !=-1) throw "Format |" + fmt + "| unterminated string at " + in_str;
255
+ return out;
256
+ }
257
+ SSF._split = split_fmt;
258
+ function eval_fmt(fmt, v, opts, flen) {
259
+ var out = [], o = "", i = 0, c = "", lst='t', q = {}, dt;
260
+ fixopts(opts = (opts || {}));
261
+ var hr='H';
262
+ /* Tokenize */
263
+ while(i < fmt.length) {
264
+ switch((c = fmt[i])) {
265
+ case '"': /* Literal text */
266
+ for(o="";fmt[++i] !== '"' && i < fmt.length;) o += fmt[i];
267
+ out.push({t:'t', v:o}); ++i; break;
268
+ case '\\': var w = fmt[++i], t = "()".indexOf(w) === -1 ? 't' : w;
269
+ out.push({t:t, v:w}); ++i; break;
270
+ case '_': out.push({t:'t', v:" "}); i+=2; break;
271
+ case '@': /* Text Placeholder */
272
+ out.push({t:'T', v:v}); ++i; break;
273
+ /* Dates */
274
+ case 'm': case 'd': case 'y': case 'h': case 's': case 'e':
275
+ if(v < 0) return "";
276
+ if(!dt) dt = parse_date_code(v, opts);
277
+ o = fmt[i]; while(fmt[++i] === c) o+=c;
278
+ if(c === 's' && fmt[i] === '.' && fmt[i+1] === '0') { o+='.'; while(fmt[++i] === '0') o+= '0'; }
279
+ if(c === 'm' && lst.toLowerCase() === 'h') c = 'M'; /* m = minute */
280
+ if(c === 'h') c = hr;
281
+ q={t:c, v:o}; out.push(q); lst = c; break;
282
+ case 'A':
283
+ if(!dt) dt = parse_date_code(v, opts);
284
+ q={t:c,v:"A"};
285
+ if(fmt.substr(i, 3) === "A/P") {q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
286
+ else if(fmt.substr(i,5) === "AM/PM") { q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; }
287
+ else q.t = "t";
288
+ out.push(q); lst = c; break;
289
+ case '[': /* TODO: Fix this -- ignore all conditionals and formatting */
290
+ o = c;
291
+ while(fmt[i++] !== ']') o += fmt[i];
292
+ if(o == "[h]") out.push({t:'Z', v:o});
293
+ break;
294
+ /* Numbers */
295
+ case '0': case '#':
296
+ o = c; while("0#?.,E+-%".indexOf(c=fmt[++i]) > -1) o += c;
297
+ out.push({t:'n', v:o}); break;
298
+ case '?':
299
+ o = fmt[i]; while(fmt[++i] === c) o+=c;
300
+ q={t:c, v:o}; out.push(q); lst = c; break;
301
+ case '*': ++i; if(fmt[i] == ' ') ++i; break; // **
302
+ case '(': case ')': out.push({t:(flen===1?'t':c),v:c}); ++i; break;
303
+ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
304
+ o = fmt[i]; while("0123456789".indexOf(fmt[++i]) > -1) o+=fmt[i];
305
+ out.push({t:'D', v:o}); break;
306
+ case ' ': out.push({t:c,v:c}); ++i; break;
307
+ default:
308
+ if("$-+/():!^&'~{}<>=".indexOf(c) === -1)
309
+ throw 'unrecognized character ' + fmt[i] + ' in ' + fmt;
310
+ out.push({t:'t', v:c}); ++i; break;
311
+ }
312
+ }
313
+
314
+ /* walk backwards */
315
+ for(i=out.length-1, lst='t'; i >= 0; --i) {
316
+ switch(out[i].t) {
317
+ case 'h': case 'H': out[i].t = hr; lst='h'; break;
318
+ case 'd': case 'y': case 's': case 'M': case 'e': lst=out[i].t; break;
319
+ case 'm': if(lst === 's') out[i].t = 'M'; break;
320
+ }
321
+ }
322
+
323
+ /* replace fields */
324
+ for(i=0; i < out.length; ++i) {
325
+ switch(out[i].t) {
326
+ case 't': case 'T': case ' ': break;
327
+ case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'A': case 'e': case 'Z':
328
+ out[i].v = write_date(out[i].t, out[i].v, dt);
329
+ out[i].t = 't'; break;
330
+ case 'n': case '(':
331
+ var jj = i+1;
332
+ while(out[jj] && ("? D".indexOf(out[jj].t) > -1 || out[i].t == '(' && (out[jj].t == ')' || out[jj].t == 'n') || out[jj].t == 't' && (out[jj].v == '/' || out[jj].v == '$' || (out[jj].v == ' ' && (out[jj+1]||{}).t == '?')))) {
333
+ if(out[jj].v!==' ') out[i].v += ' ' + out[jj].v;
334
+ delete out[jj]; ++jj;
335
+ }
336
+ out[i].v = write_num(out[i].t, out[i].v, v);
337
+ out[i].t = 't';
338
+ i = jj; break;
339
+ default: throw "unrecognized type " + out[i].t;
340
+ }
341
+ }
342
+
343
+ return out.map(function(x){return x.v;}).join("");
344
+ }
345
+ SSF._eval = eval_fmt;
346
+ function choose_fmt(fmt, v, o) {
347
+ if(typeof fmt === 'number') fmt = table_fmt[fmt];
348
+ if(typeof fmt === "string") fmt = split_fmt(fmt);
349
+ var l = fmt.length;
350
+ switch(fmt.length) {
351
+ case 1: fmt = [fmt[0], fmt[0], fmt[0], "@"]; break;
352
+ case 2: fmt = [fmt[0], fmt[fmt[1] === "@"?0:1], fmt[0], "@"]; break;
353
+ case 4: break;
354
+ default: throw "cannot find right format for |" + fmt + "|";
355
+ }
356
+ if(typeof v !== "number") return [fmt.length, fmt[3]];
357
+ return [l, v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2]];
358
+ }
359
+
360
+ var format = function format(fmt,v,o) {
361
+ fixopts(o = (o||{}));
362
+ if(fmt === 0) return general_fmt(v, o);
363
+ if(typeof fmt === 'number') fmt = table_fmt[fmt];
364
+ var f = choose_fmt(fmt, v, o);
365
+ return eval_fmt(f[1], v, o, f[0]);
366
+ };
367
+
368
+ SSF._choose = choose_fmt;
369
+ SSF._table = table_fmt;
370
+ SSF.load = function(fmt, idx) { table_fmt[idx] = fmt; };
371
+ SSF.format = format;
372
+ };
373
+ make_ssf(SSF);
374
+ var XLSX = {};
375
+ (function(XLSX){
376
+ function parsexmltag(tag) {
377
+ var words = tag.split(/\s+/);
378
+ var z = {'0': words[0]};
379
+ if(words.length === 1) return z;
380
+ (tag.match(/(\w+)="([^"]*)"/g) || []).map(
381
+ function(x){var y=x.match(/(\w+)="([^"]*)"/); z[y[1]] = y[2]; });
382
+ return z;
383
+ }
384
+
385
+ var encodings = {
386
+ '&quot;': '"',
387
+ '&apos;': "'",
388
+ '&gt;': '>',
389
+ '&lt;': '<',
390
+ '&amp;': '&'
391
+ };
392
+
393
+ // TODO: CP remap (need to read file version to determine OS)
394
+ function unescapexml(text){
395
+ var s = text + '';
396
+ for(var y in encodings) s = s.replace(new RegExp(y,'g'), encodings[y]);
397
+ return s.replace(/_x([0-9a-fA-F]*)_/g,function(m,c) {return _chr(parseInt(c,16));});
398
+ }
399
+
400
+ function parsexmlbool(value, tag) {
401
+ switch(value) {
402
+ case '0': case 0: case 'false': case 'FALSE': return false;
403
+ case '1': case 1: case 'true': case 'TRUE': return true;
404
+ default: throw "bad boolean value " + value + " in "+(tag||"?");
405
+ }
406
+ }
407
+
408
+ var utf8read = function(orig) {
409
+ var out = "", i = 0, c = 0, c1 = 0, c2 = 0, c3 = 0;
410
+ while (i < orig.length) {
411
+ c = orig.charCodeAt(i++);
412
+ if (c < 128) out += _chr(c);
413
+ else {
414
+ c2 = orig.charCodeAt(i++);
415
+ if (c>191 && c<224) out += _chr((c & 31) << 6 | c2 & 63);
416
+ else {
417
+ c3 = orig.charCodeAt(i++);
418
+ out += _chr((c & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
419
+ }
420
+ }
421
+ }
422
+ return out;
423
+ };
424
+
425
+ // matches <foo>...</foo> extracts content
426
+ function matchtag(f,g) {return new RegExp('<'+f+'(?: xml:space="preserve")?>([^\u2603]*)</'+f+'>',(g||"")+"m");}
427
+
428
+ function parseVector(data) {
429
+ var h = parsexmltag(data);
430
+
431
+ var matches = data.match(new RegExp("<vt:" + h.baseType + ">(.*?)</vt:" + h.baseType + ">", 'g'))||[];
432
+ if(matches.length != h.size) throw "unexpected vector length " + matches.length + " != " + h.size;
433
+ var res = [];
434
+ matches.forEach(function(x) {
435
+ var v = x.replace(/<[/]?vt:variant>/g,"").match(/<vt:([^>]*)>(.*)</);
436
+ res.push({v:v[2], t:v[1]});
437
+ });
438
+ return res;
439
+ }
440
+
441
+ function isval(x) { return typeof x !== "undefined" && x !== null; }
442
+ /* 18.4 Shared String Table */
443
+ var parse_sst = (function(){
444
+ var tregex = matchtag("t"), rpregex = matchtag("rPr");
445
+ /* Parse a list of <r> tags */
446
+ var parse_rs = (function() {
447
+ /* 18.4.7 rPr CT_RPrElt */
448
+ var parse_rpr = function(rpr, intro, outro) {
449
+ var font = {};
450
+ (rpr.match(/<[^>]*>/g)||[]).forEach(function(x) {
451
+ var y = parsexmltag(x);
452
+ switch(y[0]) {
453
+ /* 18.8.12 condense CT_BooleanProperty */
454
+ /* ** not required . */
455
+ case '<condense': break;
456
+ /* 18.8.17 extend CT_BooleanProperty */
457
+ /* ** not required . */
458
+ case '<extend': break;
459
+ /* 18.8.36 shadow CT_BooleanProperty */
460
+ /* ** not required . */
461
+ case '<shadow': break;
462
+
463
+ /* 18.4.1 charset CT_IntProperty TODO */
464
+ case '<charset': break;
465
+
466
+ /* 18.4.2 outline CT_BooleanProperty TODO */
467
+ case '<outline': break;
468
+
469
+ /* 18.4.5 rFont CT_FontName */
470
+ case '<rFont': font.name = y.val; break;
471
+
472
+ /* 18.4.11 sz CT_FontSize */
473
+ case '<sz': font.sz = y.val; break;
474
+
475
+ /* 18.4.10 strike CT_BooleanProperty */
476
+ case '<strike':
477
+ if(!y.val) break;
478
+ /* falls through */
479
+ case '<strike/>': font.strike = 1; break;
480
+ case '</strike>': break;
481
+
482
+ /* 18.4.13 u CT_UnderlineProperty */
483
+ case '<u':
484
+ if(!y.val) break;
485
+ /* falls through */
486
+ case '<u/>': font.u = 1; break;
487
+ case '</u>': break;
488
+
489
+ /* 18.8.2 b */
490
+ case '<b':
491
+ if(!y.val) break;
492
+ /* falls through */
493
+ case '<b/>': font.b = 1; break;
494
+ case '</b>': break;
495
+
496
+ /* 18.8.26 i */
497
+ case '<i':
498
+ if(!y.val) break;
499
+ /* falls through */
500
+ case '<i/>': font.i = 1; break;
501
+ case '</i>': break;
502
+
503
+ /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
504
+ case '<color':
505
+ if(y.rgb) font.color = y.rgb.substr(2,6);
506
+ break;
507
+
508
+ /* 18.8.18 family ST_FontFamily */
509
+ case '<family': font.family = y.val; break;
510
+
511
+ /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
512
+ case '<vertAlign': break;
513
+
514
+ /* 18.8.35 scheme CT_FontScheme TODO */
515
+ case '<scheme': break;
516
+
517
+ default:
518
+ if(y[0][2] !== '/') throw 'Unrecognized rich format ' + y[0];
519
+ }
520
+ });
521
+ /* TODO: These should be generated styles, not inline */
522
+ var style = [];
523
+ if(font.b) style.push("font-weight: bold;");
524
+ if(font.i) style.push("font-style: italic;");
525
+ intro.push('<span style="' + style.join("") + '">');
526
+ outro.push("</span>");
527
+ };
528
+
529
+ /* 18.4.4 r CT_RElt */
530
+ function parse_r(r) {
531
+ var terms = [[],"",[]];
532
+ /* 18.4.12 t ST_Xstring */
533
+ var t = r.match(tregex);
534
+ if(!isval(t)) return "";
535
+ terms[1] = t[1];
536
+
537
+ var rpr = r.match(rpregex);
538
+ if(isval(rpr)) parse_rpr(rpr[1], terms[0], terms[2]);
539
+ return terms[0].join("") + terms[1].replace(/\r\n/g,'<br/>') + terms[2].join("");
540
+ }
541
+ return function(rs) {
542
+ return rs.replace(/<r>/g,"").split(/<\/r>/).map(parse_r).join("");
543
+ };
544
+ })();
545
+
546
+ /* 18.4.8 si CT_Rst */
547
+ var parse_si = function(x) {
548
+ var z = {};
549
+ if(!x) return z;
550
+ var y;
551
+ /* 18.4.12 t ST_Xstring (Plaintext String) */
552
+ if(x[1] === 't') {
553
+ z.t = utf8read(unescapexml(x.replace(/<[^>]*>/g,"")));
554
+ z.raw = x;
555
+ z.r = z.t;
556
+ }
557
+ /* 18.4.4 r CT_RElt (Rich Text Run) */
558
+ else if((y = x.match(/<r>/))) {
559
+ z.raw = x;
560
+ /* TODO: properly parse (note: no other valid child can have body text) */
561
+ z.t = utf8read(unescapexml(x.replace(/<[^>]*>/gm,"")));
562
+ z.r = parse_rs(x);
563
+ }
564
+ /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
565
+ /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
566
+ return z;
567
+ };
568
+
569
+
570
+ return function(data) {
571
+ var s = [];
572
+ /* 18.4.9 sst CT_Sst */
573
+ var sst = data.match(new RegExp("<sst([^>]*)>([\\s\\S]*)<\/sst>","m"));
574
+ if(isval(sst)) {
575
+ s = sst[2].replace(/<si>/g,"").split(/<\/si>/).map(parse_si);
576
+ sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
577
+ }
578
+ return s;
579
+ };
580
+ })();
581
+
582
+ var ct2type = {
583
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
584
+ "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
585
+ "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
586
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
587
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":"sheets",
588
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs",
589
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":"styles",
590
+ "application/vnd.openxmlformats-officedocument.theme+xml":"themes",
591
+ "foo": "bar"
592
+ };
593
+
594
+ /* 18.2.28 (CT_WorkbookProtection) Defaults */
595
+ var WBPropsDef = {
596
+ allowRefreshQuery: '0',
597
+ autoCompressPictures: '1',
598
+ backupFile: '0',
599
+ checkCompatibility: '0',
600
+ codeName: '',
601
+ date1904: '0',
602
+ dateCompatibility: '1',
603
+ //defaultThemeVersion: '0',
604
+ filterPrivacy: '0',
605
+ hidePivotFieldList: '0',
606
+ promptedSolutions: '0',
607
+ publishItems: '0',
608
+ refreshAllConnections: false,
609
+ saveExternalLinkValues: '1',
610
+ showBorderUnselectedTables: '1',
611
+ showInkAnnotation: '1',
612
+ showObjects: 'all',
613
+ showPivotChartFilter: '0'
614
+ //updateLinks: 'userSet'
615
+ };
616
+
617
+ /* 18.2.30 (CT_BookView) Defaults */
618
+ var WBViewDef = {
619
+ activeTab: '0',
620
+ autoFilterDateGrouping: '1',
621
+ firstSheet: '0',
622
+ minimized: '0',
623
+ showHorizontalScroll: '1',
624
+ showSheetTabs: '1',
625
+ showVerticalScroll: '1',
626
+ tabRatio: '600',
627
+ visibility: 'visible'
628
+ //window{Height,Width}, {x,y}Window
629
+ };
630
+
631
+ /* 18.2.19 (CT_Sheet) Defaults */
632
+ var SheetDef = {
633
+ state: 'visible'
634
+ };
635
+
636
+ /* 18.2.2 (CT_CalcPr) Defaults */
637
+ var CalcPrDef = {
638
+ calcCompleted: 'true',
639
+ calcMode: 'auto',
640
+ calcOnSave: 'true',
641
+ concurrentCalc: 'true',
642
+ fullCalcOnLoad: 'false',
643
+ fullPrecision: 'true',
644
+ iterate: 'false',
645
+ iterateCount: '100',
646
+ iterateDelta: '0.001',
647
+ refMode: 'A1'
648
+ };
649
+
650
+ /* 18.2.3 (CT_CustomWorkbookView) Defaults */
651
+ var CustomWBViewDef = {
652
+ autoUpdate: 'false',
653
+ changesSavedWin: 'false',
654
+ includeHiddenRowCol: 'true',
655
+ includePrintSettings: 'true',
656
+ maximized: 'false',
657
+ minimized: 'false',
658
+ onlySync: 'false',
659
+ personalView: 'false',
660
+ showComments: 'commIndicator',
661
+ showFormulaBar: 'true',
662
+ showHorizontalScroll: 'true',
663
+ showObjects: 'all',
664
+ showSheetTabs: 'true',
665
+ showStatusbar: 'true',
666
+ showVerticalScroll: 'true',
667
+ tabRatio: '600',
668
+ xWindow: '0',
669
+ yWindow: '0'
670
+ };
671
+
672
+ var XMLNS_CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
673
+ var XMLNS_WB = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
674
+
675
+ var strs = {}; // shared strings
676
+ var styles = {}; // shared styles
677
+ var _ssfopts = {}; // spreadsheet formatting options
678
+
679
+ /* 18.3 Worksheets */
680
+ function parseSheet(data) {
681
+ if(!data) return data;
682
+ /* 18.3.1.99 worksheet CT_Worksheet */
683
+ var s = {};
684
+
685
+ /* 18.3.1.35 dimension CT_SheetDimension ? */
686
+ var ref = data.match(/<dimension ref="([^"]*)"\s*\/>/);
687
+ if(ref && ref.length == 2 && ref[1].indexOf(":") !== -1) s["!ref"] = ref[1];
688
+
689
+ var refguess = {s: {r:1000000, c:1000000}, e: {r:0, c:0} };
690
+ var q = ["v","f"];
691
+ var sidx = 0;
692
+ /* 18.3.1.80 sheetData CT_SheetData ? */
693
+ if(!data.match(/<sheetData *\/>/))
694
+ data.match(/<sheetData>([^\u2603]*)<\/sheetData>/m)[1].split("</row>").forEach(function(x) {
695
+ if(x === "" || x.trim() === "") return;
696
+
697
+ /* 18.3.1.73 row CT_Row */
698
+ var row = parsexmltag(x.match(/<row[^>]*>/)[0]);
699
+ if(refguess.s.r > row.r - 1) refguess.s.r = row.r - 1;
700
+ if(refguess.e.r < row.r - 1) refguess.e.r = row.r - 1;
701
+
702
+ /* 18.3.1.4 c CT_Cell */
703
+ var cells = x.substr(x.indexOf('>')+1).split(/<c/);
704
+ cells.forEach(function(c, idx) { if(c === "" || c.trim() === "") return;
705
+ var cref = c.match(/r="([^"]*)"/);
706
+ c = "<c" + c;
707
+ if(cref && cref.length == 2) {
708
+ var cref_cell = decode_cell(cref[1]);
709
+ idx = cref_cell.c;
710
+ }
711
+ if(refguess.s.c > idx) refguess.s.c = idx;
712
+ if(refguess.e.c < idx) refguess.e.c = idx;
713
+ var cell = parsexmltag((c.match(/<c[^>]*>/)||[c])[0]); delete cell[0];
714
+ var d = c.substr(c.indexOf('>')+1);
715
+ var p = {};
716
+ q.forEach(function(f){var x=d.match(matchtag(f));if(x)p[f]=unescapexml(x[1]);});
717
+
718
+ /* SCHEMA IS ACTUALLY INCORRECT HERE. IF A CELL HAS NO T, EMIT "" */
719
+ if(cell.t === undefined && p.v === undefined) { p.t = "str"; p.v = undefined; }
720
+ else p.t = (cell.t ? cell.t : "n"); // default is "n" in schema
721
+ switch(p.t) {
722
+ case 'n': p.v = parseFloat(p.v); break;
723
+ case 's': {
724
+ sidx = parseInt(p.v, 10);
725
+ p.v = strs[sidx].t;
726
+ p.r = strs[sidx].r;
727
+ } break;
728
+ case 'str': if(p.v) p.v = utf8read(p.v); break; // normal string
729
+ case 'inlineStr':
730
+ p.t = 'str'; p.v = unescapexml((d.match(matchtag('t'))||["",""])[1]);
731
+ break; // inline string
732
+ case 'b':
733
+ switch(p.v) {
734
+ case '0': case 'FALSE': case "false": case false: p.v=false; break;
735
+ case '1': case 'TRUE': case "true": case true: p.v=true; break;
736
+ default: throw "Unrecognized boolean: " + p.v;
737
+ } break;
738
+ /* in case of error, stick value in .raw */
739
+ case 'e': p.raw = p.v; p.v = undefined; break;
740
+ default: throw "Unrecognized cell type: " + p.t;
741
+ }
742
+
743
+ /* formatting */
744
+ if(cell.s && styles.CellXf) { /* TODO: second check is a hacked guard */
745
+ var cf = styles.CellXf[cell.s];
746
+ if(cf && cf.numFmtId && cf.numFmtId !== 0) {
747
+ p.raw = p.v;
748
+ p.rawt = p.t;
749
+ try {
750
+ p.v = SSF.format(cf.numFmtId,p.v,_ssfopts);
751
+ p.t = 'str';
752
+ } catch(e) { p.v = p.raw; }
753
+ }
754
+ }
755
+
756
+ s[cell.r] = p;
757
+ });
758
+ });
759
+ if(!s["!ref"]) s["!ref"] = encode_range(refguess);
760
+ return s;
761
+ }
762
+
763
+ function parseProps(data) {
764
+ var p = { Company:'' }, q = {};
765
+ var strings = ["Application", "DocSecurity", "Company", "AppVersion"];
766
+ var bools = ["HyperlinksChanged","SharedDoc","LinksUpToDate","ScaleCrop"];
767
+ var xtra = ["HeadingPairs", "TitlesOfParts"];
768
+ var xtracp = ["category", "contentStatus", "lastModifiedBy", "lastPrinted", "revision", "version"];
769
+ var xtradc = ["creator", "description", "identifier", "language", "subject", "title"];
770
+ var xtradcterms = ["created", "modified"];
771
+ xtra = xtra.concat(xtracp.map(function(x) { return "cp:" + x; }));
772
+ xtra = xtra.concat(xtradc.map(function(x) { return "dc:" + x; }));
773
+ xtra = xtra.concat(xtradcterms.map(function(x) { return "dcterms:" + x; }));
774
+
775
+
776
+ strings.forEach(function(f){p[f] = (data.match(matchtag(f))||[])[1];});
777
+ bools.forEach(function(f){p[f] = (data.match(matchtag(f))||[])[1] == "true";});
778
+ xtra.forEach(function(f) {
779
+ var cur = data.match(new RegExp("<" + f + "[^>]*>(.*)<\/" + f + ">"));
780
+ if(cur && cur.length > 0) q[f] = cur[1];
781
+ });
782
+
783
+ if(q.HeadingPairs && q.TitlesOfParts) {
784
+ var v = parseVector(q.HeadingPairs);
785
+ var j = 0, widx = 0;
786
+ for(var i = 0; i !== v.length; ++i) {
787
+ switch(v[i].v) {
788
+ case "Worksheets": widx = j; p.Worksheets = +v[++i]; break;
789
+ case "Named Ranges": ++i; break; // TODO: Handle Named Ranges
790
+ }
791
+ }
792
+ var parts = parseVector(q.TitlesOfParts).map(utf8read);
793
+ p.SheetNames = parts.slice(widx, widx + p.Worksheets);
794
+ }
795
+ p.Creator = q["dc:creator"];
796
+ p.LastModifiedBy = q["cp:lastModifiedBy"];
797
+ p.CreatedDate = new Date(q["dcterms:created"]);
798
+ p.ModifiedDate = new Date(q["dcterms:modified"]);
799
+ return p;
800
+ }
801
+
802
+ /* 18.6 Calculation Chain */
803
+ function parseDeps(data) {
804
+ var d = [];
805
+ var l = 0, i = 1;
806
+ (data.match(/<[^>]*>/g)||[]).forEach(function(x) {
807
+ var y = parsexmltag(x);
808
+ switch(y[0]) {
809
+ case '<?xml': break;
810
+ /* 18.6.2 calcChain CT_CalcChain 1 */
811
+ case '<calcChain': case '<calcChain>': case '</calcChain>': break;
812
+ /* 18.6.1 c CT_CalcCell 1 */
813
+ case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
814
+ }
815
+ });
816
+ return d;
817
+ }
818
+
819
+ var ctext = {};
820
+
821
+ function parseCT(data) {
822
+ if(!data || !data.match) return data;
823
+ var ct = { workbooks: [], sheets: [], calcchains: [], themes: [], styles: [],
824
+ coreprops: [], extprops: [], strs:[], xmlns: "" };
825
+ (data.match(/<[^>]*>/g)||[]).forEach(function(x) {
826
+ var y = parsexmltag(x);
827
+ switch(y[0]) {
828
+ case '<?xml': break;
829
+ case '<Types': ct.xmlns = y.xmlns; break;
830
+ case '<Default': ctext[y.Extension] = y.ContentType; break;
831
+ case '<Override':
832
+ if(y.ContentType in ct2type)ct[ct2type[y.ContentType]].push(y.PartName);
833
+ break;
834
+ }
835
+ });
836
+ if(ct.xmlns !== XMLNS_CT) throw new Error("Unknown Namespace: " + ct.xmlns);
837
+ ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
838
+ ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
839
+ ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
840
+ delete ct.calcchains;
841
+ return ct;
842
+ }
843
+
844
+
845
+ /* 18.2 Workbook */
846
+ function parseWB(data) {
847
+ var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
848
+ var pass = false;
849
+ data.match(/<[^>]*>/g).forEach(function(x) {
850
+ var y = parsexmltag(x);
851
+ switch(y[0]) {
852
+ case '<?xml': break;
853
+
854
+ /* 18.2.27 workbook CT_Workbook 1 */
855
+ case '<workbook': wb.xmlns = y.xmlns; break;
856
+ case '</workbook>': break;
857
+
858
+ /* 18.2.13 fileVersion CT_FileVersion ? */
859
+ case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
860
+ case '<fileVersion/>': break;
861
+
862
+ /* 18.2.12 fileSharing CT_FileSharing ? */
863
+ case '<fileSharing': case '<fileSharing/>': break;
864
+
865
+ /* 18.2.28 workbookPr CT_WorkbookPr ? */
866
+ case '<workbookPr': delete y[0]; wb.WBProps = y; break;
867
+ case '<workbookPr/>': delete y[0]; wb.WBProps = y; break;
868
+
869
+ /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
870
+ case '<workbookProtection/>': break;
871
+
872
+ /* 18.2.1 bookViews CT_BookViews ? */
873
+ case '<bookViews>': case '</bookViews>': break;
874
+ /* 18.2.30 workbookView CT_BookView + */
875
+ case '<workbookView': delete y[0]; wb.WBView.push(y); break;
876
+
877
+ /* 18.2.20 sheets CT_Sheets 1 */
878
+ case '<sheets>': case '</sheets>': break; // aggregate sheet
879
+ /* 18.2.19 sheet CT_Sheet + */
880
+ case '<sheet': delete y[0]; y.name = utf8read(y.name); wb.Sheets.push(y); break;
881
+
882
+ /* 18.2.15 functionGroups CT_FunctionGroups ? */
883
+ case '<functionGroups': case '<functionGroups/>': break;
884
+ /* 18.2.14 functionGroup CT_FunctionGroup + */
885
+ case '<functionGroup': break;
886
+
887
+ /* 18.2.9 externalReferences CT_ExternalReferences ? */
888
+ case '<externalReferences': case '</externalReferences>': break;
889
+ /* 18.2.8 externalReference CT_ExternalReference + */
890
+ case '<externalReference': break;
891
+
892
+ /* 18.2.6 definedNames CT_DefinedNames ? */
893
+ case '<definedNames/>': break;
894
+ case '<definedNames>': pass=true; break;
895
+ case '</definedNames>': pass=false; break;
896
+ /* 18.2.5 definedName CT_DefinedName + */
897
+ case '<definedName': case '<definedName/>': case '</definedName>': break;
898
+
899
+ /* 18.2.2 calcPr CT_CalcPr ? */
900
+ case '<calcPr': delete y[0]; wb.CalcPr = y; break;
901
+ case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
902
+
903
+ /* 18.2.16 oleSize CT_OleSize ? (ref required) */
904
+ case '<oleSize': break;
905
+
906
+ /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
907
+ case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
908
+ /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
909
+ case '<customWorkbookView': case '</customWorkbookView>': break;
910
+
911
+ /* 18.2.18 pivotCaches CT_PivotCaches ? */
912
+ case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
913
+ /* 18.2.17 pivotCache CT_PivotCache ? */
914
+ case '<pivotCache': break;
915
+
916
+ /* 18.2.21 smartTagPr CT_SmartTagPr ? */
917
+ case '<smartTagPr': case '<smartTagPr/>': break;
918
+
919
+ /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
920
+ case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
921
+ /* 18.2.22 smartTagType CT_SmartTagType ? */
922
+ case '<smartTagType': break;
923
+
924
+ /* 18.2.24 webPublishing CT_WebPublishing ? */
925
+ case '<webPublishing': case '<webPublishing/>': break;
926
+
927
+ /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
928
+ case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
929
+
930
+ /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
931
+ case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
932
+ /* 18.2.25 webPublishObject CT_WebPublishObject ? */
933
+ case '<webPublishObject': break;
934
+
935
+ /* 18.2.10 extLst CT_ExtensionList ? */
936
+ case '<extLst>': case '</extLst>': case '<extLst/>': break;
937
+ /* 18.2.7 ext CT_Extension + */
938
+ case '<ext': pass=true; break; //TODO: check with versions of excel
939
+ case '</ext>': pass=false; break;
940
+
941
+ /* Others */
942
+ case '<mx:ArchID': break;
943
+ case '<mc:AlternateContent': pass=true; break;
944
+ case '</mc:AlternateContent>': pass=false; break;
945
+ }
946
+ });
947
+ if(wb.xmlns !== XMLNS_WB) throw new Error("Unknown Namespace: " + wb.xmlns);
948
+
949
+ var z;
950
+ /* defaults */
951
+ for(z in WBPropsDef) if(typeof wb.WBProps[z] === 'undefined') wb.WBProps[z] = WBPropsDef[z];
952
+ for(z in CalcPrDef) if(typeof wb.CalcPr[z] === 'undefined') wb.CalcPr[z] = CalcPrDef[z];
953
+
954
+ wb.WBView.forEach(function(w){for(var z in WBViewDef) if(typeof w[z] === 'undefined') w[z]=WBViewDef[z]; });
955
+ wb.Sheets.forEach(function(w){for(var z in SheetDef) if(typeof w[z] === 'undefined') w[z]=SheetDef[z]; });
956
+
957
+ _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904, 'date1904');
958
+
959
+ return wb;
960
+ }
961
+
962
+ /* 18.8.31 numFmts CT_NumFmts */
963
+ function parseNumFmts(t) {
964
+ styles.NumberFmt = [];
965
+ for(var y in SSF._table) styles.NumberFmt[y] = SSF._table[y];
966
+ t[0].match(/<[^>]*>/g).forEach(function(x) {
967
+ var y = parsexmltag(x);
968
+ switch(y[0]) {
969
+ case '<numFmts': case '</numFmts>': case '<numFmts/>': break;
970
+ case '<numFmt': {
971
+ var f=unescapexml(y.formatCode), i=parseInt(y.numFmtId,10);
972
+ styles.NumberFmt[i] = f; SSF.load(f,i);
973
+ } break;
974
+ default: throw 'unrecognized ' + y[0] + ' in numFmts';
975
+ }
976
+ });
977
+ }
978
+
979
+ /* 18.8.10 cellXfs CT_CellXfs */
980
+ function parseCXfs(t) {
981
+ styles.CellXf = [];
982
+ t[0].match(/<[^>]*>/g).forEach(function(x) {
983
+ var y = parsexmltag(x);
984
+ switch(y[0]) {
985
+ case '<cellXfs': case '<cellXfs/>': case '</cellXfs>': break;
986
+
987
+ /* 18.8.45 xf CT_Xf */
988
+ case '<xf': if(y.numFmtId) y.numFmtId = parseInt(y.numFmtId, 10);
989
+ styles.CellXf.push(y); break;
990
+ case '</xf>': break;
991
+
992
+ /* 18.8.1 alignment CT_CellAlignment */
993
+ case '<alignment': break;
994
+
995
+ /* 18.8.33 protection CT_CellProtection */
996
+ case '<protection': case '</protection>': case '<protection/>': break;
997
+
998
+ case '<extLst': case '</extLst>': break;
999
+ case '<ext': break;
1000
+ default: throw 'unrecognized ' + y[0] + ' in cellXfs';
1001
+ }
1002
+ });
1003
+ }
1004
+
1005
+ /* 18.8 Styles CT_Stylesheet*/
1006
+ function parseStyles(data) {
1007
+ /* 18.8.39 styleSheet CT_Stylesheet */
1008
+ var t;
1009
+
1010
+ /* numFmts CT_NumFmts ? */
1011
+ if((t=data.match(/<numFmts([^>]*)>.*<\/numFmts>/))) parseNumFmts(t);
1012
+
1013
+ /* fonts CT_Fonts ? */
1014
+ /* fills CT_Fills ? */
1015
+ /* borders CT_Borders ? */
1016
+ /* cellStyleXfs CT_CellStyleXfs ? */
1017
+
1018
+ /* cellXfs CT_CellXfs ? */
1019
+ if((t=data.match(/<cellXfs([^>]*)>.*<\/cellXfs>/))) parseCXfs(t);
1020
+
1021
+ /* dxfs CT_Dxfs ? */
1022
+ /* tableStyles CT_TableStyles ? */
1023
+ /* colors CT_Colors ? */
1024
+ /* extLst CT_ExtensionList ? */
1025
+
1026
+ return styles;
1027
+ }
1028
+
1029
+ function getdata(data) {
1030
+ if(!data) return null;
1031
+ if(data.data) return data.data;
1032
+ if(data._data && data._data.getContent) return Array.prototype.slice.call(data._data.getContent(),0).map(function(x) { return String.fromCharCode(x); }).join("");
1033
+ return null;
1034
+ }
1035
+
1036
+ function getzipfile(zip, file) {
1037
+ var f = file; if(zip.files[f]) return zip.files[f];
1038
+ f = file.toLowerCase(); if(zip.files[f]) return zip.files[f];
1039
+ f = f.replace(/\//g,'\\'); if(zip.files[f]) return zip.files[f];
1040
+ throw new Error("Cannot find file " + file + " in zip");
1041
+ }
1042
+
1043
+ function parseZip(zip) {
1044
+ var entries = Object.keys(zip.files);
1045
+ var keys = entries.filter(function(x){return x.substr(-1) != '/';}).sort();
1046
+ var dir = parseCT(getdata(getzipfile(zip, '[Content_Types].xml')));
1047
+ if(dir.workbooks.length === 0) throw new Error("Could not find workbook entry");
1048
+ strs = {};
1049
+ if(dir.sst) strs=parse_sst(getdata(getzipfile(zip, dir.sst.replace(/^\//,''))));
1050
+
1051
+ styles = {};
1052
+ if(dir.style) styles = parseStyles(getdata(getzipfile(zip, dir.style.replace(/^\//,''))));
1053
+
1054
+ var wb = parseWB(getdata(getzipfile(zip, dir.workbooks[0].replace(/^\//,''))));
1055
+ var propdata = dir.coreprops.length !== 0 ? getdata(getzipfile(zip, dir.coreprops[0].replace(/^\//,''))) : "";
1056
+ propdata += dir.extprops.length !== 0 ? getdata(getzipfile(zip, dir.extprops[0].replace(/^\//,''))) : "";
1057
+ var props = propdata !== "" ? parseProps(propdata) : {};
1058
+ var deps = {};
1059
+ if(dir.calcchain) deps=parseDeps(getdata(getzipfile(zip, dir.calcchain.replace(/^\//,''))));
1060
+ var sheets = {}, i=0;
1061
+ if(!props.Worksheets) {
1062
+ /* Google Docs doesn't generate the appropriate metadata, so we impute: */
1063
+ var wbsheets = wb.Sheets;
1064
+ props.Worksheets = wbsheets.length;
1065
+ props.SheetNames = [];
1066
+ for(var j = 0; j != wbsheets.length; ++j) {
1067
+ props.SheetNames[j] = wbsheets[j].name;
1068
+ }
1069
+ for(i = 0; i != props.Worksheets; ++i) {
1070
+ try { /* TODO: remove these guards */
1071
+ sheets[props.SheetNames[i]]=parseSheet(getdata(getzipfile(zip, 'xl/worksheets/sheet' + (i+1) + '.xml')));
1072
+ } catch(e) {}
1073
+ }
1074
+ }
1075
+ else {
1076
+ for(i = 0; i != props.Worksheets; ++i) {
1077
+ try {
1078
+ sheets[props.SheetNames[i]]=parseSheet(getdata(getzipfile(zip, dir.sheets[i].replace(/^\//,''))));
1079
+ } catch(e) {}
1080
+ }
1081
+ }
1082
+ return {
1083
+ Directory: dir,
1084
+ Workbook: wb,
1085
+ Props: props,
1086
+ Deps: deps,
1087
+ Sheets: sheets,
1088
+ SheetNames: props.SheetNames,
1089
+ Strings: strs,
1090
+ Styles: styles,
1091
+ keys: keys,
1092
+ files: zip.files
1093
+ };
1094
+ }
1095
+
1096
+ var _fs, jszip;
1097
+ if(typeof JSZip !== 'undefined') jszip = JSZip;
1098
+ if (typeof exports !== 'undefined') {
1099
+ if (typeof module !== 'undefined' && module.exports) {
1100
+ if(typeof jszip === 'undefined') jszip = require('./jszip').JSZip;
1101
+ _fs = require('fs');
1102
+ }
1103
+ }
1104
+
1105
+ function readSync(data, options) {
1106
+ var zip, d = data;
1107
+ var o = options||{};
1108
+ switch((o.type||"base64")){
1109
+ case "file": d = _fs.readFileSync(data).toString('base64');
1110
+ /* falls through */
1111
+ case "base64": zip = new jszip(d, { base64:true }); break;
1112
+ case "binary": zip = new jszip(d, { base64:false }); break;
1113
+ }
1114
+ return parseZip(zip);
1115
+ }
1116
+
1117
+ function readFileSync(data, options) {
1118
+ var o = options||{}; o.type = 'file';
1119
+ return readSync(data, o);
1120
+ }
1121
+
1122
+ XLSX.read = readSync;
1123
+ XLSX.readFile = readFileSync;
1124
+ XLSX.parseZip = parseZip;
1125
+ return this;
1126
+
1127
+ })(XLSX);
1128
+
1129
+ var _chr = function(c) { return String.fromCharCode(c); };
1130
+
1131
+ function encode_col(col) { var s=""; for(++col; col; col=Math.floor((col-1)/26)) s = _chr(((col-1)%26) + 65) + s; return s; }
1132
+ function encode_row(row) { return "" + (row + 1); }
1133
+ function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
1134
+
1135
+ function decode_col(c) { var d = 0, i = 0; for(; i !== c.length; ++i) d = 26*d + c.charCodeAt(i) - 64; return d - 1; }
1136
+ function decode_row(rowstr) { return Number(rowstr) - 1; }
1137
+ function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?[0-9]*)/,"$1,$2").split(","); }
1138
+ function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
1139
+ function decode_range(range) { var x =range.split(":").map(decode_cell); return {s:x[0],e:x[x.length-1]}; }
1140
+ function encode_range(range) { return encode_cell(range.s) + ":" + encode_cell(range.e); }
1141
+ /**
1142
+ * Convert a sheet into an array of objects where the column headers are keys.
1143
+ **/
1144
+ function sheet_to_row_object_array(sheet){
1145
+ var val, rowObject, range, columnHeaders, emptyRow, C;
1146
+ var outSheet = [];
1147
+ if (sheet["!ref"]) {
1148
+ range = decode_range(sheet["!ref"]);
1149
+
1150
+ columnHeaders = {};
1151
+ for (C = range.s.c; C <= range.e.c; ++C) {
1152
+ val = sheet[encode_cell({
1153
+ c: C,
1154
+ r: range.s.r
1155
+ })];
1156
+ if(val){
1157
+ switch(val.t) {
1158
+ case 's': case 'str': columnHeaders[C] = val.v; break;
1159
+ case 'n': columnHeaders[C] = val.v; break;
1160
+ }
1161
+ }
1162
+ }
1163
+
1164
+ for (var R = range.s.r + 1; R <= range.e.r; ++R) {
1165
+ emptyRow = true;
1166
+ //Row number is recorded in the prototype
1167
+ //so that it doesn't appear when stringified.
1168
+ rowObject = Object.create({ __rowNum__ : R });
1169
+ for (C = range.s.c; C <= range.e.c; ++C) {
1170
+ val = sheet[encode_cell({
1171
+ c: C,
1172
+ r: R
1173
+ })];
1174
+ if(val !== undefined) switch(val.t){
1175
+ case 's': case 'str': case 'b': case 'n':
1176
+ if(val.v !== undefined) {
1177
+ rowObject[columnHeaders[C]] = val.v;
1178
+ emptyRow = false;
1179
+ }
1180
+ break;
1181
+ case 'e': break; /* throw */
1182
+ default: throw 'unrecognized type ' + val.t;
1183
+ }
1184
+ }
1185
+ if(!emptyRow) {
1186
+ outSheet.push(rowObject);
1187
+ }
1188
+ }
1189
+ }
1190
+ return outSheet;
1191
+ }
1192
+
1193
+ function sheet_to_csv(sheet) {
1194
+ var stringify = function stringify(val) {
1195
+ switch(val.t){
1196
+ case 'n': return String(val.v);
1197
+ case 's': case 'str':
1198
+ if(typeof val.v === 'undefined') return "";
1199
+ return JSON.stringify(val.v);
1200
+ case 'b': return val.v ? "TRUE" : "FALSE";
1201
+ case 'e': return ""; /* throw out value in case of error */
1202
+ default: throw 'unrecognized type ' + val.t;
1203
+ }
1204
+ };
1205
+ var out = "";
1206
+ if(sheet["!ref"]) {
1207
+ var r = XLSX.utils.decode_range(sheet["!ref"]);
1208
+ for(var R = r.s.r; R <= r.e.r; ++R) {
1209
+ var row = [];
1210
+ for(var C = r.s.c; C <= r.e.c; ++C) {
1211
+ var val = sheet[XLSX.utils.encode_cell({c:C,r:R})];
1212
+ row.push(val ? stringify(val).replace(/\\r\\n/g,"\n").replace(/\\t/g,"\t").replace(/\\\\/g,"\\").replace("\\\"","\"\"") : "");
1213
+ }
1214
+ out += row.join(",") + "\n";
1215
+ }
1216
+ }
1217
+ return out;
1218
+ }
1219
+ var make_csv = sheet_to_csv;
1220
+
1221
+ function get_formulae(ws) {
1222
+ var cmds = [];
1223
+ for(var y in ws) if(y[0] !=='!' && ws.hasOwnProperty(y)) {
1224
+ var x = ws[y];
1225
+ var val = "";
1226
+ if(x.f) val = x.f;
1227
+ else if(typeof x.v === 'number') val = x.v;
1228
+ else val = x.v;
1229
+ cmds.push(y + "=" + val);
1230
+ }
1231
+ return cmds;
1232
+ }
1233
+
1234
+ XLSX.utils = {
1235
+ encode_col: encode_col,
1236
+ encode_row: encode_row,
1237
+ encode_cell: encode_cell,
1238
+ encode_range: encode_range,
1239
+ decode_col: decode_col,
1240
+ decode_row: decode_row,
1241
+ split_cell: split_cell,
1242
+ decode_cell: decode_cell,
1243
+ decode_range: decode_range,
1244
+ sheet_to_csv: sheet_to_csv,
1245
+ make_csv: sheet_to_csv,
1246
+ get_formulae: get_formulae,
1247
+ sheet_to_row_object_array: sheet_to_row_object_array
1248
+ };
1249
+
1250
+ if(typeof require !== 'undefined' && typeof exports !== 'undefined') {
1251
+ exports.read = XLSX.read;
1252
+ exports.readFile = XLSX.readFile;
1253
+ exports.utils = XLSX.utils;
1254
+ exports.main = function(args) {
1255
+ var zip = XLSX.read(args[0], {type:'file'});
1256
+ console.log(zip.Sheets);
1257
+ };
1258
+ if(typeof module !== 'undefined' && require.main === module)
1259
+ exports.main(process.argv.slice(2));
1260
+ }
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: js-xlsx-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.6
5
+ platform: ruby
6
+ authors:
7
+ - Adrien Montfort
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-01-08 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: A gem that makes SheetJS/xslx available to the Rails asset pipeline.
14
+ email:
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - lib/js-xlsx-rails.rb
20
+ - lib/js-xlsx-rails/version.rb
21
+ - vendor/assets/javascripts/xlsx.js
22
+ homepage: https://github.com/idolweb/js-xlsx-rails
23
+ licenses:
24
+ - MIT
25
+ metadata: {}
26
+ post_install_message:
27
+ rdoc_options: []
28
+ require_paths:
29
+ - lib
30
+ required_ruby_version: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - '>='
33
+ - !ruby/object:Gem::Version
34
+ version: '0'
35
+ required_rubygems_version: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - '>='
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ requirements: []
41
+ rubyforge_project:
42
+ rubygems_version: 2.2.1
43
+ signing_key:
44
+ specification_version: 4
45
+ summary: Integrates JS-XLSX with Rails's asset pipeline
46
+ test_files: []
47
+ has_rdoc: