You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10809 lines
379 KiB

6 months ago
  1. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  2. /* vim: set ts=2: */
  3. /*exported XLSX */
  4. /*global global, exports, module, require:false, process:false, Buffer:false, ArrayBuffer:false */
  5. var XLSX = {};
  6. var make_xlsx_lib= function (XLSX){
  7. XLSX.version = '0.17.5';
  8. var current_codepage = 1200, current_ansi = 1252;
  9. var VALID_ANSI = [ 874, 932, 936, 949, 950 ];
  10. for(var i = 0; i <= 8; ++i) VALID_ANSI.push(1250 + i);
  11. /* ECMA-376 Part I 18.4.1 charset to codepage mapping */
  12. var CS2CP = ({
  13. 0: 1252, /* ANSI */
  14. 1: 65001, /* DEFAULT */
  15. 2: 65001, /* SYMBOL */
  16. 77: 10000, /* MAC */
  17. 128: 932, /* SHIFTJIS */
  18. 129: 949, /* HANGUL */
  19. 130: 1361, /* JOHAB */
  20. 134: 936, /* GB2312 */
  21. 136: 950, /* CHINESEBIG5 */
  22. 161: 1253, /* GREEK */
  23. 162: 1254, /* TURKISH */
  24. 163: 1258, /* VIETNAMESE */
  25. 177: 1255, /* HEBREW */
  26. 178: 1256, /* ARABIC */
  27. 186: 1257, /* BALTIC */
  28. 204: 1251, /* RUSSIAN */
  29. 222: 874, /* THAI */
  30. 238: 1250, /* EASTEUROPE */
  31. 255: 1252, /* OEM */
  32. 69: 6969 /* MISC */
  33. });
  34. var set_ansi = function(cp) { if(VALID_ANSI.indexOf(cp) == -1) return; current_ansi = CS2CP[0] = cp; };
  35. function reset_ansi() { set_ansi(1252); }
  36. var set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  37. function reset_cp() { set_cp(1200); reset_ansi(); }
  38. function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
  39. function utf16leread(data) {
  40. var o = [];
  41. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
  42. return o.join("");
  43. }
  44. function utf16beread(data) {
  45. var o = [];
  46. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
  47. return o.join("");
  48. }
  49. var debom = function(data) {
  50. var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
  51. if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.slice(2));
  52. if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.slice(2));
  53. if(c1 == 0xFEFF) return data.slice(1);
  54. return data;
  55. };
  56. var _getchar = function _gc1(x) { return String.fromCharCode(x); };
  57. var _getansi = function _ga1(x) { return String.fromCharCode(x); };
  58. var DENSE = null;
  59. var DIF_XL = true;
  60. var Base64 = (function make_b64(){
  61. var map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  62. return {
  63. encode: function(input) {
  64. var o = "";
  65. var c1=0, c2=0, c3=0, e1=0, e2=0, e3=0, e4=0;
  66. for(var i = 0; i < input.length; ) {
  67. c1 = input.charCodeAt(i++);
  68. e1 = (c1 >> 2);
  69. c2 = input.charCodeAt(i++);
  70. e2 = ((c1 & 3) << 4) | (c2 >> 4);
  71. c3 = input.charCodeAt(i++);
  72. e3 = ((c2 & 15) << 2) | (c3 >> 6);
  73. e4 = (c3 & 63);
  74. if (isNaN(c2)) { e3 = e4 = 64; }
  75. else if (isNaN(c3)) { e4 = 64; }
  76. o += map.charAt(e1) + map.charAt(e2) + map.charAt(e3) + map.charAt(e4);
  77. }
  78. return o;
  79. },
  80. decode: function b64_decode(input) {
  81. var o = "";
  82. var c1=0, c2=0, c3=0, e1=0, e2=0, e3=0, e4=0;
  83. input = input.replace(/[^\w\+\/\=]/g, "");
  84. for(var i = 0; i < input.length;) {
  85. e1 = map.indexOf(input.charAt(i++));
  86. e2 = map.indexOf(input.charAt(i++));
  87. c1 = (e1 << 2) | (e2 >> 4);
  88. o += String.fromCharCode(c1);
  89. e3 = map.indexOf(input.charAt(i++));
  90. c2 = ((e2 & 15) << 4) | (e3 >> 2);
  91. if (e3 !== 64) { o += String.fromCharCode(c2); }
  92. e4 = map.indexOf(input.charAt(i++));
  93. c3 = ((e3 & 3) << 6) | e4;
  94. if (e4 !== 64) { o += String.fromCharCode(c3); }
  95. }
  96. return o;
  97. }
  98. };
  99. })();
  100. var has_buf = (typeof Buffer !== 'undefined' && typeof process !== 'undefined' && typeof process.versions !== 'undefined' && !!process.versions.node);
  101. var Buffer_from = function(){};
  102. if(typeof Buffer !== 'undefined') {
  103. var nbfs = !Buffer.from;
  104. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  105. Buffer_from = nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  106. // $FlowIgnore
  107. if(!Buffer.alloc) Buffer.alloc = function(n) { return new Buffer(n); };
  108. // $FlowIgnore
  109. if(!Buffer.allocUnsafe) Buffer.allocUnsafe = function(n) { return new Buffer(n); };
  110. }
  111. function new_raw_buf(len) {
  112. /* jshint -W056 */
  113. return has_buf ? Buffer.alloc(len) : new Array(len);
  114. /* jshint +W056 */
  115. }
  116. function new_unsafe_buf(len) {
  117. /* jshint -W056 */
  118. return has_buf ? Buffer.allocUnsafe(len) : new Array(len);
  119. /* jshint +W056 */
  120. }
  121. var s2a = function s2a(s) {
  122. if(has_buf) return Buffer_from(s, "binary");
  123. return s.split("").map(function(x){ return x.charCodeAt(0) & 0xff; });
  124. };
  125. function s2ab(s) {
  126. if(typeof ArrayBuffer === 'undefined') return s2a(s);
  127. var buf = new ArrayBuffer(s.length), view = new Uint8Array(buf);
  128. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  129. return buf;
  130. }
  131. function a2s(data) {
  132. if(Array.isArray(data)) return data.map(function(c) { return String.fromCharCode(c); }).join("");
  133. var o = []; for(var i = 0; i < data.length; ++i) o[i] = String.fromCharCode(data[i]); return o.join("");
  134. }
  135. function a2u(data) {
  136. if(typeof Uint8Array === 'undefined') throw new Error("Unsupported");
  137. return new Uint8Array(data);
  138. }
  139. function ab2a(data) {
  140. if(typeof ArrayBuffer == 'undefined') throw new Error("Unsupported");
  141. if(data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
  142. var o = new Array(data.length);
  143. for(var i = 0; i < data.length; ++i) o[i] = data[i];
  144. return o;
  145. }
  146. var bconcat = function(bufs) { return [].concat.apply([], bufs); };
  147. var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/g;
  148. /* ssf.js (C) 2013-present SheetJS -- http://sheetjs.com */
  149. /*jshint -W041 */
  150. var SSF = ({});
  151. var make_ssf = function make_ssf(SSF){
  152. SSF.version = '0.11.2';
  153. function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
  154. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  155. function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  156. function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;}
  157. function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);}
  158. function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;}
  159. function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  160. var p2_32 = Math.pow(2,32);
  161. function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
  162. function isgeneral(s, i) { i = i || 0; return s.length >= 7 + i && (s.charCodeAt(i)|32) === 103 && (s.charCodeAt(i+1)|32) === 101 && (s.charCodeAt(i+2)|32) === 110 && (s.charCodeAt(i+3)|32) === 101 && (s.charCodeAt(i+4)|32) === 114 && (s.charCodeAt(i+5)|32) === 97 && (s.charCodeAt(i+6)|32) === 108; }
  163. var days = [
  164. ['Sun', 'Sunday'],
  165. ['Mon', 'Monday'],
  166. ['Tue', 'Tuesday'],
  167. ['Wed', 'Wednesday'],
  168. ['Thu', 'Thursday'],
  169. ['Fri', 'Friday'],
  170. ['Sat', 'Saturday']
  171. ];
  172. var months = [
  173. ['J', 'Jan', 'January'],
  174. ['F', 'Feb', 'February'],
  175. ['M', 'Mar', 'March'],
  176. ['A', 'Apr', 'April'],
  177. ['M', 'May', 'May'],
  178. ['J', 'Jun', 'June'],
  179. ['J', 'Jul', 'July'],
  180. ['A', 'Aug', 'August'],
  181. ['S', 'Sep', 'September'],
  182. ['O', 'Oct', 'October'],
  183. ['N', 'Nov', 'November'],
  184. ['D', 'Dec', 'December']
  185. ];
  186. function init_table(t) {
  187. t[0]= 'General';
  188. t[1]= '0';
  189. t[2]= '0.00';
  190. t[3]= '#,##0';
  191. t[4]= '#,##0.00';
  192. t[9]= '0%';
  193. t[10]= '0.00%';
  194. t[11]= '0.00E+00';
  195. t[12]= '# ?/?';
  196. t[13]= '# ??/??';
  197. t[14]= 'm/d/yy';
  198. t[15]= 'd-mmm-yy';
  199. t[16]= 'd-mmm';
  200. t[17]= 'mmm-yy';
  201. t[18]= 'h:mm AM/PM';
  202. t[19]= 'h:mm:ss AM/PM';
  203. t[20]= 'h:mm';
  204. t[21]= 'h:mm:ss';
  205. t[22]= 'm/d/yy h:mm';
  206. t[37]= '#,##0 ;(#,##0)';
  207. t[38]= '#,##0 ;[Red](#,##0)';
  208. t[39]= '#,##0.00;(#,##0.00)';
  209. t[40]= '#,##0.00;[Red](#,##0.00)';
  210. t[45]= 'mm:ss';
  211. t[46]= '[h]:mm:ss';
  212. t[47]= 'mmss.0';
  213. t[48]= '##0.0E+0';
  214. t[49]= '@';
  215. t[56]= '"上午/下午 "hh"時"mm"分"ss"秒 "';
  216. }
  217. var table_fmt = {};
  218. init_table(table_fmt);
  219. /* Defaults determined by systematically testing in Excel 2019 */
  220. /* These formats appear to default to other formats in the table */
  221. var default_map = [];
  222. var defi = 0;
  223. // 5 -> 37 ... 8 -> 40
  224. for(defi = 5; defi <= 8; ++defi) default_map[defi] = 32 + defi;
  225. // 23 -> 0 ... 26 -> 0
  226. for(defi = 23; defi <= 26; ++defi) default_map[defi] = 0;
  227. // 27 -> 14 ... 31 -> 14
  228. for(defi = 27; defi <= 31; ++defi) default_map[defi] = 14;
  229. // 50 -> 14 ... 58 -> 14
  230. for(defi = 50; defi <= 58; ++defi) default_map[defi] = 14;
  231. // 59 -> 1 ... 62 -> 4
  232. for(defi = 59; defi <= 62; ++defi) default_map[defi] = defi - 58;
  233. // 67 -> 9 ... 68 -> 10
  234. for(defi = 67; defi <= 68; ++defi) default_map[defi] = defi - 58;
  235. // 72 -> 14 ... 75 -> 17
  236. for(defi = 72; defi <= 75; ++defi) default_map[defi] = defi - 58;
  237. // 69 -> 12 ... 71 -> 14
  238. for(defi = 67; defi <= 68; ++defi) default_map[defi] = defi - 57;
  239. // 76 -> 20 ... 78 -> 22
  240. for(defi = 76; defi <= 78; ++defi) default_map[defi] = defi - 56;
  241. // 79 -> 45 ... 81 -> 47
  242. for(defi = 79; defi <= 81; ++defi) default_map[defi] = defi - 34;
  243. // 82 -> 0 ... 65536 -> 0 (omitted)
  244. /* These formats technically refer to Accounting formats with no equivalent */
  245. var default_str = [];
  246. // 5 -- Currency, 0 decimal, black negative
  247. default_str[5] = default_str[63] = '"$"#,##0_);\\("$"#,##0\\)';
  248. // 6 -- Currency, 0 decimal, red negative
  249. default_str[6] = default_str[64] = '"$"#,##0_);[Red]\\("$"#,##0\\)';
  250. // 7 -- Currency, 2 decimal, black negative
  251. default_str[7] = default_str[65] = '"$"#,##0.00_);\\("$"#,##0.00\\)';
  252. // 8 -- Currency, 2 decimal, red negative
  253. default_str[8] = default_str[66] = '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)';
  254. // 41 -- Accounting, 0 decimal, No Symbol
  255. default_str[41] = '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)';
  256. // 42 -- Accounting, 0 decimal, $ Symbol
  257. default_str[42] = '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)';
  258. // 43 -- Accounting, 2 decimal, No Symbol
  259. default_str[43] = '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)';
  260. // 44 -- Accounting, 2 decimal, $ Symbol
  261. default_str[44] = '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)';
  262. function frac(x, D, mixed) {
  263. var sgn = x < 0 ? -1 : 1;
  264. var B = x * sgn;
  265. var P_2 = 0, P_1 = 1, P = 0;
  266. var Q_2 = 1, Q_1 = 0, Q = 0;
  267. var A = Math.floor(B);
  268. while(Q_1 < D) {
  269. A = Math.floor(B);
  270. P = A * P_1 + P_2;
  271. Q = A * Q_1 + Q_2;
  272. if((B - A) < 0.00000005) break;
  273. B = 1 / (B - A);
  274. P_2 = P_1; P_1 = P;
  275. Q_2 = Q_1; Q_1 = Q;
  276. }
  277. if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
  278. if(!mixed) return [0, sgn * P, Q];
  279. var q = Math.floor(sgn * P/Q);
  280. return [q, sgn*P - q*Q, Q];
  281. }
  282. function parse_date_code(v,opts,b2) {
  283. if(v > 2958465 || v < 0) return null;
  284. var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
  285. var dout=[];
  286. var out={D:date, T:time, u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0};
  287. if(Math.abs(out.u) < 1e-6) out.u = 0;
  288. if(opts && opts.date1904) date += 1462;
  289. if(out.u > 0.9999) {
  290. out.u = 0;
  291. if(++time == 86400) { out.T = time = 0; ++date; ++out.D; }
  292. }
  293. if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
  294. else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
  295. else {
  296. if(date > 60) --date;
  297. /* 1 = Jan 1 1900 in Gregorian */
  298. var d = new Date(1900, 0, 1);
  299. d.setDate(d.getDate() + date - 1);
  300. dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
  301. dow = d.getDay();
  302. if(date < 60) dow = (dow + 6) % 7;
  303. if(b2) dow = fix_hijri(d, dout);
  304. }
  305. out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
  306. out.S = time % 60; time = Math.floor(time / 60);
  307. out.M = time % 60; time = Math.floor(time / 60);
  308. out.H = time;
  309. out.q = dow;
  310. return out;
  311. }
  312. SSF.parse_date_code = parse_date_code;
  313. var basedate = new Date(1899, 11, 31, 0, 0, 0);
  314. var dnthresh = basedate.getTime();
  315. var base1904 = new Date(1900, 2, 1, 0, 0, 0);
  316. function datenum_local(v, date1904) {
  317. var epoch = v.getTime();
  318. if(date1904) epoch -= 1461*24*60*60*1000;
  319. else if(v >= base1904) epoch += 24*60*60*1000;
  320. return (epoch - (dnthresh + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
  321. }
  322. /* The longest 32-bit integer text is "-4294967296", exactly 11 chars */
  323. function general_fmt_int(v) { return v.toString(10); }
  324. SSF._general_int = general_fmt_int;
  325. /* ECMA-376 18.8.30 numFmt*/
  326. /* Note: `toPrecision` uses standard form when prec > E and E >= -6 */
  327. var general_fmt_num = (function make_general_fmt_num() {
  328. var trailing_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)$/;
  329. function strip_decimal(o) {
  330. return (o.indexOf(".") == -1) ? o : o.replace(trailing_zeroes_and_decimal, "$1");
  331. }
  332. /* General Exponential always shows 2 digits exp and trims the mantissa */
  333. var mantissa_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)[Ee]/;
  334. var exp_with_single_digit = /(E[+-])(\d)$/;
  335. function normalize_exp(o) {
  336. if(o.indexOf("E") == -1) return o;
  337. return o.replace(mantissa_zeroes_and_decimal,"$1E").replace(exp_with_single_digit,"$10$2");
  338. }
  339. /* exponent >= -9 and <= 9 */
  340. function small_exp(v) {
  341. var w = (v<0?12:11);
  342. var o = strip_decimal(v.toFixed(12)); if(o.length <= w) return o;
  343. o = v.toPrecision(10); if(o.length <= w) return o;
  344. return v.toExponential(5);
  345. }
  346. /* exponent >= 11 or <= -10 likely exponential */
  347. function large_exp(v) {
  348. var o = strip_decimal(v.toFixed(11));
  349. return (o.length > (v<0?12:11) || o === "0" || o === "-0") ? v.toPrecision(6) : o;
  350. }
  351. function general_fmt_num_base(v) {
  352. var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;
  353. if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
  354. else if(Math.abs(V) <= 9) o = small_exp(v);
  355. else if(V === 10) o = v.toFixed(10).substr(0,12);
  356. else o = large_exp(v);
  357. return strip_decimal(normalize_exp(o.toUpperCase()));
  358. }
  359. return general_fmt_num_base;
  360. })();
  361. SSF._general_num = general_fmt_num;
  362. /*
  363. "General" rules:
  364. - text is passed through ("@")
  365. - booleans are rendered as TRUE/FALSE
  366. - "up to 11 characters" displayed for numbers
  367. - Default date format (code 14) used for Dates
  368. TODO: technically the display depends on the width of the cell
  369. */
  370. function general_fmt(v, opts) {
  371. switch(typeof v) {
  372. case 'string': return v;
  373. case 'boolean': return v ? "TRUE" : "FALSE";
  374. case 'number': return (v|0) === v ? v.toString(10) : general_fmt_num(v);
  375. case 'undefined': return "";
  376. case 'object':
  377. if(v == null) return "";
  378. if(v instanceof Date) return format(14, datenum_local(v, opts && opts.date1904), opts);
  379. }
  380. throw new Error("unsupported value in General format: " + v);
  381. }
  382. SSF._general = general_fmt;
  383. function fix_hijri(date, o) {
  384. /* TODO: properly adjust y/m/d and */
  385. o[0] -= 581;
  386. var dow = date.getDay();
  387. if(date < 60) dow = (dow + 6) % 7;
  388. return dow;
  389. }
  390. //var THAI_DIGITS = "\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59".split("");
  391. /*jshint -W086 */
  392. function write_date(type, fmt, val, ss0) {
  393. var o="", ss=0, tt=0, y = val.y, out, outl = 0;
  394. switch(type) {
  395. case 98: /* 'b' buddhist year */
  396. y = val.y + 543;
  397. /* falls through */
  398. case 121: /* 'y' year */
  399. switch(fmt.length) {
  400. case 1: case 2: out = y % 100; outl = 2; break;
  401. default: out = y % 10000; outl = 4; break;
  402. } break;
  403. case 109: /* 'm' month */
  404. switch(fmt.length) {
  405. case 1: case 2: out = val.m; outl = fmt.length; break;
  406. case 3: return months[val.m-1][1];
  407. case 5: return months[val.m-1][0];
  408. default: return months[val.m-1][2];
  409. } break;
  410. case 100: /* 'd' day */
  411. switch(fmt.length) {
  412. case 1: case 2: out = val.d; outl = fmt.length; break;
  413. case 3: return days[val.q][0];
  414. default: return days[val.q][1];
  415. } break;
  416. case 104: /* 'h' 12-hour */
  417. switch(fmt.length) {
  418. case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
  419. default: throw 'bad hour format: ' + fmt;
  420. } break;
  421. case 72: /* 'H' 24-hour */
  422. switch(fmt.length) {
  423. case 1: case 2: out = val.H; outl = fmt.length; break;
  424. default: throw 'bad hour format: ' + fmt;
  425. } break;
  426. case 77: /* 'M' minutes */
  427. switch(fmt.length) {
  428. case 1: case 2: out = val.M; outl = fmt.length; break;
  429. default: throw 'bad minute format: ' + fmt;
  430. } break;
  431. case 115: /* 's' seconds */
  432. if(fmt != 's' && fmt != 'ss' && fmt != '.0' && fmt != '.00' && fmt != '.000') throw 'bad second format: ' + fmt;
  433. if(val.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val.S, fmt.length);
  434. if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
  435. else tt = ss0 === 1 ? 10 : 1;
  436. ss = Math.round((tt)*(val.S + val.u));
  437. if(ss >= 60*tt) ss = 0;
  438. if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
  439. o = pad0(ss,2 + ss0);
  440. if(fmt === 'ss') return o.substr(0,2);
  441. return "." + o.substr(2,fmt.length-1);
  442. case 90: /* 'Z' absolute time */
  443. switch(fmt) {
  444. case '[h]': case '[hh]': out = val.D*24+val.H; break;
  445. case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
  446. case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
  447. default: throw 'bad abstime format: ' + fmt;
  448. } outl = fmt.length === 3 ? 1 : 2; break;
  449. case 101: /* 'e' era */
  450. out = y; outl = 1; break;
  451. }
  452. var outstr = outl > 0 ? pad0(out, outl) : "";
  453. return outstr;
  454. }
  455. /*jshint +W086 */
  456. function commaify(s) {
  457. var w = 3;
  458. if(s.length <= w) return s;
  459. var j = (s.length % w), o = s.substr(0,j);
  460. for(; j!=s.length; j+=w) o+=(o.length > 0 ? "," : "") + s.substr(j,w);
  461. return o;
  462. }
  463. var write_num = (function make_write_num(){
  464. var pct1 = /%/g;
  465. function write_num_pct(type, fmt, val){
  466. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  467. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  468. }
  469. function write_num_cm(type, fmt, val){
  470. var idx = fmt.length - 1;
  471. while(fmt.charCodeAt(idx-1) === 44) --idx;
  472. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  473. }
  474. function write_num_exp(fmt, val){
  475. var o;
  476. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  477. if(fmt.match(/^#+0.0E\+0$/)) {
  478. if(val == 0) return "0.0E+0";
  479. else if(val < 0) return "-" + write_num_exp(fmt, -val);
  480. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  481. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  482. if(ee < 0) ee += period;
  483. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  484. if(o.indexOf("e") === -1) {
  485. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  486. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  487. else o += "E+" + (fakee - ee);
  488. while(o.substr(0,2) === "0.") {
  489. o = o.charAt(0) + o.substr(2,period) + "." + o.substr(2+period);
  490. o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
  491. }
  492. o = o.replace(/\+-/,"-");
  493. }
  494. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  495. } else o = val.toExponential(idx);
  496. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  497. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  498. return o.replace("e","E");
  499. }
  500. var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
  501. function write_num_f1(r, aval, sign) {
  502. var den = parseInt(r[4],10), rr = Math.round(aval * den), base = Math.floor(rr/den);
  503. var myn = (rr - base*den), myd = den;
  504. return sign + (base === 0 ? "" : ""+base) + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[4].length) : pad_(myn,r[1].length) + r[2] + "/" + r[3] + pad0(myd,r[4].length));
  505. }
  506. function write_num_f2(r, aval, sign) {
  507. return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length);
  508. }
  509. var dec1 = /^#*0*\.([0#]+)/;
  510. var closeparen = /\).*[0#]/;
  511. var phone = /\(###\) ###\\?-####/;
  512. function hashq(str) {
  513. var o = "", cc;
  514. for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
  515. case 35: break;
  516. case 63: o+= " "; break;
  517. case 48: o+= "0"; break;
  518. default: o+= String.fromCharCode(cc);
  519. }
  520. return o;
  521. }
  522. function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
  523. function dec(val, d) {
  524. var _frac = val - Math.floor(val), dd = Math.pow(10,d);
  525. if (d < ('' + Math.round(_frac * dd)).length) return 0;
  526. return Math.round(_frac * dd);
  527. }
  528. function carry(val, d) {
  529. if (d < ('' + Math.round((val-Math.floor(val))*Math.pow(10,d))).length) {
  530. return 1;
  531. }
  532. return 0;
  533. }
  534. function flr(val) {
  535. if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0));
  536. return ""+Math.floor(val);
  537. }
  538. function write_num_flt(type, fmt, val) {
  539. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  540. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  541. if(val >= 0) return write_num_flt('n', ffmt, val);
  542. return '(' + write_num_flt('n', ffmt, -val) + ')';
  543. }
  544. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
  545. if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
  546. if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
  547. if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  548. var o;
  549. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  550. if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
  551. if(fmt.match(/^[#?]+$/)) {
  552. o = pad0r(val,0); if(o === "0") o = "";
  553. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  554. }
  555. if((r = fmt.match(frac1))) return write_num_f1(r, aval, sign);
  556. if(fmt.match(/^#+0+$/)) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
  557. if((r = fmt.match(dec1))) {
  558. o = rnd(val, r[1].length).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1])).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  559. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  560. }
  561. fmt = fmt.replace(/^#+([0.])/, "$1");
  562. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  563. return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  564. }
  565. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify(pad0r(aval,0));
  566. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  567. return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(""+(Math.floor(val) + carry(val, r[1].length))) + "." + pad0(dec(val, r[1].length),r[1].length);
  568. }
  569. if((r = fmt.match(/^#,#*,#0/))) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
  570. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  571. o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
  572. ri = 0;
  573. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  574. }
  575. if(fmt.match(phone)) {
  576. o = write_num_flt(type, "##########", val);
  577. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  578. }
  579. var oa = "";
  580. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  581. ri = Math.min(r[4].length,7);
  582. ff = frac(aval, Math.pow(10,ri)-1, false);
  583. o = "" + sign;
  584. oa = write_num("n", r[1], ff[1]);
  585. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  586. o += oa + r[2] + "/" + r[3];
  587. oa = rpad_(ff[2],ri);
  588. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  589. o += oa;
  590. return o;
  591. }
  592. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  593. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  594. ff = frac(aval, Math.pow(10,ri)-1, true);
  595. return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
  596. }
  597. if((r = fmt.match(/^[#0?]+$/))) {
  598. o = pad0r(val, 0);
  599. if(fmt.length <= o.length) return o;
  600. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  601. }
  602. if((r = fmt.match(/^([#0?]+)\.([#0]+)$/))) {
  603. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  604. ri = o.indexOf(".");
  605. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  606. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  607. }
  608. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  609. ri = dec(val, r[1].length);
  610. return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(ri,r[1].length);
  611. }
  612. switch(fmt) {
  613. case "###,##0.00": return write_num_flt(type, "#,##0.00", val);
  614. case "###,###":
  615. case "##,###":
  616. case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
  617. case "###,###.00": return write_num_flt(type, "###,##0.00",val).replace(/^0\./,".");
  618. case "#,###.00": return write_num_flt(type, "#,##0.00",val).replace(/^0\./,".");
  619. default:
  620. }
  621. throw new Error("unsupported format |" + fmt + "|");
  622. }
  623. function write_num_cm2(type, fmt, val){
  624. var idx = fmt.length - 1;
  625. while(fmt.charCodeAt(idx-1) === 44) --idx;
  626. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  627. }
  628. function write_num_pct2(type, fmt, val){
  629. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  630. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  631. }
  632. function write_num_exp2(fmt, val){
  633. var o;
  634. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  635. if(fmt.match(/^#+0.0E\+0$/)) {
  636. if(val == 0) return "0.0E+0";
  637. else if(val < 0) return "-" + write_num_exp2(fmt, -val);
  638. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  639. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  640. if(ee < 0) ee += period;
  641. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  642. if(!o.match(/[Ee]/)) {
  643. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  644. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  645. else o += "E+" + (fakee - ee);
  646. o = o.replace(/\+-/,"-");
  647. }
  648. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  649. } else o = val.toExponential(idx);
  650. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  651. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  652. return o.replace("e","E");
  653. }
  654. function write_num_int(type, fmt, val) {
  655. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  656. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  657. if(val >= 0) return write_num_int('n', ffmt, val);
  658. return '(' + write_num_int('n', ffmt, -val) + ')';
  659. }
  660. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
  661. if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
  662. if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
  663. if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  664. var o;
  665. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  666. if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
  667. if(fmt.match(/^[#?]+$/)) {
  668. o = (""+val); if(val === 0) o = "";
  669. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  670. }
  671. if((r = fmt.match(frac1))) return write_num_f2(r, aval, sign);
  672. if(fmt.match(/^#+0+$/)) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
  673. if((r = fmt.match(dec1))) {
  674. o = (""+val).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1]));
  675. o = o.replace(/\.(\d*)$/,function($$, $1) {
  676. return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  677. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  678. }
  679. fmt = fmt.replace(/^#+([0.])/, "$1");
  680. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  681. return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  682. }
  683. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify((""+aval));
  684. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  685. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length);
  686. }
  687. if((r = fmt.match(/^#,#*,#0/))) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
  688. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  689. o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
  690. ri = 0;
  691. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  692. }
  693. if(fmt.match(phone)) {
  694. o = write_num_int(type, "##########", val);
  695. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  696. }
  697. var oa = "";
  698. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  699. ri = Math.min(r[4].length,7);
  700. ff = frac(aval, Math.pow(10,ri)-1, false);
  701. o = "" + sign;
  702. oa = write_num("n", r[1], ff[1]);
  703. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  704. o += oa + r[2] + "/" + r[3];
  705. oa = rpad_(ff[2],ri);
  706. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  707. o += oa;
  708. return o;
  709. }
  710. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  711. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  712. ff = frac(aval, Math.pow(10,ri)-1, true);
  713. return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
  714. }
  715. if((r = fmt.match(/^[#0?]+$/))) {
  716. o = "" + val;
  717. if(fmt.length <= o.length) return o;
  718. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  719. }
  720. if((r = fmt.match(/^([#0]+)\.([#0]+)$/))) {
  721. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  722. ri = o.indexOf(".");
  723. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  724. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  725. }
  726. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  727. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(0,r[1].length);
  728. }
  729. switch(fmt) {
  730. case "###,###":
  731. case "##,###":
  732. case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
  733. default:
  734. if(fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0,fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
  735. }
  736. throw new Error("unsupported format |" + fmt + "|");
  737. }
  738. return function write_num(type, fmt, val) {
  739. return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
  740. };})();
  741. function split_fmt(fmt) {
  742. var out = [];
  743. var in_str = false/*, cc*/;
  744. for(var i = 0, j = 0; i < fmt.length; ++i) switch((/*cc=*/fmt.charCodeAt(i))) {
  745. case 34: /* '"' */
  746. in_str = !in_str; break;
  747. case 95: case 42: case 92: /* '_' '*' '\\' */
  748. ++i; break;
  749. case 59: /* ';' */
  750. out[out.length] = fmt.substr(j,i-j);
  751. j = i+1;
  752. }
  753. out[out.length] = fmt.substr(j);
  754. if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
  755. return out;
  756. }
  757. SSF._split = split_fmt;
  758. var abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
  759. function fmt_is_date(fmt) {
  760. var i = 0, /*cc = 0,*/ c = "", o = "";
  761. while(i < fmt.length) {
  762. switch((c = fmt.charAt(i))) {
  763. case 'G': if(isgeneral(fmt, i)) i+= 6; i++; break;
  764. case '"': for(;(/*cc=*/fmt.charCodeAt(++i)) !== 34 && i < fmt.length;){/*empty*/} ++i; break;
  765. case '\\': i+=2; break;
  766. case '_': i+=2; break;
  767. case '@': ++i; break;
  768. case 'B': case 'b':
  769. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") return true;
  770. /* falls through */
  771. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  772. /* falls through */
  773. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': return true;
  774. case 'A': case 'a': case '上':
  775. if(fmt.substr(i, 3).toUpperCase() === "A/P") return true;
  776. if(fmt.substr(i, 5).toUpperCase() === "AM/PM") return true;
  777. if(fmt.substr(i, 5).toUpperCase() === "上午/下午") return true;
  778. ++i; break;
  779. case '[':
  780. o = c;
  781. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  782. if(o.match(abstime)) return true;
  783. break;
  784. case '.':
  785. /* falls through */
  786. case '0': case '#':
  787. while(i < fmt.length && ("0#?.,E+-%".indexOf(c=fmt.charAt(++i)) > -1 || (c=='\\' && fmt.charAt(i+1) == "-" && "0#".indexOf(fmt.charAt(i+2))>-1))){/* empty */}
  788. break;
  789. case '?': while(fmt.charAt(++i) === c){/* empty */} break;
  790. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break;
  791. case '(': case ')': ++i; break;
  792. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  793. while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1){/* empty */} break;
  794. case ' ': ++i; break;
  795. default: ++i; break;
  796. }
  797. }
  798. return false;
  799. }
  800. SSF.is_date = fmt_is_date;
  801. function eval_fmt(fmt, v, opts, flen) {
  802. var out = [], o = "", i = 0, c = "", lst='t', dt, j, cc;
  803. var hr='H';
  804. /* Tokenize */
  805. while(i < fmt.length) {
  806. switch((c = fmt.charAt(i))) {
  807. case 'G': /* General */
  808. if(!isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
  809. out[out.length] = {t:'G', v:'General'}; i+=7; break;
  810. case '"': /* Literal text */
  811. for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
  812. out[out.length] = {t:'t', v:o}; ++i; break;
  813. case '\\': var w = fmt.charAt(++i), t = (w === "(" || w === ")") ? w : 't';
  814. out[out.length] = {t:t, v:w}; ++i; break;
  815. case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
  816. case '@': /* Text Placeholder */
  817. out[out.length] = {t:'T', v:v}; ++i; break;
  818. case 'B': case 'b':
  819. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") {
  820. if(dt==null) { dt=parse_date_code(v, opts, fmt.charAt(i+1) === "2"); if(dt==null) return ""; }
  821. out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
  822. }
  823. /* falls through */
  824. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  825. c = c.toLowerCase();
  826. /* falls through */
  827. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
  828. if(v < 0) return "";
  829. if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
  830. o = c; while(++i < fmt.length && fmt.charAt(i).toLowerCase() === c) o+=c;
  831. if(c === 'm' && lst.toLowerCase() === 'h') c = 'M';
  832. if(c === 'h') c = hr;
  833. out[out.length] = {t:c, v:o}; lst = c; break;
  834. case 'A': case 'a': case '上':
  835. var q={t:c, v:c};
  836. if(dt==null) dt=parse_date_code(v, opts);
  837. if(fmt.substr(i, 3).toUpperCase() === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
  838. else if(fmt.substr(i,5).toUpperCase() === "AM/PM") { if(dt!=null) q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; }
  839. else if(fmt.substr(i,5).toUpperCase() === "上午/下午") { if(dt!=null) q.v = dt.H >= 12 ? "下午" : "上午"; q.t = 'T'; i+=5; hr='h'; }
  840. else { q.t = "t"; ++i; }
  841. if(dt==null && q.t === 'T') return "";
  842. out[out.length] = q; lst = c; break;
  843. case '[':
  844. o = c;
  845. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  846. if(o.slice(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
  847. if(o.match(abstime)) {
  848. if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
  849. out[out.length] = {t:'Z', v:o.toLowerCase()};
  850. lst = o.charAt(1);
  851. } else if(o.indexOf("$") > -1) {
  852. o = (o.match(/\$([^-\[\]]*)/)||[])[1]||"$";
  853. if(!fmt_is_date(fmt)) out[out.length] = {t:'t',v:o};
  854. }
  855. break;
  856. /* Numbers */
  857. case '.':
  858. if(dt != null) {
  859. o = c; while(++i < fmt.length && (c=fmt.charAt(i)) === "0") o += c;
  860. out[out.length] = {t:'s', v:o}; break;
  861. }
  862. /* falls through */
  863. case '0': case '#':
  864. o = c; while(++i < fmt.length && "0#?.,E+-%".indexOf(c=fmt.charAt(i)) > -1) o += c;
  865. out[out.length] = {t:'n', v:o}; break;
  866. case '?':
  867. o = c; while(fmt.charAt(++i) === c) o+=c;
  868. out[out.length] = {t:c, v:o}; lst = c; break;
  869. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break; // **
  870. case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
  871. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  872. o = c; while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) o+=fmt.charAt(i);
  873. out[out.length] = {t:'D', v:o}; break;
  874. case ' ': out[out.length] = {t:c, v:c}; ++i; break;
  875. case '$': out[out.length] = {t:'t', v:'$'}; ++i; break;
  876. default:
  877. if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
  878. out[out.length] = {t:'t', v:c}; ++i; break;
  879. }
  880. }
  881. /* Scan for date/time parts */
  882. var bt = 0, ss0 = 0, ssm;
  883. for(i=out.length-1, lst='t'; i >= 0; --i) {
  884. switch(out[i].t) {
  885. case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
  886. case 's':
  887. if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
  888. if(bt < 3) bt = 3;
  889. /* falls through */
  890. case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
  891. case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
  892. case 'X': /*if(out[i].v === "B2");*/
  893. break;
  894. case 'Z':
  895. if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
  896. if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
  897. if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
  898. }
  899. }
  900. /* time rounding depends on presence of minute / second / usec fields */
  901. switch(bt) {
  902. case 0: break;
  903. case 1:
  904. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  905. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  906. if(dt.M >= 60) { dt.M = 0; ++dt.H; }
  907. break;
  908. case 2:
  909. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  910. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  911. break;
  912. }
  913. /* replace fields */
  914. var nstr = "", jj;
  915. for(i=0; i < out.length; ++i) {
  916. switch(out[i].t) {
  917. case 't': case 'T': case ' ': case 'D': break;
  918. case 'X': out[i].v = ""; out[i].t = ";"; break;
  919. case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
  920. out[i].v = write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
  921. out[i].t = 't'; break;
  922. case 'n': case '?':
  923. jj = i+1;
  924. while(out[jj] != null && (
  925. (c=out[jj].t) === "?" || c === "D" ||
  926. ((c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/')) ||
  927. (out[i].t === '(' && (c === ' ' || c === 'n' || c === ')')) ||
  928. (c === 't' && (out[jj].v === '/' || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?'))
  929. )) {
  930. out[i].v += out[jj].v;
  931. out[jj] = {v:"", t:";"}; ++jj;
  932. }
  933. nstr += out[i].v;
  934. i = jj-1; break;
  935. case 'G': out[i].t = 't'; out[i].v = general_fmt(v,opts); break;
  936. }
  937. }
  938. var vv = "", myv, ostr;
  939. if(nstr.length > 0) {
  940. if(nstr.charCodeAt(0) == 40) /* '(' */ {
  941. myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v);
  942. ostr = write_num('n', nstr, myv);
  943. } else {
  944. myv = (v<0 && flen > 1 ? -v : v);
  945. ostr = write_num('n', nstr, myv);
  946. if(myv < 0 && out[0] && out[0].t == 't') {
  947. ostr = ostr.substr(1);
  948. out[0].v = "-" + out[0].v;
  949. }
  950. }
  951. jj=ostr.length-1;
  952. var decpt = out.length;
  953. for(i=0; i < out.length; ++i) if(out[i] != null && out[i].t != 't' && out[i].v.indexOf(".") > -1) { decpt = i; break; }
  954. var lasti=out.length;
  955. if(decpt === out.length && ostr.indexOf("E") === -1) {
  956. for(i=out.length-1; i>= 0;--i) {
  957. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  958. if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
  959. else if(jj < 0) out[i].v = "";
  960. else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
  961. out[i].t = 't';
  962. lasti = i;
  963. }
  964. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  965. }
  966. else if(decpt !== out.length && ostr.indexOf("E") === -1) {
  967. jj = ostr.indexOf(".")-1;
  968. for(i=decpt; i>= 0; --i) {
  969. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  970. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
  971. vv = out[i].v.substr(j+1);
  972. for(; j>=0; --j) {
  973. if(jj>=0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#")) vv = ostr.charAt(jj--) + vv;
  974. }
  975. out[i].v = vv;
  976. out[i].t = 't';
  977. lasti = i;
  978. }
  979. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  980. jj = ostr.indexOf(".")+1;
  981. for(i=decpt; i<out.length; ++i) {
  982. if(out[i] == null || ('n?('.indexOf(out[i].t) === -1 && i !== decpt)) continue;
  983. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
  984. vv = out[i].v.substr(0,j);
  985. for(; j<out[i].v.length; ++j) {
  986. if(jj<ostr.length) vv += ostr.charAt(jj++);
  987. }
  988. out[i].v = vv;
  989. out[i].t = 't';
  990. lasti = i;
  991. }
  992. }
  993. }
  994. for(i=0; i<out.length; ++i) if(out[i] != null && 'n?'.indexOf(out[i].t)>-1) {
  995. myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
  996. out[i].v = write_num(out[i].t, out[i].v, myv);
  997. out[i].t = 't';
  998. }
  999. var retval = "";
  1000. for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
  1001. return retval;
  1002. }
  1003. SSF._eval = eval_fmt;
  1004. var cfregex = /\[[=<>]/;
  1005. var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
  1006. function chkcond(v, rr) {
  1007. if(rr == null) return false;
  1008. var thresh = parseFloat(rr[2]);
  1009. switch(rr[1]) {
  1010. case "=": if(v == thresh) return true; break;
  1011. case ">": if(v > thresh) return true; break;
  1012. case "<": if(v < thresh) return true; break;
  1013. case "<>": if(v != thresh) return true; break;
  1014. case ">=": if(v >= thresh) return true; break;
  1015. case "<=": if(v <= thresh) return true; break;
  1016. }
  1017. return false;
  1018. }
  1019. function choose_fmt(f, v) {
  1020. var fmt = split_fmt(f);
  1021. var l = fmt.length, lat = fmt[l-1].indexOf("@");
  1022. if(l<4 && lat>-1) --l;
  1023. if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
  1024. if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
  1025. switch(fmt.length) {
  1026. case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
  1027. case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
  1028. case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
  1029. case 4: break;
  1030. }
  1031. var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
  1032. if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
  1033. if(fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) {
  1034. var m1 = fmt[0].match(cfregex2);
  1035. var m2 = fmt[1].match(cfregex2);
  1036. return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
  1037. }
  1038. return [l, ff];
  1039. }
  1040. function format(fmt,v,o) {
  1041. if(o == null) o = {};
  1042. var sfmt = "";
  1043. switch(typeof fmt) {
  1044. case "string":
  1045. if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
  1046. else sfmt = fmt;
  1047. break;
  1048. case "number":
  1049. if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
  1050. else sfmt = (o.table != null ? (o.table) : table_fmt)[fmt];
  1051. if(sfmt == null) sfmt = (o.table && o.table[default_map[fmt]]) || table_fmt[default_map[fmt]];
  1052. if(sfmt == null) sfmt = default_str[fmt] || "General";
  1053. break;
  1054. }
  1055. if(isgeneral(sfmt,0)) return general_fmt(v, o);
  1056. if(v instanceof Date) v = datenum_local(v, o.date1904);
  1057. var f = choose_fmt(sfmt, v);
  1058. if(isgeneral(f[1])) return general_fmt(v, o);
  1059. if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
  1060. else if(v === "" || v == null) return "";
  1061. return eval_fmt(f[1], v, o, f[0]);
  1062. }
  1063. function load_entry(fmt, idx) {
  1064. if(typeof idx != 'number') {
  1065. idx = +idx || -1;
  1066. for(var i = 0; i < 0x0188; ++i) {
  1067. if(table_fmt[i] == undefined) { if(idx < 0) idx = i; continue; }
  1068. if(table_fmt[i] == fmt) { idx = i; break; }
  1069. }
  1070. if(idx < 0) idx = 0x187;
  1071. }
  1072. table_fmt[idx] = fmt;
  1073. return idx;
  1074. }
  1075. SSF.load = load_entry;
  1076. SSF._table = table_fmt;
  1077. SSF.get_table = function get_table() { return table_fmt; };
  1078. SSF.load_table = function load_table(tbl) {
  1079. for(var i=0; i!=0x0188; ++i)
  1080. if(tbl[i] !== undefined) load_entry(tbl[i], i);
  1081. };
  1082. SSF.init_table = init_table;
  1083. SSF.format = format;
  1084. };
  1085. make_ssf(SSF);
  1086. /* map from xlml named formats to SSF TODO: localize */
  1087. var XLMLFormatMap/*{[string]:string}*/ = ({
  1088. "General Number": "General",
  1089. "General Date": SSF._table[22],
  1090. "Long Date": "dddd, mmmm dd, yyyy",
  1091. "Medium Date": SSF._table[15],
  1092. "Short Date": SSF._table[14],
  1093. "Long Time": SSF._table[19],
  1094. "Medium Time": SSF._table[18],
  1095. "Short Time": SSF._table[20],
  1096. "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1097. "Fixed": SSF._table[2],
  1098. "Standard": SSF._table[4],
  1099. "Percent": SSF._table[10],
  1100. "Scientific": SSF._table[11],
  1101. "Yes/No": '"Yes";"Yes";"No";@',
  1102. "True/False": '"True";"True";"False";@',
  1103. "On/Off": '"Yes";"Yes";"No";@'
  1104. });
  1105. var SSFImplicit/*{[number]:string}*/ = ({
  1106. "5": '"$"#,##0_);\\("$"#,##0\\)',
  1107. "6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  1108. "7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  1109. "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1110. "23": 'General', "24": 'General', "25": 'General', "26": 'General',
  1111. "27": 'm/d/yy', "28": 'm/d/yy', "29": 'm/d/yy', "30": 'm/d/yy', "31": 'm/d/yy',
  1112. "32": 'h:mm:ss', "33": 'h:mm:ss', "34": 'h:mm:ss', "35": 'h:mm:ss',
  1113. "36": 'm/d/yy',
  1114. "41": '_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
  1115. "42": '_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
  1116. "43": '_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
  1117. "44": '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
  1118. "50": 'm/d/yy', "51": 'm/d/yy', "52": 'm/d/yy', "53": 'm/d/yy', "54": 'm/d/yy',
  1119. "55": 'm/d/yy', "56": 'm/d/yy', "57": 'm/d/yy', "58": 'm/d/yy',
  1120. "59": '0',
  1121. "60": '0.00',
  1122. "61": '#,##0',
  1123. "62": '#,##0.00',
  1124. "63": '"$"#,##0_);\\("$"#,##0\\)',
  1125. "64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  1126. "65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  1127. "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1128. "67": '0%',
  1129. "68": '0.00%',
  1130. "69": '# ?/?',
  1131. "70": '# ??/??',
  1132. "71": 'm/d/yy',
  1133. "72": 'm/d/yy',
  1134. "73": 'd-mmm-yy',
  1135. "74": 'd-mmm',
  1136. "75": 'mmm-yy',
  1137. "76": 'h:mm',
  1138. "77": 'h:mm:ss',
  1139. "78": 'm/d/yy h:mm',
  1140. "79": 'mm:ss',
  1141. "80": '[h]:mm:ss',
  1142. "81": 'mmss.0'
  1143. });
  1144. /* dateNF parse TODO: move to SSF */
  1145. var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
  1146. function dateNF_regex(dateNF) {
  1147. var fmt = typeof dateNF == "number" ? SSF._table[dateNF] : dateNF;
  1148. fmt = fmt.replace(dateNFregex, "(\\d+)");
  1149. return new RegExp("^" + fmt + "$");
  1150. }
  1151. function dateNF_fix(str, dateNF, match) {
  1152. var Y = -1, m = -1, d = -1, H = -1, M = -1, S = -1;
  1153. (dateNF.match(dateNFregex)||[]).forEach(function(n, i) {
  1154. var v = parseInt(match[i+1], 10);
  1155. switch(n.toLowerCase().charAt(0)) {
  1156. case 'y': Y = v; break; case 'd': d = v; break;
  1157. case 'h': H = v; break; case 's': S = v; break;
  1158. case 'm': if(H >= 0) M = v; else m = v; break;
  1159. }
  1160. });
  1161. if(S >= 0 && M == -1 && m >= 0) { M = m; m = -1; }
  1162. var datestr = (("" + (Y>=0?Y: new Date().getFullYear())).slice(-4) + "-" + ("00" + (m>=1?m:1)).slice(-2) + "-" + ("00" + (d>=1?d:1)).slice(-2));
  1163. if(datestr.length == 7) datestr = "0" + datestr;
  1164. if(datestr.length == 8) datestr = "20" + datestr;
  1165. var timestr = (("00" + (H>=0?H:0)).slice(-2) + ":" + ("00" + (M>=0?M:0)).slice(-2) + ":" + ("00" + (S>=0?S:0)).slice(-2));
  1166. if(H == -1 && M == -1 && S == -1) return datestr;
  1167. if(Y == -1 && m == -1 && d == -1) return timestr;
  1168. return datestr + "T" + timestr;
  1169. }
  1170. var DO_NOT_EXPORT_CFB = true;
  1171. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  1172. /* vim: set ts=2: */
  1173. /*jshint eqnull:true */
  1174. /*exported CFB */
  1175. /*global Uint8Array:false, Uint16Array:false */
  1176. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  1177. /* vim: set ts=2: */
  1178. /*exported CRC32 */
  1179. var CRC32;
  1180. (function (factory) {
  1181. /*jshint ignore:start */
  1182. /*eslint-disable */
  1183. factory(CRC32 = {});
  1184. /*eslint-enable */
  1185. /*jshint ignore:end */
  1186. }(function(CRC32) {
  1187. CRC32.version = '1.2.0';
  1188. /* see perf/crc32table.js */
  1189. /*global Int32Array */
  1190. function signed_crc_table() {
  1191. var c = 0, table = new Array(256);
  1192. for(var n =0; n != 256; ++n){
  1193. c = n;
  1194. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1195. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1196. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1197. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1198. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1199. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1200. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1201. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1202. table[n] = c;
  1203. }
  1204. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  1205. }
  1206. var T = signed_crc_table();
  1207. function crc32_bstr(bstr, seed) {
  1208. var C = seed ^ -1, L = bstr.length - 1;
  1209. for(var i = 0; i < L;) {
  1210. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  1211. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  1212. }
  1213. if(i === L) C = (C>>>8) ^ T[(C ^ bstr.charCodeAt(i))&0xFF];
  1214. return C ^ -1;
  1215. }
  1216. function crc32_buf(buf, seed) {
  1217. if(buf.length > 10000) return crc32_buf_8(buf, seed);
  1218. var C = seed ^ -1, L = buf.length - 3;
  1219. for(var i = 0; i < L;) {
  1220. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1221. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1222. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1223. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1224. }
  1225. while(i < L+3) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1226. return C ^ -1;
  1227. }
  1228. function crc32_buf_8(buf, seed) {
  1229. var C = seed ^ -1, L = buf.length - 7;
  1230. for(var i = 0; i < L;) {
  1231. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1232. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1233. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1234. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1235. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1236. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1237. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1238. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1239. }
  1240. while(i < L+7) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  1241. return C ^ -1;
  1242. }
  1243. function crc32_str(str, seed) {
  1244. var C = seed ^ -1;
  1245. for(var i = 0, L=str.length, c, d; i < L;) {
  1246. c = str.charCodeAt(i++);
  1247. if(c < 0x80) {
  1248. C = (C>>>8) ^ T[(C ^ c)&0xFF];
  1249. } else if(c < 0x800) {
  1250. C = (C>>>8) ^ T[(C ^ (192|((c>>6)&31)))&0xFF];
  1251. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  1252. } else if(c >= 0xD800 && c < 0xE000) {
  1253. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  1254. C = (C>>>8) ^ T[(C ^ (240|((c>>8)&7)))&0xFF];
  1255. C = (C>>>8) ^ T[(C ^ (128|((c>>2)&63)))&0xFF];
  1256. C = (C>>>8) ^ T[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  1257. C = (C>>>8) ^ T[(C ^ (128|(d&63)))&0xFF];
  1258. } else {
  1259. C = (C>>>8) ^ T[(C ^ (224|((c>>12)&15)))&0xFF];
  1260. C = (C>>>8) ^ T[(C ^ (128|((c>>6)&63)))&0xFF];
  1261. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  1262. }
  1263. }
  1264. return C ^ -1;
  1265. }
  1266. CRC32.table = T;
  1267. CRC32.bstr = crc32_bstr;
  1268. CRC32.buf = crc32_buf;
  1269. CRC32.str = crc32_str;
  1270. }));
  1271. /* [MS-CFB] v20171201 */
  1272. var CFB = (function _CFB(){
  1273. var exports = {};
  1274. exports.version = '1.1.4';
  1275. /* [MS-CFB] 2.6.4 */
  1276. function namecmp(l, r) {
  1277. var L = l.split("/"), R = r.split("/");
  1278. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  1279. if((c = L[i].length - R[i].length)) return c;
  1280. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  1281. }
  1282. return L.length - R.length;
  1283. }
  1284. function dirname(p) {
  1285. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  1286. var c = p.lastIndexOf("/");
  1287. return (c === -1) ? p : p.slice(0, c+1);
  1288. }
  1289. function filename(p) {
  1290. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  1291. var c = p.lastIndexOf("/");
  1292. return (c === -1) ? p : p.slice(c+1);
  1293. }
  1294. /* -------------------------------------------------------------------------- */
  1295. /* DOS Date format:
  1296. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  1297. add 1980 to stored year
  1298. stored second should be doubled
  1299. */
  1300. /* write JS date to buf as a DOS date */
  1301. function write_dos_date(buf, date) {
  1302. if(typeof date === "string") date = new Date(date);
  1303. var hms = date.getHours();
  1304. hms = hms << 6 | date.getMinutes();
  1305. hms = hms << 5 | (date.getSeconds()>>>1);
  1306. buf.write_shift(2, hms);
  1307. var ymd = (date.getFullYear() - 1980);
  1308. ymd = ymd << 4 | (date.getMonth()+1);
  1309. ymd = ymd << 5 | date.getDate();
  1310. buf.write_shift(2, ymd);
  1311. }
  1312. /* read four bytes from buf and interpret as a DOS date */
  1313. function parse_dos_date(buf) {
  1314. var hms = buf.read_shift(2) & 0xFFFF;
  1315. var ymd = buf.read_shift(2) & 0xFFFF;
  1316. var val = new Date();
  1317. var d = ymd & 0x1F; ymd >>>= 5;
  1318. var m = ymd & 0x0F; ymd >>>= 4;
  1319. val.setMilliseconds(0);
  1320. val.setFullYear(ymd + 1980);
  1321. val.setMonth(m-1);
  1322. val.setDate(d);
  1323. var S = hms & 0x1F; hms >>>= 5;
  1324. var M = hms & 0x3F; hms >>>= 6;
  1325. val.setHours(hms);
  1326. val.setMinutes(M);
  1327. val.setSeconds(S<<1);
  1328. return val;
  1329. }
  1330. function parse_extra_field(blob) {
  1331. prep_blob(blob, 0);
  1332. var o = {};
  1333. var flags = 0;
  1334. while(blob.l <= blob.length - 4) {
  1335. var type = blob.read_shift(2);
  1336. var sz = blob.read_shift(2), tgt = blob.l + sz;
  1337. var p = {};
  1338. switch(type) {
  1339. /* UNIX-style Timestamps */
  1340. case 0x5455: {
  1341. flags = blob.read_shift(1);
  1342. if(flags & 1) p.mtime = blob.read_shift(4);
  1343. /* for some reason, CD flag corresponds to LFH */
  1344. if(sz > 5) {
  1345. if(flags & 2) p.atime = blob.read_shift(4);
  1346. if(flags & 4) p.ctime = blob.read_shift(4);
  1347. }
  1348. if(p.mtime) p.mt = new Date(p.mtime*1000);
  1349. }
  1350. break;
  1351. }
  1352. blob.l = tgt;
  1353. o[type] = p;
  1354. }
  1355. return o;
  1356. }
  1357. var fs;
  1358. function get_fs() { return fs || (fs = require('fs')); }
  1359. function parse(file, options) {
  1360. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  1361. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  1362. var mver = 3;
  1363. var ssz = 512;
  1364. var nmfs = 0; // number of mini FAT sectors
  1365. var difat_sec_cnt = 0;
  1366. var dir_start = 0;
  1367. var minifat_start = 0;
  1368. var difat_start = 0;
  1369. var fat_addrs = []; // locations of FAT sectors
  1370. /* [MS-CFB] 2.2 Compound File Header */
  1371. var blob = file.slice(0,512);
  1372. prep_blob(blob, 0);
  1373. /* major version */
  1374. var mv = check_get_mver(blob);
  1375. mver = mv[0];
  1376. switch(mver) {
  1377. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  1378. case 0: if(mv[1] == 0) return parse_zip(file, options);
  1379. /* falls through */
  1380. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  1381. }
  1382. /* reprocess header */
  1383. if(ssz !== 512) { blob = file.slice(0,ssz); prep_blob(blob, 28 /* blob.l */); }
  1384. /* Save header for final object */
  1385. var header = file.slice(0,ssz);
  1386. check_shifts(blob, mver);
  1387. // Number of Directory Sectors
  1388. var dir_cnt = blob.read_shift(4, 'i');
  1389. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  1390. // Number of FAT Sectors
  1391. blob.l += 4;
  1392. // First Directory Sector Location
  1393. dir_start = blob.read_shift(4, 'i');
  1394. // Transaction Signature
  1395. blob.l += 4;
  1396. // Mini Stream Cutoff Size
  1397. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  1398. // First Mini FAT Sector Location
  1399. minifat_start = blob.read_shift(4, 'i');
  1400. // Number of Mini FAT Sectors
  1401. nmfs = blob.read_shift(4, 'i');
  1402. // First DIFAT sector location
  1403. difat_start = blob.read_shift(4, 'i');
  1404. // Number of DIFAT Sectors
  1405. difat_sec_cnt = blob.read_shift(4, 'i');
  1406. // Grab FAT Sector Locations
  1407. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  1408. q = blob.read_shift(4, 'i');
  1409. if(q<0) break;
  1410. fat_addrs[j] = q;
  1411. }
  1412. /** Break the file up into sectors */
  1413. var sectors = sectorify(file, ssz);
  1414. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  1415. /** Chains */
  1416. var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  1417. sector_list[dir_start].name = "!Directory";
  1418. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  1419. sector_list[fat_addrs[0]].name = "!FAT";
  1420. sector_list.fat_addrs = fat_addrs;
  1421. sector_list.ssz = ssz;
  1422. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  1423. var files = {}, Paths = [], FileIndex = [], FullPaths = [];
  1424. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  1425. build_full_paths(FileIndex, FullPaths, Paths);
  1426. Paths.shift();
  1427. var o = {
  1428. FileIndex: FileIndex,
  1429. FullPaths: FullPaths
  1430. };
  1431. // $FlowIgnore
  1432. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  1433. return o;
  1434. } // parse
  1435. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  1436. function check_get_mver(blob) {
  1437. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  1438. // header signature 8
  1439. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  1440. // clsid 16
  1441. //blob.chk(HEADER_CLSID, 'CLSID: ');
  1442. blob.l += 16;
  1443. // minor version 2
  1444. var mver = blob.read_shift(2, 'u');
  1445. return [blob.read_shift(2,'u'), mver];
  1446. }
  1447. function check_shifts(blob, mver) {
  1448. var shift = 0x09;
  1449. // Byte Order
  1450. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  1451. blob.l += 2;
  1452. // Sector Shift
  1453. switch((shift = blob.read_shift(2))) {
  1454. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  1455. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  1456. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  1457. }
  1458. // Mini Sector Shift
  1459. blob.chk('0600', 'Mini Sector Shift: ');
  1460. // Reserved
  1461. blob.chk('000000000000', 'Reserved: ');
  1462. }
  1463. /** Break the file up into sectors */
  1464. function sectorify(file, ssz) {
  1465. var nsectors = Math.ceil(file.length/ssz)-1;
  1466. var sectors = [];
  1467. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  1468. sectors[nsectors-1] = file.slice(nsectors*ssz);
  1469. return sectors;
  1470. }
  1471. /* [MS-CFB] 2.6.4 Red-Black Tree */
  1472. function build_full_paths(FI, FP, Paths) {
  1473. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  1474. var dad = [], q = [];
  1475. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  1476. for(; j < q.length; ++j) {
  1477. i = q[j];
  1478. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  1479. if(dad[i] === i) {
  1480. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  1481. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  1482. }
  1483. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  1484. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  1485. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  1486. }
  1487. for(i=1; i < pl; ++i) if(dad[i] === i) {
  1488. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  1489. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  1490. }
  1491. for(i=1; i < pl; ++i) {
  1492. if(FI[i].type === 0 /* unknown */) continue;
  1493. j = i;
  1494. if(j != dad[j]) do {
  1495. j = dad[j];
  1496. FP[i] = FP[j] + "/" + FP[i];
  1497. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  1498. dad[i] = -1;
  1499. }
  1500. FP[0] += "/";
  1501. for(i=1; i < pl; ++i) {
  1502. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  1503. }
  1504. }
  1505. function get_mfat_entry(entry, payload, mini) {
  1506. var start = entry.start, size = entry.size;
  1507. //return (payload.slice(start*MSSZ, start*MSSZ + size));
  1508. var o = [];
  1509. var idx = start;
  1510. while(mini && size > 0 && idx >= 0) {
  1511. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  1512. size -= MSSZ;
  1513. idx = __readInt32LE(mini, idx * 4);
  1514. }
  1515. if(o.length === 0) return (new_buf(0));
  1516. return (bconcat(o).slice(0, entry.size));
  1517. }
  1518. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  1519. DIFAT chains by storing the next sector number as the last 32 bits */
  1520. function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
  1521. var q = ENDOFCHAIN;
  1522. if(idx === ENDOFCHAIN) {
  1523. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  1524. } else if(idx !== -1 /*FREESECT*/) {
  1525. var sector = sectors[idx], m = (ssz>>>2)-1;
  1526. if(!sector) return;
  1527. for(var i = 0; i < m; ++i) {
  1528. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  1529. fat_addrs.push(q);
  1530. }
  1531. if(cnt >= 1) sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  1532. }
  1533. }
  1534. /** Follow the linked list of sectors for a given starting point */
  1535. function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
  1536. var buf = [], buf_chain = [];
  1537. if(!chkd) chkd = [];
  1538. var modulus = ssz - 1, j = 0, jj = 0;
  1539. for(j=start; j>=0;) {
  1540. chkd[j] = true;
  1541. buf[buf.length] = j;
  1542. buf_chain.push(sectors[j]);
  1543. var addr = fat_addrs[Math.floor(j*4/ssz)];
  1544. jj = ((j*4) & modulus);
  1545. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  1546. if(!sectors[addr]) break;
  1547. j = __readInt32LE(sectors[addr], jj);
  1548. }
  1549. return {nodes: buf, data:__toBuffer([buf_chain])};
  1550. }
  1551. /** Chase down the sector linked lists */
  1552. function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
  1553. var sl = sectors.length, sector_list = ([]);
  1554. var chkd = [], buf = [], buf_chain = [];
  1555. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  1556. for(i=0; i < sl; ++i) {
  1557. buf = ([]);
  1558. k = (i + dir_start); if(k >= sl) k-=sl;
  1559. if(chkd[k]) continue;
  1560. buf_chain = [];
  1561. var seen = [];
  1562. for(j=k; j>=0;) {
  1563. seen[j] = true;
  1564. chkd[j] = true;
  1565. buf[buf.length] = j;
  1566. buf_chain.push(sectors[j]);
  1567. var addr = fat_addrs[Math.floor(j*4/ssz)];
  1568. jj = ((j*4) & modulus);
  1569. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  1570. if(!sectors[addr]) break;
  1571. j = __readInt32LE(sectors[addr], jj);
  1572. if(seen[j]) break;
  1573. }
  1574. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])});
  1575. }
  1576. return sector_list;
  1577. }
  1578. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  1579. function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
  1580. var minifat_store = 0, pl = (Paths.length?2:0);
  1581. var sector = sector_list[dir_start].data;
  1582. var i = 0, namelen = 0, name;
  1583. for(; i < sector.length; i+= 128) {
  1584. var blob = sector.slice(i, i+128);
  1585. prep_blob(blob, 64);
  1586. namelen = blob.read_shift(2);
  1587. name = __utf16le(blob,0,namelen-pl);
  1588. Paths.push(name);
  1589. var o = ({
  1590. name: name,
  1591. type: blob.read_shift(1),
  1592. color: blob.read_shift(1),
  1593. L: blob.read_shift(4, 'i'),
  1594. R: blob.read_shift(4, 'i'),
  1595. C: blob.read_shift(4, 'i'),
  1596. clsid: blob.read_shift(16),
  1597. state: blob.read_shift(4, 'i'),
  1598. start: 0,
  1599. size: 0
  1600. });
  1601. var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  1602. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  1603. var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  1604. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  1605. o.start = blob.read_shift(4, 'i');
  1606. o.size = blob.read_shift(4, 'i');
  1607. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  1608. if(o.type === 5) { /* root */
  1609. minifat_store = o.start;
  1610. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  1611. /*minifat_size = o.size;*/
  1612. } else if(o.size >= 4096 /* MSCSZ */) {
  1613. o.storage = 'fat';
  1614. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  1615. sector_list[o.start].name = o.name;
  1616. o.content = (sector_list[o.start].data.slice(0,o.size));
  1617. } else {
  1618. o.storage = 'minifat';
  1619. if(o.size < 0) o.size = 0;
  1620. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  1621. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  1622. }
  1623. }
  1624. if(o.content) prep_blob(o.content, 0);
  1625. files[name] = o;
  1626. FileIndex.push(o);
  1627. }
  1628. }
  1629. function read_date(blob, offset) {
  1630. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  1631. }
  1632. function read_file(filename, options) {
  1633. get_fs();
  1634. return parse(fs.readFileSync(filename), options);
  1635. }
  1636. function read(blob, options) {
  1637. switch(options && options.type || "base64") {
  1638. case "file": return read_file(blob, options);
  1639. case "base64": return parse(s2a(Base64.decode(blob)), options);
  1640. case "binary": return parse(s2a(blob), options);
  1641. }
  1642. return parse(blob, options);
  1643. }
  1644. function init_cfb(cfb, opts) {
  1645. var o = opts || {}, root = o.root || "Root Entry";
  1646. if(!cfb.FullPaths) cfb.FullPaths = [];
  1647. if(!cfb.FileIndex) cfb.FileIndex = [];
  1648. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  1649. if(cfb.FullPaths.length === 0) {
  1650. cfb.FullPaths[0] = root + "/";
  1651. cfb.FileIndex[0] = ({ name: root, type: 5 });
  1652. }
  1653. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  1654. seed_cfb(cfb);
  1655. }
  1656. function seed_cfb(cfb) {
  1657. var nm = "\u0001Sh33tJ5";
  1658. if(CFB.find(cfb, "/" + nm)) return;
  1659. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  1660. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }));
  1661. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  1662. rebuild_cfb(cfb);
  1663. }
  1664. function rebuild_cfb(cfb, f) {
  1665. init_cfb(cfb);
  1666. var gc = false, s = false;
  1667. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  1668. var _file = cfb.FileIndex[i];
  1669. switch(_file.type) {
  1670. case 0:
  1671. if(s) gc = true;
  1672. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  1673. break;
  1674. case 1: case 2: case 5:
  1675. s = true;
  1676. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  1677. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  1678. break;
  1679. default: gc = true; break;
  1680. }
  1681. }
  1682. if(!gc && !f) return;
  1683. var now = new Date(1987, 1, 19), j = 0;
  1684. var data = [];
  1685. for(i = 0; i < cfb.FullPaths.length; ++i) {
  1686. if(cfb.FileIndex[i].type === 0) continue;
  1687. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  1688. }
  1689. for(i = 0; i < data.length; ++i) {
  1690. var dad = dirname(data[i][0]);
  1691. s = false;
  1692. for(j = 0; j < data.length; ++j) if(data[j][0] === dad) s = true;
  1693. if(!s) data.push([dad, ({
  1694. name: filename(dad).replace("/",""),
  1695. type: 1,
  1696. clsid: HEADER_CLSID,
  1697. ct: now, mt: now,
  1698. content: null
  1699. })]);
  1700. }
  1701. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  1702. cfb.FullPaths = []; cfb.FileIndex = [];
  1703. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  1704. for(i = 0; i < data.length; ++i) {
  1705. var elt = cfb.FileIndex[i];
  1706. var nm = cfb.FullPaths[i];
  1707. elt.name = filename(nm).replace("/","");
  1708. elt.L = elt.R = elt.C = -(elt.color = 1);
  1709. elt.size = elt.content ? elt.content.length : 0;
  1710. elt.start = 0;
  1711. elt.clsid = (elt.clsid || HEADER_CLSID);
  1712. if(i === 0) {
  1713. elt.C = data.length > 1 ? 1 : -1;
  1714. elt.size = 0;
  1715. elt.type = 5;
  1716. } else if(nm.slice(-1) == "/") {
  1717. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  1718. elt.C = j >= data.length ? -1 : j;
  1719. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  1720. elt.R = j >= data.length ? -1 : j;
  1721. elt.type = 1;
  1722. } else {
  1723. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  1724. elt.type = 2;
  1725. }
  1726. }
  1727. }
  1728. function _write(cfb, options) {
  1729. var _opts = options || {};
  1730. rebuild_cfb(cfb);
  1731. if(_opts.fileType == 'zip') return write_zip(cfb, _opts);
  1732. var L = (function(cfb){
  1733. var mini_size = 0, fat_size = 0;
  1734. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  1735. var file = cfb.FileIndex[i];
  1736. if(!file.content) continue;
  1737. var flen = file.content.length;
  1738. if(flen > 0){
  1739. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  1740. else fat_size += (flen + 0x01FF) >> 9;
  1741. }
  1742. }
  1743. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  1744. var mini_cnt = (mini_size + 7) >> 3;
  1745. var mfat_cnt = (mini_size + 0x7F) >> 7;
  1746. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  1747. var fat_cnt = (fat_base + 0x7F) >> 7;
  1748. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  1749. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  1750. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  1751. cfb.FileIndex[0].size = mini_size << 6;
  1752. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  1753. return L;
  1754. })(cfb);
  1755. var o = new_buf(L[7] << 9);
  1756. var i = 0, T = 0;
  1757. {
  1758. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  1759. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  1760. o.write_shift(2, 0x003E);
  1761. o.write_shift(2, 0x0003);
  1762. o.write_shift(2, 0xFFFE);
  1763. o.write_shift(2, 0x0009);
  1764. o.write_shift(2, 0x0006);
  1765. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  1766. o.write_shift(4, 0);
  1767. o.write_shift(4, L[2]);
  1768. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  1769. o.write_shift(4, 0);
  1770. o.write_shift(4, 1<<12);
  1771. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  1772. o.write_shift(4, L[3]);
  1773. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  1774. o.write_shift(4, L[1]);
  1775. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  1776. }
  1777. if(L[1]) {
  1778. for(T = 0; T < L[1]; ++T) {
  1779. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  1780. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  1781. }
  1782. }
  1783. var chainit = function(w) {
  1784. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  1785. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  1786. };
  1787. T = i = 0;
  1788. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  1789. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  1790. chainit(L[3]);
  1791. chainit(L[4]);
  1792. var j = 0, flen = 0;
  1793. var file = cfb.FileIndex[0];
  1794. for(; j < cfb.FileIndex.length; ++j) {
  1795. file = cfb.FileIndex[j];
  1796. if(!file.content) continue;
  1797. flen = file.content.length;
  1798. if(flen < 0x1000) continue;
  1799. file.start = T;
  1800. chainit((flen + 0x01FF) >> 9);
  1801. }
  1802. chainit((L[6] + 7) >> 3);
  1803. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  1804. T = i = 0;
  1805. for(j = 0; j < cfb.FileIndex.length; ++j) {
  1806. file = cfb.FileIndex[j];
  1807. if(!file.content) continue;
  1808. flen = file.content.length;
  1809. if(!flen || flen >= 0x1000) continue;
  1810. file.start = T;
  1811. chainit((flen + 0x3F) >> 6);
  1812. }
  1813. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  1814. for(i = 0; i < L[4]<<2; ++i) {
  1815. var nm = cfb.FullPaths[i];
  1816. if(!nm || nm.length === 0) {
  1817. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  1818. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  1819. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  1820. continue;
  1821. }
  1822. file = cfb.FileIndex[i];
  1823. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  1824. var _nm = (i === 0 && _opts.root) || file.name;
  1825. flen = 2*(_nm.length+1);
  1826. o.write_shift(64, _nm, "utf16le");
  1827. o.write_shift(2, flen);
  1828. o.write_shift(1, file.type);
  1829. o.write_shift(1, file.color);
  1830. o.write_shift(-4, file.L);
  1831. o.write_shift(-4, file.R);
  1832. o.write_shift(-4, file.C);
  1833. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  1834. else o.write_shift(16, file.clsid, "hex");
  1835. o.write_shift(4, file.state || 0);
  1836. o.write_shift(4, 0); o.write_shift(4, 0);
  1837. o.write_shift(4, 0); o.write_shift(4, 0);
  1838. o.write_shift(4, file.start);
  1839. o.write_shift(4, file.size); o.write_shift(4, 0);
  1840. }
  1841. for(i = 1; i < cfb.FileIndex.length; ++i) {
  1842. file = cfb.FileIndex[i];
  1843. if(file.size >= 0x1000) {
  1844. o.l = (file.start+1) << 9;
  1845. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  1846. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  1847. }
  1848. }
  1849. for(i = 1; i < cfb.FileIndex.length; ++i) {
  1850. file = cfb.FileIndex[i];
  1851. if(file.size > 0 && file.size < 0x1000) {
  1852. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  1853. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  1854. }
  1855. }
  1856. while(o.l < o.length) o.write_shift(1, 0);
  1857. return o;
  1858. }
  1859. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  1860. function find(cfb, path) {
  1861. var UCFullPaths = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  1862. var UCPaths = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  1863. var k = false;
  1864. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  1865. else k = path.indexOf("/") !== -1;
  1866. var UCPath = path.toUpperCase();
  1867. var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  1868. if(w !== -1) return cfb.FileIndex[w];
  1869. var m = !UCPath.match(chr1);
  1870. UCPath = UCPath.replace(chr0,'');
  1871. if(m) UCPath = UCPath.replace(chr1,'!');
  1872. for(w = 0; w < UCFullPaths.length; ++w) {
  1873. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  1874. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  1875. }
  1876. return null;
  1877. }
  1878. /** CFB Constants */
  1879. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  1880. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  1881. /* 2.1 Compound File Sector Numbers and Types */
  1882. var ENDOFCHAIN = -2;
  1883. /* 2.2 Compound File Header */
  1884. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  1885. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  1886. var HEADER_CLSID = '00000000000000000000000000000000';
  1887. var consts = {
  1888. /* 2.1 Compund File Sector Numbers and Types */
  1889. MAXREGSECT: -6,
  1890. DIFSECT: -4,
  1891. FATSECT: -3,
  1892. ENDOFCHAIN: ENDOFCHAIN,
  1893. FREESECT: -1,
  1894. /* 2.2 Compound File Header */
  1895. HEADER_SIGNATURE: HEADER_SIGNATURE,
  1896. HEADER_MINOR_VERSION: '3e00',
  1897. MAXREGSID: -6,
  1898. NOSTREAM: -1,
  1899. HEADER_CLSID: HEADER_CLSID,
  1900. /* 2.6.1 Compound File Directory Entry */
  1901. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  1902. };
  1903. function write_file(cfb, filename, options) {
  1904. get_fs();
  1905. var o = _write(cfb, options);
  1906. fs.writeFileSync(filename, o);
  1907. }
  1908. function a2s(o) {
  1909. var out = new Array(o.length);
  1910. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  1911. return out.join("");
  1912. }
  1913. function write(cfb, options) {
  1914. var o = _write(cfb, options);
  1915. switch(options && options.type) {
  1916. case "file": get_fs(); fs.writeFileSync(options.filename, (o)); return o;
  1917. case "binary": return a2s(o);
  1918. case "base64": return Base64.encode(a2s(o));
  1919. }
  1920. return o;
  1921. }
  1922. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  1923. var _zlib;
  1924. function use_zlib(zlib) { try {
  1925. var InflateRaw = zlib.InflateRaw;
  1926. var InflRaw = new InflateRaw();
  1927. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  1928. if(InflRaw.bytesRead) _zlib = zlib;
  1929. else throw new Error("zlib does not expose bytesRead");
  1930. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  1931. function _inflateRawSync(payload, usz) {
  1932. if(!_zlib) return _inflate(payload, usz);
  1933. var InflateRaw = _zlib.InflateRaw;
  1934. var InflRaw = new InflateRaw();
  1935. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  1936. payload.l += InflRaw.bytesRead;
  1937. return out;
  1938. }
  1939. function _deflateRawSync(payload) {
  1940. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  1941. }
  1942. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  1943. /* LEN_ID = [ 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 ]; */
  1944. var LEN_LN = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13 , 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 ];
  1945. /* DST_ID = [ 0, 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 ]; */
  1946. var DST_LN = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ];
  1947. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  1948. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  1949. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  1950. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  1951. function bit_swap_n(n, b) {
  1952. var rev = bitswap8[n & 0xFF];
  1953. if(b <= 8) return rev >>> (8-b);
  1954. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  1955. if(b <= 16) return rev >>> (16-b);
  1956. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  1957. return rev >>> (24-b);
  1958. }
  1959. /* helpers for unaligned bit reads */
  1960. function read_bits_2(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 6 ? 0 : buf[h+1]<<8))>>>w)& 0x03; }
  1961. function read_bits_3(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 5 ? 0 : buf[h+1]<<8))>>>w)& 0x07; }
  1962. function read_bits_4(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 4 ? 0 : buf[h+1]<<8))>>>w)& 0x0F; }
  1963. function read_bits_5(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 3 ? 0 : buf[h+1]<<8))>>>w)& 0x1F; }
  1964. function read_bits_7(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 1 ? 0 : buf[h+1]<<8))>>>w)& 0x7F; }
  1965. /* works up to n = 3 * 8 + 1 = 25 */
  1966. function read_bits_n(buf, bl, n) {
  1967. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  1968. var v = buf[h] >>> w;
  1969. if(n < 8 - w) return v & f;
  1970. v |= buf[h+1]<<(8-w);
  1971. if(n < 16 - w) return v & f;
  1972. v |= buf[h+2]<<(16-w);
  1973. if(n < 24 - w) return v & f;
  1974. v |= buf[h+3]<<(24-w);
  1975. return v & f;
  1976. }
  1977. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  1978. function realloc(b, sz) {
  1979. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  1980. if(L >= sz) return b;
  1981. if(has_buf) {
  1982. var o = new_unsafe_buf(M);
  1983. // $FlowIgnore
  1984. if(b.copy) b.copy(o);
  1985. else for(; i < b.length; ++i) o[i] = b[i];
  1986. return o;
  1987. } else if(use_typed_arrays) {
  1988. var a = new Uint8Array(M);
  1989. if(a.set) a.set(b);
  1990. else for(; i < b.length; ++i) a[i] = b[i];
  1991. return a;
  1992. }
  1993. b.length = M;
  1994. return b;
  1995. }
  1996. /* zero-filled arrays for older browsers */
  1997. function zero_fill_array(n) {
  1998. var o = new Array(n);
  1999. for(var i = 0; i < n; ++i) o[i] = 0;
  2000. return o;
  2001. }var _deflate = (function() {
  2002. var _deflateRaw = (function() {
  2003. return function deflateRaw(data, out) {
  2004. var boff = 0;
  2005. while(boff < data.length) {
  2006. var L = Math.min(0xFFFF, data.length - boff);
  2007. var h = boff + L == data.length;
  2008. /* TODO: this is only type 0 stored */
  2009. out.write_shift(1, +h);
  2010. out.write_shift(2, L);
  2011. out.write_shift(2, (~L) & 0xFFFF);
  2012. while(L-- > 0) out[out.l++] = data[boff++];
  2013. }
  2014. return out.l;
  2015. };
  2016. })();
  2017. return function(data) {
  2018. var buf = new_buf(50+Math.floor(data.length*1.1));
  2019. var off = _deflateRaw(data, buf);
  2020. return buf.slice(0, off);
  2021. };
  2022. })();
  2023. /* modified inflate function also moves original read head */
  2024. /* build tree (used for literals and lengths) */
  2025. function build_tree(clens, cmap, MAX) {
  2026. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  2027. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  2028. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  2029. for(i = L; i < MAX; ++i) clens[i] = 0;
  2030. L = clens.length;
  2031. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  2032. /* build code tree */
  2033. for(i = 0; i < L; ++i) {
  2034. bl_count[(w = clens[i])]++;
  2035. if(maxlen < w) maxlen = w;
  2036. ctree[i] = 0;
  2037. }
  2038. bl_count[0] = 0;
  2039. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  2040. for(i = 0; i < L; ++i) {
  2041. ccode = clens[i];
  2042. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  2043. }
  2044. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  2045. var cleni = 0;
  2046. for(i = 0; i < L; ++i) {
  2047. cleni = clens[i];
  2048. if(cleni != 0) {
  2049. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  2050. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  2051. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  2052. }
  2053. }
  2054. return maxlen;
  2055. }
  2056. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  2057. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  2058. if(!use_typed_arrays) {
  2059. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  2060. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  2061. }
  2062. (function() {
  2063. var dlens = [];
  2064. var i = 0;
  2065. for(;i<32; i++) dlens.push(5);
  2066. build_tree(dlens, fix_dmap, 32);
  2067. var clens = [];
  2068. i = 0;
  2069. for(; i<=143; i++) clens.push(8);
  2070. for(; i<=255; i++) clens.push(9);
  2071. for(; i<=279; i++) clens.push(7);
  2072. for(; i<=287; i++) clens.push(8);
  2073. build_tree(clens, fix_lmap, 288);
  2074. })();
  2075. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  2076. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  2077. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  2078. var dyn_len_1 = 1, dyn_len_2 = 1;
  2079. /* 5.5.3 Expanding Huffman Codes */
  2080. function dyn(data, boff) {
  2081. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  2082. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  2083. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  2084. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  2085. var w = 0;
  2086. /* grab and store code lengths */
  2087. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  2088. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  2089. var maxlen = 1;
  2090. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  2091. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  2092. var L = clens.length; /* 19 */
  2093. for(var i = 0; i < _HCLEN; ++i) {
  2094. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  2095. if(maxlen < w) maxlen = w;
  2096. bl_count[w]++;
  2097. boff += 3;
  2098. }
  2099. /* build code tree */
  2100. var ccode = 0;
  2101. bl_count[0] = 0;
  2102. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  2103. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  2104. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  2105. var cleni = 0;
  2106. for(i = 0; i < L; ++i) {
  2107. cleni = clens[i];
  2108. if(cleni != 0) {
  2109. ccode = bitswap8[ctree[i]]>>(8-cleni);
  2110. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  2111. }
  2112. }
  2113. /* read literal and dist codes at once */
  2114. var hcodes = [];
  2115. maxlen = 1;
  2116. for(; hcodes.length < _HLIT + _HDIST;) {
  2117. ccode = dyn_cmap[read_bits_7(data, boff)];
  2118. boff += ccode & 7;
  2119. switch((ccode >>>= 3)) {
  2120. case 16:
  2121. w = 3 + read_bits_2(data, boff); boff += 2;
  2122. ccode = hcodes[hcodes.length - 1];
  2123. while(w-- > 0) hcodes.push(ccode);
  2124. break;
  2125. case 17:
  2126. w = 3 + read_bits_3(data, boff); boff += 3;
  2127. while(w-- > 0) hcodes.push(0);
  2128. break;
  2129. case 18:
  2130. w = 11 + read_bits_7(data, boff); boff += 7;
  2131. while(w -- > 0) hcodes.push(0);
  2132. break;
  2133. default:
  2134. hcodes.push(ccode);
  2135. if(maxlen < ccode) maxlen = ccode;
  2136. break;
  2137. }
  2138. }
  2139. /* build literal / length trees */
  2140. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  2141. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  2142. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  2143. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  2144. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  2145. return boff;
  2146. }
  2147. /* return [ data, bytesRead ] */
  2148. function inflate(data, usz) {
  2149. /* shortcircuit for empty buffer [0x03, 0x00] */
  2150. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  2151. /* bit offset */
  2152. var boff = 0;
  2153. /* header includes final bit and type bits */
  2154. var header = 0;
  2155. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  2156. var woff = 0;
  2157. var OL = outbuf.length>>>0;
  2158. var max_len_1 = 0, max_len_2 = 0;
  2159. while((header&1) == 0) {
  2160. header = read_bits_3(data, boff); boff += 3;
  2161. if((header >>> 1) == 0) {
  2162. /* Stored block */
  2163. if(boff & 7) boff += 8 - (boff&7);
  2164. /* 2 bytes sz, 2 bytes bit inverse */
  2165. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  2166. boff += 32;
  2167. /* push sz bytes */
  2168. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  2169. if(typeof data.copy === 'function') {
  2170. // $FlowIgnore
  2171. data.copy(outbuf, woff, boff>>>3, (boff>>>3)+sz);
  2172. woff += sz; boff += 8*sz;
  2173. } else while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  2174. continue;
  2175. } else if((header >>> 1) == 1) {
  2176. /* Fixed Huffman */
  2177. max_len_1 = 9; max_len_2 = 5;
  2178. } else {
  2179. /* Dynamic Huffman */
  2180. boff = dyn(data, boff);
  2181. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  2182. }
  2183. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  2184. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  2185. /* ingest code and move read head */
  2186. var bits = read_bits_n(data, boff, max_len_1);
  2187. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  2188. boff += code & 15; code >>>= 4;
  2189. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  2190. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  2191. else if(code == 256) break;
  2192. else {
  2193. code -= 257;
  2194. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  2195. var tgt = woff + LEN_LN[code];
  2196. /* length extra bits */
  2197. if(len_eb > 0) {
  2198. tgt += read_bits_n(data, boff, len_eb);
  2199. boff += len_eb;
  2200. }
  2201. /* dist code */
  2202. bits = read_bits_n(data, boff, max_len_2);
  2203. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  2204. boff += code & 15; code >>>= 4;
  2205. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  2206. var dst = DST_LN[code];
  2207. /* dist extra bits */
  2208. if(dst_eb > 0) {
  2209. dst += read_bits_n(data, boff, dst_eb);
  2210. boff += dst_eb;
  2211. }
  2212. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  2213. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt); OL = outbuf.length; }
  2214. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  2215. }
  2216. }
  2217. }
  2218. return [usz ? outbuf : outbuf.slice(0, woff), (boff+7)>>>3];
  2219. }
  2220. function _inflate(payload, usz) {
  2221. var data = payload.slice(payload.l||0);
  2222. var out = inflate(data, usz);
  2223. payload.l += out[1];
  2224. return out[0];
  2225. }
  2226. function warn_or_throw(wrn, msg) {
  2227. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  2228. else throw new Error(msg);
  2229. }
  2230. function parse_zip(file, options) {
  2231. var blob = file;
  2232. prep_blob(blob, 0);
  2233. var FileIndex = [], FullPaths = [];
  2234. var o = {
  2235. FileIndex: FileIndex,
  2236. FullPaths: FullPaths
  2237. };
  2238. init_cfb(o, { root: options.root });
  2239. /* find end of central directory, start just after signature */
  2240. var i = blob.length - 4;
  2241. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  2242. blob.l = i + 4;
  2243. /* parse end of central directory */
  2244. blob.l += 4;
  2245. var fcnt = blob.read_shift(2);
  2246. blob.l += 6;
  2247. var start_cd = blob.read_shift(4);
  2248. /* parse central directory */
  2249. blob.l = start_cd;
  2250. for(i = 0; i < fcnt; ++i) {
  2251. /* trust local file header instead of CD entry */
  2252. blob.l += 20;
  2253. var csz = blob.read_shift(4);
  2254. var usz = blob.read_shift(4);
  2255. var namelen = blob.read_shift(2);
  2256. var efsz = blob.read_shift(2);
  2257. var fcsz = blob.read_shift(2);
  2258. blob.l += 8;
  2259. var offset = blob.read_shift(4);
  2260. var EF = parse_extra_field(blob.slice(blob.l+namelen, blob.l+namelen+efsz));
  2261. blob.l += namelen + efsz + fcsz;
  2262. var L = blob.l;
  2263. blob.l = offset + 4;
  2264. parse_local_file(blob, csz, usz, o, EF);
  2265. blob.l = L;
  2266. }
  2267. return o;
  2268. }
  2269. /* head starts just after local file header signature */
  2270. function parse_local_file(blob, csz, usz, o, EF) {
  2271. /* [local file header] */
  2272. blob.l += 2;
  2273. var flags = blob.read_shift(2);
  2274. var meth = blob.read_shift(2);
  2275. var date = parse_dos_date(blob);
  2276. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  2277. var crc32 = blob.read_shift(4);
  2278. var _csz = blob.read_shift(4);
  2279. var _usz = blob.read_shift(4);
  2280. var namelen = blob.read_shift(2);
  2281. var efsz = blob.read_shift(2);
  2282. // TODO: flags & (1<<11) // UTF8
  2283. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  2284. if(efsz) {
  2285. var ef = parse_extra_field(blob.slice(blob.l, blob.l + efsz));
  2286. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  2287. if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
  2288. }
  2289. blob.l += efsz;
  2290. /* [encryption header] */
  2291. /* [file data] */
  2292. var data = blob.slice(blob.l, blob.l + _csz);
  2293. switch(meth) {
  2294. case 8: data = _inflateRawSync(blob, _usz); break;
  2295. case 0: break;
  2296. default: throw new Error("Unsupported ZIP Compression method " + meth);
  2297. }
  2298. /* [data descriptor] */
  2299. var wrn = false;
  2300. if(flags & 8) {
  2301. crc32 = blob.read_shift(4);
  2302. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  2303. _csz = blob.read_shift(4);
  2304. _usz = blob.read_shift(4);
  2305. }
  2306. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  2307. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  2308. var _crc32 = CRC32.buf(data, 0);
  2309. if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  2310. cfb_add(o, name, data, {unsafe: true, mt: date});
  2311. }
  2312. function write_zip(cfb, options) {
  2313. var _opts = options || {};
  2314. var out = [], cdirs = [];
  2315. var o = new_buf(1);
  2316. var method = (_opts.compression ? 8 : 0), flags = 0;
  2317. var desc = false;
  2318. if(desc) flags |= 8;
  2319. var i = 0, j = 0;
  2320. var start_cd = 0, fcnt = 0;
  2321. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  2322. var crcs = [];
  2323. var sz_cd = 0;
  2324. for(i = 1; i < cfb.FullPaths.length; ++i) {
  2325. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  2326. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  2327. var start = start_cd;
  2328. /* TODO: CP437 filename */
  2329. var namebuf = new_buf(fp.length);
  2330. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  2331. namebuf = namebuf.slice(0, namebuf.l);
  2332. crcs[fcnt] = CRC32.buf(fi.content, 0);
  2333. var outbuf = fi.content;
  2334. if(method == 8) outbuf = _deflateRawSync(outbuf);
  2335. /* local file header */
  2336. o = new_buf(30);
  2337. o.write_shift(4, 0x04034b50);
  2338. o.write_shift(2, 20);
  2339. o.write_shift(2, flags);
  2340. o.write_shift(2, method);
  2341. /* TODO: last mod file time/date */
  2342. if(fi.mt) write_dos_date(o, fi.mt);
  2343. else o.write_shift(4, 0);
  2344. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  2345. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  2346. o.write_shift(4, (flags & 8) ? 0 : fi.content.length);
  2347. o.write_shift(2, namebuf.length);
  2348. o.write_shift(2, 0);
  2349. start_cd += o.length;
  2350. out.push(o);
  2351. start_cd += namebuf.length;
  2352. out.push(namebuf);
  2353. /* TODO: encryption header ? */
  2354. start_cd += outbuf.length;
  2355. out.push(outbuf);
  2356. /* data descriptor */
  2357. if(flags & 8) {
  2358. o = new_buf(12);
  2359. o.write_shift(-4, crcs[fcnt]);
  2360. o.write_shift(4, outbuf.length);
  2361. o.write_shift(4, fi.content.length);
  2362. start_cd += o.l;
  2363. out.push(o);
  2364. }
  2365. /* central directory */
  2366. o = new_buf(46);
  2367. o.write_shift(4, 0x02014b50);
  2368. o.write_shift(2, 0);
  2369. o.write_shift(2, 20);
  2370. o.write_shift(2, flags);
  2371. o.write_shift(2, method);
  2372. o.write_shift(4, 0); /* TODO: last mod file time/date */
  2373. o.write_shift(-4, crcs[fcnt]);
  2374. o.write_shift(4, outbuf.length);
  2375. o.write_shift(4, fi.content.length);
  2376. o.write_shift(2, namebuf.length);
  2377. o.write_shift(2, 0);
  2378. o.write_shift(2, 0);
  2379. o.write_shift(2, 0);
  2380. o.write_shift(2, 0);
  2381. o.write_shift(4, 0);
  2382. o.write_shift(4, start);
  2383. sz_cd += o.l;
  2384. cdirs.push(o);
  2385. sz_cd += namebuf.length;
  2386. cdirs.push(namebuf);
  2387. ++fcnt;
  2388. }
  2389. /* end of central directory */
  2390. o = new_buf(22);
  2391. o.write_shift(4, 0x06054b50);
  2392. o.write_shift(2, 0);
  2393. o.write_shift(2, 0);
  2394. o.write_shift(2, fcnt);
  2395. o.write_shift(2, fcnt);
  2396. o.write_shift(4, sz_cd);
  2397. o.write_shift(4, start_cd);
  2398. o.write_shift(2, 0);
  2399. return bconcat(([bconcat((out)), bconcat(cdirs), o]));
  2400. }
  2401. function cfb_new(opts) {
  2402. var o = ({});
  2403. init_cfb(o, opts);
  2404. return o;
  2405. }
  2406. function cfb_add(cfb, name, content, opts) {
  2407. var unsafe = opts && opts.unsafe;
  2408. if(!unsafe) init_cfb(cfb);
  2409. var file = !unsafe && CFB.find(cfb, name);
  2410. if(!file) {
  2411. var fpath = cfb.FullPaths[0];
  2412. if(name.slice(0, fpath.length) == fpath) fpath = name;
  2413. else {
  2414. if(fpath.slice(-1) != "/") fpath += "/";
  2415. fpath = (fpath + name).replace("//","/");
  2416. }
  2417. file = ({name: filename(name), type: 2});
  2418. cfb.FileIndex.push(file);
  2419. cfb.FullPaths.push(fpath);
  2420. if(!unsafe) CFB.utils.cfb_gc(cfb);
  2421. }
  2422. file.content = (content);
  2423. file.size = content ? content.length : 0;
  2424. if(opts) {
  2425. if(opts.CLSID) file.clsid = opts.CLSID;
  2426. if(opts.mt) file.mt = opts.mt;
  2427. if(opts.ct) file.ct = opts.ct;
  2428. }
  2429. return file;
  2430. }
  2431. function cfb_del(cfb, name) {
  2432. init_cfb(cfb);
  2433. var file = CFB.find(cfb, name);
  2434. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  2435. cfb.FileIndex.splice(j, 1);
  2436. cfb.FullPaths.splice(j, 1);
  2437. return true;
  2438. }
  2439. return false;
  2440. }
  2441. function cfb_mov(cfb, old_name, new_name) {
  2442. init_cfb(cfb);
  2443. var file = CFB.find(cfb, old_name);
  2444. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  2445. cfb.FileIndex[j].name = filename(new_name);
  2446. cfb.FullPaths[j] = new_name;
  2447. return true;
  2448. }
  2449. return false;
  2450. }
  2451. function cfb_gc(cfb) { rebuild_cfb(cfb, true); }
  2452. exports.find = find;
  2453. exports.read = read;
  2454. exports.parse = parse;
  2455. exports.write = write;
  2456. exports.writeFile = write_file;
  2457. exports.utils = {
  2458. cfb_new: cfb_new,
  2459. cfb_add: cfb_add,
  2460. cfb_del: cfb_del,
  2461. cfb_mov: cfb_mov,
  2462. cfb_gc: cfb_gc,
  2463. ReadShift: ReadShift,
  2464. CheckField: CheckField,
  2465. prep_blob: prep_blob,
  2466. bconcat: bconcat,
  2467. use_zlib: use_zlib,
  2468. _deflateRaw: _deflate,
  2469. _inflateRaw: _inflate,
  2470. consts: consts
  2471. };
  2472. return exports;
  2473. })();
  2474. if(typeof require !== 'undefined' && typeof module !== 'undefined' && typeof DO_NOT_EXPORT_CFB === 'undefined') { module.exports = CFB; }
  2475. var _fs;
  2476. if(typeof require !== 'undefined') try { _fs = require('fs'); } catch(e) {}
  2477. /* normalize data for blob ctor */
  2478. function blobify(data) {
  2479. if(typeof data === "string") return s2ab(data);
  2480. if(Array.isArray(data)) return a2u(data);
  2481. return data;
  2482. }
  2483. /* write or download file */
  2484. function write_dl(fname, payload, enc) {
  2485. /*global IE_SaveFile, Blob, navigator, saveAs, document, File, chrome */
  2486. if(typeof _fs !== 'undefined' && _fs.writeFileSync) return enc ? _fs.writeFileSync(fname, payload, enc) : _fs.writeFileSync(fname, payload);
  2487. var data = (enc == "utf8") ? utf8write(payload) : payload;
  2488. if(typeof IE_SaveFile !== 'undefined') return IE_SaveFile(data, fname);
  2489. if(typeof Blob !== 'undefined') {
  2490. var blob = new Blob([blobify(data)], {type:"application/octet-stream"});
  2491. if(typeof navigator !== 'undefined' && navigator.msSaveBlob) return navigator.msSaveBlob(blob, fname);
  2492. if(typeof saveAs !== 'undefined') return saveAs(blob, fname);
  2493. if(typeof URL !== 'undefined' && typeof document !== 'undefined' && document.createElement && URL.createObjectURL) {
  2494. var url = URL.createObjectURL(blob);
  2495. if(typeof chrome === 'object' && typeof (chrome.downloads||{}).download == "function") {
  2496. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  2497. return chrome.downloads.download({ url: url, filename: fname, saveAs: true});
  2498. }
  2499. var a = document.createElement("a");
  2500. if(a.download != null) {
  2501. a.download = fname; a.href = url; document.body.appendChild(a); a.click();
  2502. document.body.removeChild(a);
  2503. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  2504. return url;
  2505. }
  2506. }
  2507. }
  2508. // $FlowIgnore
  2509. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  2510. // $FlowIgnore
  2511. var out = File(fname); out.open("w"); out.encoding = "binary";
  2512. if(Array.isArray(payload)) payload = a2s(payload);
  2513. out.write(payload); out.close(); return payload;
  2514. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  2515. throw new Error("cannot save file " + fname);
  2516. }
  2517. /* read binary data from file */
  2518. function read_binary(path) {
  2519. if(typeof _fs !== 'undefined') return _fs.readFileSync(path);
  2520. // $FlowIgnore
  2521. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  2522. // $FlowIgnore
  2523. var infile = File(path); infile.open("r"); infile.encoding = "binary";
  2524. var data = infile.read(); infile.close();
  2525. return data;
  2526. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  2527. throw new Error("Cannot access file " + path);
  2528. }
  2529. function keys(o) {
  2530. var ks = Object.keys(o), o2 = [];
  2531. for(var i = 0; i < ks.length; ++i) if(Object.prototype.hasOwnProperty.call(o, ks[i])) o2.push(ks[i]);
  2532. return o2;
  2533. }
  2534. function evert_key(obj, key) {
  2535. var o = ([]), K = keys(obj);
  2536. for(var i = 0; i !== K.length; ++i) if(o[obj[K[i]][key]] == null) o[obj[K[i]][key]] = K[i];
  2537. return o;
  2538. }
  2539. function evert(obj) {
  2540. var o = ([]), K = keys(obj);
  2541. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
  2542. return o;
  2543. }
  2544. function evert_num(obj) {
  2545. var o = ([]), K = keys(obj);
  2546. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
  2547. return o;
  2548. }
  2549. function evert_arr(obj) {
  2550. var o = ([]), K = keys(obj);
  2551. for(var i = 0; i !== K.length; ++i) {
  2552. if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
  2553. o[obj[K[i]]].push(K[i]);
  2554. }
  2555. return o;
  2556. }
  2557. var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
  2558. function datenum(v, date1904) {
  2559. var epoch = v.getTime();
  2560. if(date1904) epoch -= 1462*24*60*60*1000;
  2561. var dnthresh = basedate.getTime() + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  2562. return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
  2563. }
  2564. var refdate = new Date();
  2565. var dnthresh = basedate.getTime() + (refdate.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  2566. var refoffset = refdate.getTimezoneOffset();
  2567. function numdate(v) {
  2568. var out = new Date();
  2569. out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  2570. if (out.getTimezoneOffset() !== refoffset) {
  2571. out.setTime(out.getTime() + (out.getTimezoneOffset() - refoffset) * 60000);
  2572. }
  2573. return out;
  2574. }
  2575. /* ISO 8601 Duration */
  2576. function parse_isodur(s) {
  2577. var sec = 0, mt = 0, time = false;
  2578. var m = s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
  2579. if(!m) throw new Error("|" + s + "| is not an ISO8601 Duration");
  2580. for(var i = 1; i != m.length; ++i) {
  2581. if(!m[i]) continue;
  2582. mt = 1;
  2583. if(i > 3) time = true;
  2584. switch(m[i].slice(m[i].length-1)) {
  2585. case 'Y':
  2586. throw new Error("Unsupported ISO Duration Field: " + m[i].slice(m[i].length-1));
  2587. case 'D': mt *= 24;
  2588. /* falls through */
  2589. case 'H': mt *= 60;
  2590. /* falls through */
  2591. case 'M':
  2592. if(!time) throw new Error("Unsupported ISO Duration Field: M");
  2593. else mt *= 60;
  2594. /* falls through */
  2595. case 'S': break;
  2596. }
  2597. sec += mt * parseInt(m[i], 10);
  2598. }
  2599. return sec;
  2600. }
  2601. var good_pd_date = new Date('2017-02-19T19:06:09.000Z');
  2602. if(isNaN(good_pd_date.getFullYear())) good_pd_date = new Date('2/19/17');
  2603. var good_pd = good_pd_date.getFullYear() == 2017;
  2604. /* parses a date as a local date */
  2605. function parseDate(str, fixdate) {
  2606. var d = new Date(str);
  2607. if(good_pd) {
  2608. if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
  2609. else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
  2610. return d;
  2611. }
  2612. if(str instanceof Date) return str;
  2613. if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
  2614. var s = d.getFullYear();
  2615. if(str.indexOf("" + s) > -1) return d;
  2616. d.setFullYear(d.getFullYear() + 100); return d;
  2617. }
  2618. var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
  2619. var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
  2620. if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
  2621. return out;
  2622. }
  2623. function cc2str(arr) {
  2624. var o = "";
  2625. for(var i = 0; i != arr.length; ++i) o += String.fromCharCode(arr[i]);
  2626. return o;
  2627. }
  2628. function dup(o) {
  2629. if(typeof JSON != 'undefined' && !Array.isArray(o)) return JSON.parse(JSON.stringify(o));
  2630. if(typeof o != 'object' || o == null) return o;
  2631. if(o instanceof Date) return new Date(o.getTime());
  2632. var out = {};
  2633. for(var k in o) if(Object.prototype.hasOwnProperty.call(o, k)) out[k] = dup(o[k]);
  2634. return out;
  2635. }
  2636. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  2637. /* TODO: stress test */
  2638. function fuzzynum(s) {
  2639. var v = Number(s);
  2640. if(isFinite(v)) return v;
  2641. if(!isNaN(v)) return NaN;
  2642. if(!/\d/.test(s)) return v;
  2643. var wt = 1;
  2644. var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
  2645. if(!isNaN(v = Number(ss))) return v / wt;
  2646. ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
  2647. if(!isNaN(v = Number(ss))) return v / wt;
  2648. return v;
  2649. }
  2650. function fuzzydate(s) {
  2651. var o = new Date(s), n = new Date(NaN);
  2652. var y = o.getYear(), m = o.getMonth(), d = o.getDate();
  2653. if(isNaN(d)) return n;
  2654. if(y < 0 || y > 8099) return n;
  2655. if((m > 0 || d > 1) && y != 101) return o;
  2656. if(s.toLowerCase().match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) return o;
  2657. if(s.match(/[^-0-9:,\/\\]/)) return n;
  2658. return o;
  2659. }
  2660. var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  2661. function split_regex(str, re, def) {
  2662. if(safe_split_regex || typeof re == "string") return str.split(re);
  2663. var p = str.split(re), o = [p[0]];
  2664. for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
  2665. return o;
  2666. }
  2667. function getdatastr(data) {
  2668. if(!data) return null;
  2669. if(data.data) return debom(data.data);
  2670. if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
  2671. if(data.asBinary) return debom(data.asBinary());
  2672. if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
  2673. if(data.content && data.type) return debom(cc2str(data.content));
  2674. return null;
  2675. }
  2676. function getdatabin(data) {
  2677. if(!data) return null;
  2678. if(data.data) return char_codes(data.data);
  2679. if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  2680. if(data._data && data._data.getContent) {
  2681. var o = data._data.getContent();
  2682. if(typeof o == "string") return char_codes(o);
  2683. return Array.prototype.slice.call(o);
  2684. }
  2685. if(data.content && data.type) return data.content;
  2686. return null;
  2687. }
  2688. function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }
  2689. /* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
  2690. /* OASIS does not comment on filename case sensitivity */
  2691. function safegetzipfile(zip, file) {
  2692. var k = zip.FullPaths || keys(zip.files);
  2693. var f = file.toLowerCase().replace(/[\/]/g, '\\'), g = f.replace(/\\/g,'\/');
  2694. for(var i=0; i<k.length; ++i) {
  2695. var n = k[i].replace(/^Root Entry[\/]/,"").toLowerCase();
  2696. if(f == n || g == n) return zip.files ? zip.files[k[i]] : zip.FileIndex[i];
  2697. }
  2698. return null;
  2699. }
  2700. function getzipfile(zip, file) {
  2701. var o = safegetzipfile(zip, file);
  2702. if(o == null) throw new Error("Cannot find file " + file + " in zip");
  2703. return o;
  2704. }
  2705. function getzipdata(zip, file, safe) {
  2706. if(!safe) return getdata(getzipfile(zip, file));
  2707. if(!file) return null;
  2708. try { return getzipdata(zip, file); } catch(e) { return null; }
  2709. }
  2710. function getzipstr(zip, file, safe) {
  2711. if(!safe) return getdatastr(getzipfile(zip, file));
  2712. if(!file) return null;
  2713. try { return getzipstr(zip, file); } catch(e) { return null; }
  2714. }
  2715. function zipentries(zip) {
  2716. var k = zip.FullPaths || keys(zip.files), o = [];
  2717. for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i].replace(/^Root Entry[\/]/, ""));
  2718. return o.sort();
  2719. }
  2720. function zip_add_file(zip, path, content) {
  2721. if(zip.FullPaths) CFB.utils.cfb_add(zip, path, typeof content == "string" ? (has_buf ? Buffer_from(content) : s2a(utf8write(content))) : content);
  2722. else zip.file(path, content);
  2723. }
  2724. var jszip;
  2725. function zip_new() {
  2726. return CFB.utils.cfb_new();
  2727. }
  2728. function zip_read(d, o) {
  2729. var zip;
  2730. switch(o.type) {
  2731. case "base64": zip = CFB.read(d, { type: "base64" }); break;
  2732. case "binary": zip = CFB.read(d, { type: "binary" }); break;
  2733. case "buffer": case "array": zip = CFB.read(d, { type: "buffer" }); break;
  2734. default: throw new Error("Unrecognized type " + o.type);
  2735. }
  2736. return zip;
  2737. }
  2738. function resolve_path(path, base) {
  2739. if(path.charAt(0) == "/") return path.slice(1);
  2740. var result = base.split('/');
  2741. if(base.slice(-1) != "/") result.pop(); // folder path
  2742. var target = path.split('/');
  2743. while (target.length !== 0) {
  2744. var step = target.shift();
  2745. if (step === '..') result.pop();
  2746. else if (step !== '.') result.push(step);
  2747. }
  2748. return result.join('/');
  2749. }
  2750. var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
  2751. var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
  2752. var tagregex=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s*[\/\?]?>/mg;
  2753. if(!(XML_HEADER.match(tagregex))) tagregex = /<[^>]*>/g;
  2754. var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
  2755. function parsexmltag(tag, skip_root, skip_LC) {
  2756. var z = ({});
  2757. var eq = 0, c = 0;
  2758. for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
  2759. if(!skip_root) z[0] = tag.slice(0, eq);
  2760. if(eq === tag.length) return z;
  2761. var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
  2762. if(m) for(i = 0; i != m.length; ++i) {
  2763. cc = m[i];
  2764. for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
  2765. q = cc.slice(0,c).trim();
  2766. while(cc.charCodeAt(c+1) == 32) ++c;
  2767. quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
  2768. v = cc.slice(c+1+quot, cc.length-quot);
  2769. for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
  2770. if(j===q.length) {
  2771. if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
  2772. z[q] = v;
  2773. if(!skip_LC) z[q.toLowerCase()] = v;
  2774. }
  2775. else {
  2776. var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
  2777. if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
  2778. z[k] = v;
  2779. if(!skip_LC) z[k.toLowerCase()] = v;
  2780. }
  2781. }
  2782. return z;
  2783. }
  2784. function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
  2785. var encodings = {
  2786. '&quot;': '"',
  2787. '&apos;': "'",
  2788. '&gt;': '>',
  2789. '&lt;': '<',
  2790. '&amp;': '&'
  2791. };
  2792. var rencoding = evert(encodings);
  2793. //var rencstr = "&<>'\"".split("");
  2794. // TODO: CP remap (need to read file version to determine OS)
  2795. var unescapexml = (function() {
  2796. /* 22.4.2.4 bstr (Basic String) */
  2797. var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  2798. return function unescapexml(text) {
  2799. var s = text + '', i = s.indexOf("<![CDATA[");
  2800. if(i == -1) return s.replace(encregex, function($$, $1) { return encodings[$$]||String.fromCharCode(parseInt($1,$$.indexOf("x")>-1?16:10))||$$; }).replace(coderegex,function(m,c) {return String.fromCharCode(parseInt(c,16));});
  2801. var j = s.indexOf("]]>");
  2802. return unescapexml(s.slice(0, i)) + s.slice(i+9,j) + unescapexml(s.slice(j+3));
  2803. };
  2804. })();
  2805. var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
  2806. function escapexml(text){
  2807. var s = text + '';
  2808. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
  2809. }
  2810. function escapexmltag(text){ return escapexml(text).replace(/ /g,"_x0020_"); }
  2811. var htmlcharegex = /[\u0000-\u001f]/g;
  2812. function escapehtml(text){
  2813. var s = text + '';
  2814. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(/\n/g, "<br/>").replace(htmlcharegex,function(s) { return "&#x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + ";"; });
  2815. }
  2816. function escapexlml(text){
  2817. var s = text + '';
  2818. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
  2819. }
  2820. /* TODO: handle codepages */
  2821. var xlml_fixstr = (function() {
  2822. var entregex = /&#(\d+);/g;
  2823. function entrepl($$,$1) { return String.fromCharCode(parseInt($1,10)); }
  2824. return function xlml_fixstr(str) { return str.replace(entregex,entrepl); };
  2825. })();
  2826. var xlml_unfixstr = (function() {
  2827. return function xlml_unfixstr(str) { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); };
  2828. })();
  2829. function parsexmlbool(value) {
  2830. switch(value) {
  2831. case 1: case true: case '1': case 'true': case 'TRUE': return true;
  2832. /* case '0': case 'false': case 'FALSE':*/
  2833. default: return false;
  2834. }
  2835. }
  2836. var utf8read = function utf8reada(orig) {
  2837. var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
  2838. while (i < orig.length) {
  2839. c = orig.charCodeAt(i++);
  2840. if (c < 128) { out += String.fromCharCode(c); continue; }
  2841. d = orig.charCodeAt(i++);
  2842. if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
  2843. e = orig.charCodeAt(i++);
  2844. if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
  2845. f = orig.charCodeAt(i++);
  2846. w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
  2847. out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
  2848. out += String.fromCharCode(0xDC00 + (w&1023));
  2849. }
  2850. return out;
  2851. };
  2852. var utf8write = function(orig) {
  2853. var out = [], i = 0, c = 0, d = 0;
  2854. while(i < orig.length) {
  2855. c = orig.charCodeAt(i++);
  2856. switch(true) {
  2857. case c < 128: out.push(String.fromCharCode(c)); break;
  2858. case c < 2048:
  2859. out.push(String.fromCharCode(192 + (c >> 6)));
  2860. out.push(String.fromCharCode(128 + (c & 63)));
  2861. break;
  2862. case c >= 55296 && c < 57344:
  2863. c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
  2864. out.push(String.fromCharCode(240 + ((d >>18) & 7)));
  2865. out.push(String.fromCharCode(144 + ((d >>12) & 63)));
  2866. out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
  2867. out.push(String.fromCharCode(128 + (d & 63)));
  2868. break;
  2869. default:
  2870. out.push(String.fromCharCode(224 + (c >> 12)));
  2871. out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
  2872. out.push(String.fromCharCode(128 + (c & 63)));
  2873. }
  2874. }
  2875. return out.join("");
  2876. };
  2877. if(has_buf) {
  2878. var utf8readb = function utf8readb(data) {
  2879. var out = Buffer.alloc(2*data.length), w, i, j = 1, k = 0, ww=0, c;
  2880. for(i = 0; i < data.length; i+=j) {
  2881. j = 1;
  2882. if((c=data.charCodeAt(i)) < 128) w = c;
  2883. else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
  2884. else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
  2885. else { j = 4;
  2886. w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
  2887. w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
  2888. }
  2889. if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
  2890. out[k++] = w%256; out[k++] = w>>>8;
  2891. }
  2892. return out.slice(0,k).toString('ucs2');
  2893. };
  2894. var corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
  2895. if(utf8read(corpus) == utf8readb(corpus)) utf8read = utf8readb;
  2896. var utf8readc = function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); };
  2897. if(utf8read(corpus) == utf8readc(corpus)) utf8read = utf8readc;
  2898. utf8write = function(data) { return Buffer_from(data, 'utf8').toString("binary"); };
  2899. }
  2900. // matches <foo>...</foo> extracts content
  2901. var matchtag = (function() {
  2902. var mtcache = ({});
  2903. return function matchtag(f,g) {
  2904. var t = f+"|"+(g||"");
  2905. if(mtcache[t]) return mtcache[t];
  2906. return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||""))));
  2907. };
  2908. })();
  2909. var htmldecode = (function() {
  2910. var entities = [
  2911. ['nbsp', ' '], ['middot', '·'],
  2912. ['quot', '"'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['amp', '&']
  2913. ].map(function(x) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
  2914. return function htmldecode(str) {
  2915. var o = str
  2916. // Remove new lines and spaces from start of content
  2917. .replace(/^[\t\n\r ]+/, "")
  2918. // Remove new lines and spaces from end of content
  2919. .replace(/[\t\n\r ]+$/,"")
  2920. // Added line which removes any white space characters after and before html tags
  2921. .replace(/>\s+/g,">").replace(/\s+</g,"<")
  2922. // Replace remaining new lines and spaces with space
  2923. .replace(/[\t\n\r ]+/g, " ")
  2924. // Replace <br> tags with new lines
  2925. .replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
  2926. // Strip HTML elements
  2927. .replace(/<[^>]*>/g,"");
  2928. for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
  2929. return o;
  2930. };
  2931. })();
  2932. var vtregex = (function(){ var vt_cache = {};
  2933. return function vt_regex(bt) {
  2934. if(vt_cache[bt] !== undefined) return vt_cache[bt];
  2935. return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
  2936. };})();
  2937. var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
  2938. function parseVector(data, opts) {
  2939. var h = parsexmltag(data);
  2940. var matches = data.match(vtregex(h.baseType))||[];
  2941. var res = [];
  2942. if(matches.length != h.size) {
  2943. if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
  2944. return res;
  2945. }
  2946. matches.forEach(function(x) {
  2947. var v = x.replace(vtvregex,"").match(vtmregex);
  2948. if(v) res.push({v:utf8read(v[2]), t:v[1]});
  2949. });
  2950. return res;
  2951. }
  2952. var wtregex = /(^\s|\s$|\n)/;
  2953. function writetag(f,g) { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }
  2954. function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
  2955. function writextag(f,g,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
  2956. function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
  2957. function write_vt(s, xlsx) {
  2958. switch(typeof s) {
  2959. case 'string':
  2960. var o = writextag('vt:lpwstr', escapexml(s));
  2961. if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
  2962. return o;
  2963. case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
  2964. case 'boolean': return writextag('vt:bool',s?'true':'false');
  2965. }
  2966. if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
  2967. throw new Error("Unable to serialize " + s);
  2968. }
  2969. var XMLNS = ({
  2970. 'dc': 'http://purl.org/dc/elements/1.1/',
  2971. 'dcterms': 'http://purl.org/dc/terms/',
  2972. 'dcmitype': 'http://purl.org/dc/dcmitype/',
  2973. 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
  2974. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  2975. 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
  2976. 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
  2977. 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
  2978. 'xsd': 'http://www.w3.org/2001/XMLSchema'
  2979. });
  2980. XMLNS.main = [
  2981. 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  2982. 'http://purl.oclc.org/ooxml/spreadsheetml/main',
  2983. 'http://schemas.microsoft.com/office/excel/2006/main',
  2984. 'http://schemas.microsoft.com/office/excel/2006/2'
  2985. ];
  2986. var XLMLNS = ({
  2987. 'o': 'urn:schemas-microsoft-com:office:office',
  2988. 'x': 'urn:schemas-microsoft-com:office:excel',
  2989. 'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
  2990. 'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
  2991. 'mv': 'http://macVmlSchemaUri',
  2992. 'v': 'urn:schemas-microsoft-com:vml',
  2993. 'html': 'http://www.w3.org/TR/REC-html40'
  2994. });
  2995. function read_double_le(b, idx) {
  2996. var s = 1 - 2 * (b[idx + 7] >>> 7);
  2997. var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
  2998. var m = (b[idx+6]&0x0f);
  2999. for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
  3000. if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
  3001. if(e == 0) e = -1022;
  3002. else { e -= 1023; m += Math.pow(2,52); }
  3003. return s * Math.pow(2, e - 52) * m;
  3004. }
  3005. function write_double_le(b, v, idx) {
  3006. var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
  3007. var av = bs ? (-v) : v;
  3008. if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
  3009. else if(av == 0) e = m = 0;
  3010. else {
  3011. e = Math.floor(Math.log(av) / Math.LN2);
  3012. m = av * Math.pow(2, 52 - e);
  3013. if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
  3014. else { m -= Math.pow(2,52); e+=1023; }
  3015. }
  3016. for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
  3017. b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
  3018. b[idx + 7] = (e >> 4) | bs;
  3019. }
  3020. var __toBuffer = function(bufs) { var x=[],w=10240; for(var i=0;i<bufs[0].length;++i) if(bufs[0][i]) for(var j=0,L=bufs[0][i].length;j<L;j+=w) x.push.apply(x, bufs[0][i].slice(j,j+w)); return x; };
  3021. var ___toBuffer = __toBuffer;
  3022. var __utf16le = function(b,s,e) { var ss=[]; for(var i=s; i<e; i+=2) ss.push(String.fromCharCode(__readUInt16LE(b,i))); return ss.join("").replace(chr0,''); };
  3023. var ___utf16le = __utf16le;
  3024. var __hexlify = function(b,s,l) { var ss=[]; for(var i=s; i<s+l; ++i) ss.push(("0" + b[i].toString(16)).slice(-2)); return ss.join(""); };
  3025. var ___hexlify = __hexlify;
  3026. var __utf8 = function(b,s,e) { var ss=[]; for(var i=s; i<e; i++) ss.push(String.fromCharCode(__readUInt8(b,i))); return ss.join(""); };
  3027. var ___utf8 = __utf8;
  3028. var __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3029. var ___lpstr = __lpstr;
  3030. var __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3031. var ___cpstr = __cpstr;
  3032. var __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3033. var ___lpwstr = __lpwstr;
  3034. var __lpp4, ___lpp4;
  3035. __lpp4 = ___lpp4 = function lpp4_(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
  3036. var __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
  3037. var ___8lpp4 = __8lpp4;
  3038. var __double, ___double;
  3039. __double = ___double = function(b, idx) { return read_double_le(b, idx);};
  3040. var is_buf = function is_buf_a(a) { return Array.isArray(a); };
  3041. if(has_buf) {
  3042. __utf16le = function(b,s,e) { if(!Buffer.isBuffer(b)) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; };
  3043. __hexlify = function(b,s,l) { return Buffer.isBuffer(b) ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); };
  3044. __lpstr = function lpstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
  3045. __cpstr = function cpstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___cpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
  3046. __lpwstr = function lpwstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpwstr(b, i); var len = 2*b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len-1);};
  3047. __lpp4 = function lpp4_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len);};
  3048. __8lpp4 = function lpp4_8b(b, i) { if(!Buffer.isBuffer(b)) return ___8lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf8',i+4,i+4+len);};
  3049. __utf8 = function utf8_b(b, s, e) { return (Buffer.isBuffer(b)) ? b.toString('utf8',s,e) : ___utf8(b,s,e); };
  3050. __toBuffer = function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0]) : ___toBuffer(bufs);};
  3051. bconcat = function(bufs) { return Buffer.isBuffer(bufs[0]) ? Buffer.concat(bufs) : [].concat.apply([], bufs); };
  3052. __double = function double_(b, i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
  3053. is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a); };
  3054. }
  3055. /* from js-xls */
  3056. if(typeof cptable !== 'undefined') {
  3057. __utf16le = function(b,s,e) { return cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
  3058. __utf8 = function(b,s,e) { return cptable.utils.decode(65001, b.slice(s,e)); };
  3059. __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(current_ansi, b.slice(i+4, i+4+len-1)) : "";};
  3060. __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(current_codepage, b.slice(i+4, i+4+len-1)) : "";};
  3061. __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len-1)) : "";};
  3062. __lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
  3063. __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
  3064. }
  3065. var __readUInt8 = function(b, idx) { return b[idx]; };
  3066. var __readUInt16LE = function(b, idx) { return (b[idx+1]*(1<<8))+b[idx]; };
  3067. var __readInt16LE = function(b, idx) { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
  3068. var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
  3069. var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
  3070. var __readInt32BE = function(b, idx) { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };
  3071. function ReadShift(size, t) {
  3072. var o="", oI, oR, oo=[], w, vv, i, loc;
  3073. switch(t) {
  3074. case 'dbcs':
  3075. loc = this.l;
  3076. if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
  3077. else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
  3078. size *= 2;
  3079. break;
  3080. case 'utf8': o = __utf8(this, this.l, this.l + size); break;
  3081. case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;
  3082. case 'wstr':
  3083. if(typeof cptable !== 'undefined') o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
  3084. else return ReadShift.call(this, size, 'dbcs');
  3085. size = 2 * size; break;
  3086. /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
  3087. case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3088. case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3089. /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
  3090. case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
  3091. /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
  3092. case 'lpp4': size = 4 + __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
  3093. /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
  3094. case '8lpp4': size = 4 + __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;
  3095. case 'cstr': size = 0; o = "";
  3096. while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
  3097. o = oo.join(""); break;
  3098. case '_wstr': size = 0; o = "";
  3099. while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
  3100. size+=2; o = oo.join(""); break;
  3101. /* sbcs and dbcs support continue records in the SST way TODO codepages */
  3102. case 'dbcs-cont': o = ""; loc = this.l;
  3103. for(i = 0; i < size; ++i) {
  3104. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3105. w = __readUInt8(this, loc);
  3106. this.l = loc + 1;
  3107. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3108. return oo.join("") + vv;
  3109. }
  3110. oo.push(_getchar(__readUInt16LE(this, loc)));
  3111. loc+=2;
  3112. } o = oo.join(""); size *= 2; break;
  3113. case 'cpstr':
  3114. if(typeof cptable !== 'undefined') {
  3115. o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
  3116. break;
  3117. }
  3118. /* falls through */
  3119. case 'sbcs-cont': o = ""; loc = this.l;
  3120. for(i = 0; i != size; ++i) {
  3121. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3122. w = __readUInt8(this, loc);
  3123. this.l = loc + 1;
  3124. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3125. return oo.join("") + vv;
  3126. }
  3127. oo.push(_getchar(__readUInt8(this, loc)));
  3128. loc+=1;
  3129. } o = oo.join(""); break;
  3130. default:
  3131. switch(size) {
  3132. case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
  3133. case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
  3134. case 4: case -4:
  3135. if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
  3136. else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
  3137. case 8: case -8:
  3138. if(t === 'f') {
  3139. if(size == 8) oR = __double(this, this.l);
  3140. else oR = __double([this[this.l+7],this[this.l+6],this[this.l+5],this[this.l+4],this[this.l+3],this[this.l+2],this[this.l+1],this[this.l+0]], 0);
  3141. this.l += 8; return oR;
  3142. } else size = 8;
  3143. /* falls through */
  3144. case 16: o = __hexlify(this, this.l, size); break;
  3145. }}
  3146. this.l+=size; return o;
  3147. }
  3148. var __writeUInt32LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); b[idx+2] = ((val >>> 16) & 0xFF); b[idx+3] = ((val >>> 24) & 0xFF); };
  3149. var __writeInt32LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >> 8) & 0xFF); b[idx+2] = ((val >> 16) & 0xFF); b[idx+3] = ((val >> 24) & 0xFF); };
  3150. var __writeUInt16LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };
  3151. function WriteShift(t, val, f) {
  3152. var size = 0, i = 0;
  3153. if(f === 'dbcs') {
  3154. for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
  3155. size = 2 * val.length;
  3156. } else if(f === 'sbcs') {
  3157. if(typeof cptable !== 'undefined' && current_ansi == 874) {
  3158. /* TODO: use tables directly, don't encode */
  3159. for(i = 0; i != val.length; ++i) {
  3160. var cppayload = cptable.utils.encode(current_ansi, val.charAt(i));
  3161. this[this.l + i] = cppayload[0];
  3162. }
  3163. } else {
  3164. val = val.replace(/[^\x00-\x7F]/g, "_");
  3165. for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
  3166. }
  3167. size = val.length;
  3168. } else if(f === 'hex') {
  3169. for(; i < t; ++i) {
  3170. this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
  3171. } return this;
  3172. } else if(f === 'utf16le') {
  3173. var end = Math.min(this.l + t, this.length);
  3174. for(i = 0; i < Math.min(val.length, t); ++i) {
  3175. var cc = val.charCodeAt(i);
  3176. this[this.l++] = (cc & 0xff);
  3177. this[this.l++] = (cc >> 8);
  3178. }
  3179. while(this.l < end) this[this.l++] = 0;
  3180. return this;
  3181. } else switch(t) {
  3182. case 1: size = 1; this[this.l] = val&0xFF; break;
  3183. case 2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
  3184. case 3: size = 3; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; val >>>= 8; this[this.l+2] = val&0xFF; break;
  3185. case 4: size = 4; __writeUInt32LE(this, val, this.l); break;
  3186. case 8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
  3187. /* falls through */
  3188. case 16: break;
  3189. case -4: size = 4; __writeInt32LE(this, val, this.l); break;
  3190. }
  3191. this.l += size; return this;
  3192. }
  3193. function CheckField(hexstr, fld) {
  3194. var m = __hexlify(this,this.l,hexstr.length>>1);
  3195. if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
  3196. this.l += hexstr.length>>1;
  3197. }
  3198. function prep_blob(blob, pos) {
  3199. blob.l = pos;
  3200. blob.read_shift = ReadShift;
  3201. blob.chk = CheckField;
  3202. blob.write_shift = WriteShift;
  3203. }
  3204. function parsenoop(blob, length) { blob.l += length; }
  3205. function new_buf(sz) {
  3206. var o = new_raw_buf(sz);
  3207. prep_blob(o, 0);
  3208. return o;
  3209. }
  3210. /* [MS-XLSB] 2.1.4 Record */
  3211. function recordhopper(data, cb, opts) {
  3212. if(!data) return;
  3213. var tmpbyte, cntbyte, length;
  3214. prep_blob(data, data.l || 0);
  3215. var L = data.length, RT = 0, tgt = 0;
  3216. while(data.l < L) {
  3217. RT = data.read_shift(1);
  3218. if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
  3219. var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
  3220. tmpbyte = data.read_shift(1);
  3221. length = tmpbyte & 0x7F;
  3222. for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
  3223. tgt = data.l + length;
  3224. var d = R.f && R.f(data, length, opts);
  3225. data.l = tgt;
  3226. if(cb(d, R.n, RT)) return;
  3227. }
  3228. }
  3229. /* control buffer usage for fixed-length buffers */
  3230. function buf_array() {
  3231. var bufs = [], blksz = has_buf ? 256 : 2048;
  3232. var newblk = function ba_newblk(sz) {
  3233. var o = (new_buf(sz));
  3234. prep_blob(o, 0);
  3235. return o;
  3236. };
  3237. var curbuf = newblk(blksz);
  3238. var endbuf = function ba_endbuf() {
  3239. if(!curbuf) return;
  3240. if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
  3241. if(curbuf.length > 0) bufs.push(curbuf);
  3242. curbuf = null;
  3243. };
  3244. var next = function ba_next(sz) {
  3245. if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
  3246. endbuf();
  3247. return (curbuf = newblk(Math.max(sz+1, blksz)));
  3248. };
  3249. var end = function ba_end() {
  3250. endbuf();
  3251. return __toBuffer([bufs]);
  3252. };
  3253. var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };
  3254. return ({ next:next, push:push, end:end, _bufs:bufs });
  3255. }
  3256. function write_record(ba, type, payload, length) {
  3257. var t = +XLSBRE[type], l;
  3258. if(isNaN(t)) return; // TODO: throw something here?
  3259. if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
  3260. l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
  3261. if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
  3262. var o = ba.next(l);
  3263. if(t <= 0x7F) o.write_shift(1, t);
  3264. else {
  3265. o.write_shift(1, (t & 0x7F) + 0x80);
  3266. o.write_shift(1, (t >> 7));
  3267. }
  3268. for(var i = 0; i != 4; ++i) {
  3269. if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
  3270. else { o.write_shift(1, length); break; }
  3271. }
  3272. if(length > 0 && is_buf(payload)) ba.push(payload);
  3273. }
  3274. /* XLS ranges enforced */
  3275. function shift_cell_xls(cell, tgt, opts) {
  3276. var out = dup(cell);
  3277. if(tgt.s) {
  3278. if(out.cRel) out.c += tgt.s.c;
  3279. if(out.rRel) out.r += tgt.s.r;
  3280. } else {
  3281. if(out.cRel) out.c += tgt.c;
  3282. if(out.rRel) out.r += tgt.r;
  3283. }
  3284. if(!opts || opts.biff < 12) {
  3285. while(out.c >= 0x100) out.c -= 0x100;
  3286. while(out.r >= 0x10000) out.r -= 0x10000;
  3287. }
  3288. return out;
  3289. }
  3290. function shift_range_xls(cell, range, opts) {
  3291. var out = dup(cell);
  3292. out.s = shift_cell_xls(out.s, range.s, opts);
  3293. out.e = shift_cell_xls(out.e, range.s, opts);
  3294. return out;
  3295. }
  3296. function encode_cell_xls(c, biff) {
  3297. if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
  3298. if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
  3299. var s = encode_cell(c);
  3300. if(!c.cRel && c.cRel != null) s = fix_col(s);
  3301. if(!c.rRel && c.rRel != null) s = fix_row(s);
  3302. return s;
  3303. }
  3304. function encode_range_xls(r, opts) {
  3305. if(r.s.r == 0 && !r.s.rRel) {
  3306. if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
  3307. return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
  3308. }
  3309. }
  3310. if(r.s.c == 0 && !r.s.cRel) {
  3311. if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
  3312. return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
  3313. }
  3314. }
  3315. return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
  3316. }
  3317. function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
  3318. function encode_row(row) { return "" + (row + 1); }
  3319. function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
  3320. function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
  3321. function decode_col(colstr) { var c = unfix_col(colstr), d = 0, i = 0; for(; i !== c.length; ++i) d = 26*d + c.charCodeAt(i) - 64; return d - 1; }
  3322. function encode_col(col) { if(col < 0) throw new Error("invalid column " + col); var s=""; for(++col; col; col=Math.floor((col-1)/26)) s = String.fromCharCode(((col-1)%26) + 65) + s; return s; }
  3323. function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
  3324. function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
  3325. function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
  3326. //function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
  3327. function decode_cell(cstr) {
  3328. var R = 0, C = 0;
  3329. for(var i = 0; i < cstr.length; ++i) {
  3330. var cc = cstr.charCodeAt(i);
  3331. if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
  3332. else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
  3333. }
  3334. return { c: C - 1, r:R - 1 };
  3335. }
  3336. //function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
  3337. function encode_cell(cell) {
  3338. var col = cell.c + 1;
  3339. var s="";
  3340. for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
  3341. return s + (cell.r + 1);
  3342. }
  3343. function decode_range(range) {
  3344. var idx = range.indexOf(":");
  3345. if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
  3346. return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
  3347. }
  3348. function encode_range(cs,ce) {
  3349. if(typeof ce === 'undefined' || typeof ce === 'number') {
  3350. return encode_range(cs.s, cs.e);
  3351. }
  3352. if(typeof cs !== 'string') cs = encode_cell((cs));
  3353. if(typeof ce !== 'string') ce = encode_cell((ce));
  3354. return cs == ce ? cs : cs + ":" + ce;
  3355. }
  3356. function safe_decode_range(range) {
  3357. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  3358. var idx = 0, i = 0, cc = 0;
  3359. var len = range.length;
  3360. for(idx = 0; i < len; ++i) {
  3361. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3362. idx = 26*idx + cc;
  3363. }
  3364. o.s.c = --idx;
  3365. for(idx = 0; i < len; ++i) {
  3366. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3367. idx = 10*idx + cc;
  3368. }
  3369. o.s.r = --idx;
  3370. if(i === len || cc != 10) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
  3371. ++i;
  3372. for(idx = 0; i != len; ++i) {
  3373. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3374. idx = 26*idx + cc;
  3375. }
  3376. o.e.c = --idx;
  3377. for(idx = 0; i != len; ++i) {
  3378. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3379. idx = 10*idx + cc;
  3380. }
  3381. o.e.r = --idx;
  3382. return o;
  3383. }
  3384. function safe_format_cell(cell, v) {
  3385. var q = (cell.t == 'd' && v instanceof Date);
  3386. if(cell.z != null) try { return (cell.w = SSF.format(cell.z, q ? datenum(v) : v)); } catch(e) { }
  3387. try { return (cell.w = SSF.format((cell.XF||{}).numFmtId||(q ? 14 : 0), q ? datenum(v) : v)); } catch(e) { return ''+v; }
  3388. }
  3389. function format_cell(cell, v, o) {
  3390. if(cell == null || cell.t == null || cell.t == 'z') return "";
  3391. if(cell.w !== undefined) return cell.w;
  3392. if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
  3393. if(cell.t == "e") return BErr[cell.v] || cell.v;
  3394. if(v == undefined) return safe_format_cell(cell, cell.v);
  3395. return safe_format_cell(cell, v);
  3396. }
  3397. function sheet_to_workbook(sheet, opts) {
  3398. var n = opts && opts.sheet ? opts.sheet : "Sheet1";
  3399. var sheets = {}; sheets[n] = sheet;
  3400. return { SheetNames: [n], Sheets: sheets };
  3401. }
  3402. function sheet_add_aoa(_ws, data, opts) {
  3403. var o = opts || {};
  3404. var dense = _ws ? Array.isArray(_ws) : o.dense;
  3405. if(DENSE != null && dense == null) dense = DENSE;
  3406. var ws = _ws || (dense ? ([]) : ({}));
  3407. var _R = 0, _C = 0;
  3408. if(ws && o.origin != null) {
  3409. if(typeof o.origin == 'number') _R = o.origin;
  3410. else {
  3411. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  3412. _R = _origin.r; _C = _origin.c;
  3413. }
  3414. if(!ws["!ref"]) ws["!ref"] = "A1:A1";
  3415. }
  3416. var range = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}});
  3417. if(ws['!ref']) {
  3418. var _range = safe_decode_range(ws['!ref']);
  3419. range.s.c = _range.s.c;
  3420. range.s.r = _range.s.r;
  3421. range.e.c = Math.max(range.e.c, _range.e.c);
  3422. range.e.r = Math.max(range.e.r, _range.e.r);
  3423. if(_R == -1) range.e.r = _R = _range.e.r + 1;
  3424. }
  3425. for(var R = 0; R != data.length; ++R) {
  3426. if(!data[R]) continue;
  3427. if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
  3428. for(var C = 0; C != data[R].length; ++C) {
  3429. if(typeof data[R][C] === 'undefined') continue;
  3430. var cell = ({v: data[R][C] });
  3431. var __R = _R + R, __C = _C + C;
  3432. if(range.s.r > __R) range.s.r = __R;
  3433. if(range.s.c > __C) range.s.c = __C;
  3434. if(range.e.r < __R) range.e.r = __R;
  3435. if(range.e.c < __C) range.e.c = __C;
  3436. if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
  3437. else {
  3438. if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
  3439. if(cell.v === null) {
  3440. if(cell.f) cell.t = 'n';
  3441. else if(o.nullError) { cell.t = 'e'; cell.v = 0; }
  3442. else if(!o.sheetStubs) continue;
  3443. else cell.t = 'z';
  3444. }
  3445. else if(typeof cell.v === 'number') cell.t = 'n';
  3446. else if(typeof cell.v === 'boolean') cell.t = 'b';
  3447. else if(cell.v instanceof Date) {
  3448. cell.z = o.dateNF || SSF._table[14];
  3449. if(o.cellDates) { cell.t = 'd'; cell.w = SSF.format(cell.z, datenum(cell.v)); }
  3450. else { cell.t = 'n'; cell.v = datenum(cell.v); cell.w = SSF.format(cell.z, cell.v); }
  3451. }
  3452. else cell.t = 's';
  3453. }
  3454. if(dense) {
  3455. if(!ws[__R]) ws[__R] = [];
  3456. if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
  3457. ws[__R][__C] = cell;
  3458. } else {
  3459. var cell_ref = encode_cell(({c:__C,r:__R}));
  3460. if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
  3461. ws[cell_ref] = cell;
  3462. }
  3463. }
  3464. }
  3465. if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
  3466. return ws;
  3467. }
  3468. function aoa_to_sheet(data, opts) { return sheet_add_aoa(null, data, opts); }
  3469. /* [MS-OLEPS] 2.2 PropertyType */
  3470. //var VT_EMPTY = 0x0000;
  3471. //var VT_NULL = 0x0001;
  3472. var VT_I2 = 0x0002;
  3473. var VT_I4 = 0x0003;
  3474. //var VT_R4 = 0x0004;
  3475. //var VT_R8 = 0x0005;
  3476. //var VT_CY = 0x0006;
  3477. //var VT_DATE = 0x0007;
  3478. //var VT_BSTR = 0x0008;
  3479. //var VT_ERROR = 0x000A;
  3480. var VT_BOOL = 0x000B;
  3481. var VT_VARIANT = 0x000C;
  3482. //var VT_DECIMAL = 0x000E;
  3483. //var VT_I1 = 0x0010;
  3484. //var VT_UI1 = 0x0011;
  3485. //var VT_UI2 = 0x0012;
  3486. var VT_UI4 = 0x0013;
  3487. //var VT_I8 = 0x0014;
  3488. //var VT_UI8 = 0x0015;
  3489. //var VT_INT = 0x0016;
  3490. //var VT_UINT = 0x0017;
  3491. var VT_LPSTR = 0x001E;
  3492. //var VT_LPWSTR = 0x001F;
  3493. var VT_FILETIME = 0x0040;
  3494. var VT_BLOB = 0x0041;
  3495. //var VT_STREAM = 0x0042;
  3496. //var VT_STORAGE = 0x0043;
  3497. //var VT_STREAMED_Object = 0x0044;
  3498. //var VT_STORED_Object = 0x0045;
  3499. //var VT_BLOB_Object = 0x0046;
  3500. var VT_CF = 0x0047;
  3501. //var VT_CLSID = 0x0048;
  3502. //var VT_VERSIONED_STREAM = 0x0049;
  3503. var VT_VECTOR = 0x1000;
  3504. //var VT_ARRAY = 0x2000;
  3505. var VT_STRING = 0x0050; // 2.3.3.1.11 VtString
  3506. var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString
  3507. var VT_CUSTOM = [VT_STRING, VT_USTR];
  3508. /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
  3509. var DocSummaryPIDDSI = {
  3510. 0x01: { n: 'CodePage', t: VT_I2 },
  3511. 0x02: { n: 'Category', t: VT_STRING },
  3512. 0x03: { n: 'PresentationFormat', t: VT_STRING },
  3513. 0x04: { n: 'ByteCount', t: VT_I4 },
  3514. 0x05: { n: 'LineCount', t: VT_I4 },
  3515. 0x06: { n: 'ParagraphCount', t: VT_I4 },
  3516. 0x07: { n: 'SlideCount', t: VT_I4 },
  3517. 0x08: { n: 'NoteCount', t: VT_I4 },
  3518. 0x09: { n: 'HiddenCount', t: VT_I4 },
  3519. 0x0a: { n: 'MultimediaClipCount', t: VT_I4 },
  3520. 0x0b: { n: 'ScaleCrop', t: VT_BOOL },
  3521. 0x0c: { n: 'HeadingPairs', t: VT_VECTOR | VT_VARIANT },
  3522. 0x0d: { n: 'TitlesOfParts', t: VT_VECTOR | VT_LPSTR },
  3523. 0x0e: { n: 'Manager', t: VT_STRING },
  3524. 0x0f: { n: 'Company', t: VT_STRING },
  3525. 0x10: { n: 'LinksUpToDate', t: VT_BOOL },
  3526. 0x11: { n: 'CharacterCount', t: VT_I4 },
  3527. 0x13: { n: 'SharedDoc', t: VT_BOOL },
  3528. 0x16: { n: 'HyperlinksChanged', t: VT_BOOL },
  3529. 0x17: { n: 'AppVersion', t: VT_I4, p: 'version' },
  3530. 0x18: { n: 'DigSig', t: VT_BLOB },
  3531. 0x1A: { n: 'ContentType', t: VT_STRING },
  3532. 0x1B: { n: 'ContentStatus', t: VT_STRING },
  3533. 0x1C: { n: 'Language', t: VT_STRING },
  3534. 0x1D: { n: 'Version', t: VT_STRING },
  3535. 0xFF: {},
  3536. /* [MS-OLEPS] 2.18 */
  3537. 0x80000000: { n: 'Locale', t: VT_UI4 },
  3538. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  3539. 0x72627262: {}
  3540. };
  3541. /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
  3542. var SummaryPIDSI = {
  3543. 0x01: { n: 'CodePage', t: VT_I2 },
  3544. 0x02: { n: 'Title', t: VT_STRING },
  3545. 0x03: { n: 'Subject', t: VT_STRING },
  3546. 0x04: { n: 'Author', t: VT_STRING },
  3547. 0x05: { n: 'Keywords', t: VT_STRING },
  3548. 0x06: { n: 'Comments', t: VT_STRING },
  3549. 0x07: { n: 'Template', t: VT_STRING },
  3550. 0x08: { n: 'LastAuthor', t: VT_STRING },
  3551. 0x09: { n: 'RevNumber', t: VT_STRING },
  3552. 0x0A: { n: 'EditTime', t: VT_FILETIME },
  3553. 0x0B: { n: 'LastPrinted', t: VT_FILETIME },
  3554. 0x0C: { n: 'CreatedDate', t: VT_FILETIME },
  3555. 0x0D: { n: 'ModifiedDate', t: VT_FILETIME },
  3556. 0x0E: { n: 'PageCount', t: VT_I4 },
  3557. 0x0F: { n: 'WordCount', t: VT_I4 },
  3558. 0x10: { n: 'CharCount', t: VT_I4 },
  3559. 0x11: { n: 'Thumbnail', t: VT_CF },
  3560. 0x12: { n: 'Application', t: VT_STRING },
  3561. 0x13: { n: 'DocSecurity', t: VT_I4 },
  3562. 0xFF: {},
  3563. /* [MS-OLEPS] 2.18 */
  3564. 0x80000000: { n: 'Locale', t: VT_UI4 },
  3565. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  3566. 0x72627262: {}
  3567. };
  3568. var DocSummaryRE = evert_key(DocSummaryPIDDSI, "n");
  3569. var SummaryRE = evert_key(SummaryPIDSI, "n");
  3570. /* [MS-XLS] 2.4.63 Country/Region codes */
  3571. var CountryEnum = {
  3572. 0x0001: "US", // United States
  3573. 0x0002: "CA", // Canada
  3574. 0x0003: "", // Latin America (except Brazil)
  3575. 0x0007: "RU", // Russia
  3576. 0x0014: "EG", // Egypt
  3577. 0x001E: "GR", // Greece
  3578. 0x001F: "NL", // Netherlands
  3579. 0x0020: "BE", // Belgium
  3580. 0x0021: "FR", // France
  3581. 0x0022: "ES", // Spain
  3582. 0x0024: "HU", // Hungary
  3583. 0x0027: "IT", // Italy
  3584. 0x0029: "CH", // Switzerland
  3585. 0x002B: "AT", // Austria
  3586. 0x002C: "GB", // United Kingdom
  3587. 0x002D: "DK", // Denmark
  3588. 0x002E: "SE", // Sweden
  3589. 0x002F: "NO", // Norway
  3590. 0x0030: "PL", // Poland
  3591. 0x0031: "DE", // Germany
  3592. 0x0034: "MX", // Mexico
  3593. 0x0037: "BR", // Brazil
  3594. 0x003d: "AU", // Australia
  3595. 0x0040: "NZ", // New Zealand
  3596. 0x0042: "TH", // Thailand
  3597. 0x0051: "JP", // Japan
  3598. 0x0052: "KR", // Korea
  3599. 0x0054: "VN", // Viet Nam
  3600. 0x0056: "CN", // China
  3601. 0x005A: "TR", // Turkey
  3602. 0x0069: "JS", // Ramastan
  3603. 0x00D5: "DZ", // Algeria
  3604. 0x00D8: "MA", // Morocco
  3605. 0x00DA: "LY", // Libya
  3606. 0x015F: "PT", // Portugal
  3607. 0x0162: "IS", // Iceland
  3608. 0x0166: "FI", // Finland
  3609. 0x01A4: "CZ", // Czech Republic
  3610. 0x0376: "TW", // Taiwan
  3611. 0x03C1: "LB", // Lebanon
  3612. 0x03C2: "JO", // Jordan
  3613. 0x03C3: "SY", // Syria
  3614. 0x03C4: "IQ", // Iraq
  3615. 0x03C5: "KW", // Kuwait
  3616. 0x03C6: "SA", // Saudi Arabia
  3617. 0x03CB: "AE", // United Arab Emirates
  3618. 0x03CC: "IL", // Israel
  3619. 0x03CE: "QA", // Qatar
  3620. 0x03D5: "IR", // Iran
  3621. 0xFFFF: "US" // United States
  3622. };
  3623. /* [MS-XLS] 2.5.127 */
  3624. var XLSFillPattern = [
  3625. null,
  3626. 'solid',
  3627. 'mediumGray',
  3628. 'darkGray',
  3629. 'lightGray',
  3630. 'darkHorizontal',
  3631. 'darkVertical',
  3632. 'darkDown',
  3633. 'darkUp',
  3634. 'darkGrid',
  3635. 'darkTrellis',
  3636. 'lightHorizontal',
  3637. 'lightVertical',
  3638. 'lightDown',
  3639. 'lightUp',
  3640. 'lightGrid',
  3641. 'lightTrellis',
  3642. 'gray125',
  3643. 'gray0625'
  3644. ];
  3645. function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }
  3646. /* [MS-XLS] 2.5.161 */
  3647. /* [MS-XLSB] 2.5.75 Icv */
  3648. var _XLSIcv = rgbify([
  3649. /* Color Constants */
  3650. 0x000000,
  3651. 0xFFFFFF,
  3652. 0xFF0000,
  3653. 0x00FF00,
  3654. 0x0000FF,
  3655. 0xFFFF00,
  3656. 0xFF00FF,
  3657. 0x00FFFF,
  3658. /* Overridable Defaults */
  3659. 0x000000,
  3660. 0xFFFFFF,
  3661. 0xFF0000,
  3662. 0x00FF00,
  3663. 0x0000FF,
  3664. 0xFFFF00,
  3665. 0xFF00FF,
  3666. 0x00FFFF,
  3667. 0x800000,
  3668. 0x008000,
  3669. 0x000080,
  3670. 0x808000,
  3671. 0x800080,
  3672. 0x008080,
  3673. 0xC0C0C0,
  3674. 0x808080,
  3675. 0x9999FF,
  3676. 0x993366,
  3677. 0xFFFFCC,
  3678. 0xCCFFFF,
  3679. 0x660066,
  3680. 0xFF8080,
  3681. 0x0066CC,
  3682. 0xCCCCFF,
  3683. 0x000080,
  3684. 0xFF00FF,
  3685. 0xFFFF00,
  3686. 0x00FFFF,
  3687. 0x800080,
  3688. 0x800000,
  3689. 0x008080,
  3690. 0x0000FF,
  3691. 0x00CCFF,
  3692. 0xCCFFFF,
  3693. 0xCCFFCC,
  3694. 0xFFFF99,
  3695. 0x99CCFF,
  3696. 0xFF99CC,
  3697. 0xCC99FF,
  3698. 0xFFCC99,
  3699. 0x3366FF,
  3700. 0x33CCCC,
  3701. 0x99CC00,
  3702. 0xFFCC00,
  3703. 0xFF9900,
  3704. 0xFF6600,
  3705. 0x666699,
  3706. 0x969696,
  3707. 0x003366,
  3708. 0x339966,
  3709. 0x003300,
  3710. 0x333300,
  3711. 0x993300,
  3712. 0x993366,
  3713. 0x333399,
  3714. 0x333333,
  3715. /* Other entries to appease BIFF8/12 */
  3716. 0xFFFFFF, /* 0x40 icvForeground ?? */
  3717. 0x000000, /* 0x41 icvBackground ?? */
  3718. 0x000000, /* 0x42 icvFrame ?? */
  3719. 0x000000, /* 0x43 icv3D ?? */
  3720. 0x000000, /* 0x44 icv3DText ?? */
  3721. 0x000000, /* 0x45 icv3DHilite ?? */
  3722. 0x000000, /* 0x46 icv3DShadow ?? */
  3723. 0x000000, /* 0x47 icvHilite ?? */
  3724. 0x000000, /* 0x48 icvCtlText ?? */
  3725. 0x000000, /* 0x49 icvCtlScrl ?? */
  3726. 0x000000, /* 0x4A icvCtlInv ?? */
  3727. 0x000000, /* 0x4B icvCtlBody ?? */
  3728. 0x000000, /* 0x4C icvCtlFrame ?? */
  3729. 0x000000, /* 0x4D icvCtlFore ?? */
  3730. 0x000000, /* 0x4E icvCtlBack ?? */
  3731. 0x000000, /* 0x4F icvCtlNeutral */
  3732. 0x000000, /* 0x50 icvInfoBk ?? */
  3733. 0x000000 /* 0x51 icvInfoText ?? */
  3734. ]);
  3735. var XLSIcv = dup(_XLSIcv);
  3736. /* [MS-XLSB] 2.5.97.2 */
  3737. var BErr = {
  3738. 0x00: "#NULL!",
  3739. 0x07: "#DIV/0!",
  3740. 0x0F: "#VALUE!",
  3741. 0x17: "#REF!",
  3742. 0x1D: "#NAME?",
  3743. 0x24: "#NUM!",
  3744. 0x2A: "#N/A",
  3745. 0x2B: "#GETTING_DATA",
  3746. 0xFF: "#WTF?"
  3747. };
  3748. var RBErr = evert_num(BErr);
  3749. /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
  3750. /* 12.3 Part Summary <SpreadsheetML> */
  3751. /* 14.2 Part Summary <DrawingML> */
  3752. /* [MS-XLSX] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
  3753. var ct2type/*{[string]:string}*/ = ({
  3754. /* Workbook */
  3755. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  3756. /* Worksheet */
  3757. "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
  3758. /* Macrosheet */
  3759. "application/vnd.ms-excel.intlmacrosheet": "TODO",
  3760. "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
  3761. /* File Properties */
  3762. "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  3763. "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  3764. "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  3765. /* Custom Data Properties */
  3766. "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  3767. "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  3768. /* PivotTable */
  3769. "application/vnd.ms-excel.pivotTable": "TODO",
  3770. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  3771. /* Chart Objects */
  3772. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  3773. /* Chart Colors */
  3774. "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  3775. /* Chart Style */
  3776. "application/vnd.ms-office.chartstyle+xml": "TODO",
  3777. /* Chart Advanced */
  3778. "application/vnd.ms-office.chartex+xml": "TODO",
  3779. /* Calculation Chain */
  3780. "application/vnd.ms-excel.calcChain": "calcchains",
  3781. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  3782. /* Printer Settings */
  3783. "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  3784. /* ActiveX */
  3785. "application/vnd.ms-office.activeX": "TODO",
  3786. "application/vnd.ms-office.activeX+xml": "TODO",
  3787. /* Custom Toolbars */
  3788. "application/vnd.ms-excel.attachedToolbars": "TODO",
  3789. /* External Data Connections */
  3790. "application/vnd.ms-excel.connections": "TODO",
  3791. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  3792. /* External Links */
  3793. "application/vnd.ms-excel.externalLink": "links",
  3794. "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  3795. /* Metadata */
  3796. "application/vnd.ms-excel.sheetMetadata": "TODO",
  3797. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "TODO",
  3798. /* PivotCache */
  3799. "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  3800. "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  3801. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  3802. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  3803. /* Query Table */
  3804. "application/vnd.ms-excel.queryTable": "TODO",
  3805. "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  3806. /* Shared Workbook */
  3807. "application/vnd.ms-excel.userNames": "TODO",
  3808. "application/vnd.ms-excel.revisionHeaders": "TODO",
  3809. "application/vnd.ms-excel.revisionLog": "TODO",
  3810. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  3811. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  3812. "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  3813. /* Single Cell Table */
  3814. "application/vnd.ms-excel.tableSingleCells": "TODO",
  3815. "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  3816. /* Slicer */
  3817. "application/vnd.ms-excel.slicer": "TODO",
  3818. "application/vnd.ms-excel.slicerCache": "TODO",
  3819. "application/vnd.ms-excel.slicer+xml": "TODO",
  3820. "application/vnd.ms-excel.slicerCache+xml": "TODO",
  3821. /* Sort Map */
  3822. "application/vnd.ms-excel.wsSortMap": "TODO",
  3823. /* Table */
  3824. "application/vnd.ms-excel.table": "TODO",
  3825. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  3826. /* Themes */
  3827. "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  3828. /* Theme Override */
  3829. "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  3830. /* Timeline */
  3831. "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
  3832. "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
  3833. /* VBA */
  3834. "application/vnd.ms-office.vbaProject": "vba",
  3835. "application/vnd.ms-office.vbaProjectSignature": "vba",
  3836. /* Volatile Dependencies */
  3837. "application/vnd.ms-office.volatileDependencies": "TODO",
  3838. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  3839. /* Control Properties */
  3840. "application/vnd.ms-excel.controlproperties+xml": "TODO",
  3841. /* Data Model */
  3842. "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  3843. /* Survey */
  3844. "application/vnd.ms-excel.Survey+xml": "TODO",
  3845. /* Drawing */
  3846. "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  3847. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  3848. "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  3849. "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  3850. "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  3851. "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  3852. /* VML */
  3853. "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  3854. "application/vnd.openxmlformats-package.relationships+xml": "rels",
  3855. "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  3856. /* Image */
  3857. "image/png": "TODO",
  3858. "sheet": "js"
  3859. });
  3860. var CT_LIST = (function(){
  3861. var o = {
  3862. workbooks: {
  3863. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  3864. xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
  3865. xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
  3866. xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
  3867. xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
  3868. },
  3869. strs: { /* Shared Strings */
  3870. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
  3871. xlsb: "application/vnd.ms-excel.sharedStrings"
  3872. },
  3873. comments: { /* Comments */
  3874. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  3875. xlsb: "application/vnd.ms-excel.comments"
  3876. },
  3877. sheets: { /* Worksheet */
  3878. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  3879. xlsb: "application/vnd.ms-excel.worksheet"
  3880. },
  3881. charts: { /* Chartsheet */
  3882. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
  3883. xlsb: "application/vnd.ms-excel.chartsheet"
  3884. },
  3885. dialogs: { /* Dialogsheet */
  3886. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
  3887. xlsb: "application/vnd.ms-excel.dialogsheet"
  3888. },
  3889. macros: { /* Macrosheet (Excel 4.0 Macros) */
  3890. xlsx: "application/vnd.ms-excel.macrosheet+xml",
  3891. xlsb: "application/vnd.ms-excel.macrosheet"
  3892. },
  3893. styles: { /* Styles */
  3894. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
  3895. xlsb: "application/vnd.ms-excel.styles"
  3896. }
  3897. };
  3898. keys(o).forEach(function(k) { ["xlsm", "xlam"].forEach(function(v) { if(!o[k][v]) o[k][v] = o[k].xlsx; }); });
  3899. keys(o).forEach(function(k){ keys(o[k]).forEach(function(v) { ct2type[o[k][v]] = k; }); });
  3900. return o;
  3901. })();
  3902. var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);
  3903. XMLNS.CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
  3904. function new_ct() {
  3905. return ({
  3906. workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
  3907. rels:[], strs:[], comments:[], links:[],
  3908. coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
  3909. calcchains:[], vba: [], drawings: [],
  3910. TODO:[], xmlns: "" });
  3911. }
  3912. function parse_ct(data) {
  3913. var ct = new_ct();
  3914. if(!data || !data.match) return ct;
  3915. var ctext = {};
  3916. (data.match(tagregex)||[]).forEach(function(x) {
  3917. var y = parsexmltag(x);
  3918. switch(y[0].replace(nsregex,"<")) {
  3919. case '<?xml': break;
  3920. case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
  3921. case '<Default': ctext[y.Extension] = y.ContentType; break;
  3922. case '<Override':
  3923. if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
  3924. break;
  3925. }
  3926. });
  3927. if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  3928. ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  3929. ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  3930. ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  3931. ct.defaults = ctext;
  3932. delete ct.calcchains;
  3933. return ct;
  3934. }
  3935. var CTYPE_XML_ROOT = writextag('Types', null, {
  3936. 'xmlns': XMLNS.CT,
  3937. 'xmlns:xsd': XMLNS.xsd,
  3938. 'xmlns:xsi': XMLNS.xsi
  3939. });
  3940. var CTYPE_DEFAULTS = [
  3941. ['xml', 'application/xml'],
  3942. ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
  3943. ['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
  3944. ['data', 'application/vnd.openxmlformats-officedocument.model+data'],
  3945. /* from test files */
  3946. ['bmp', 'image/bmp'],
  3947. ['png', 'image/png'],
  3948. ['gif', 'image/gif'],
  3949. ['emf', 'image/x-emf'],
  3950. ['wmf', 'image/x-wmf'],
  3951. ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
  3952. ['tif', 'image/tiff'], ['tiff', 'image/tiff'],
  3953. ['pdf', 'application/pdf'],
  3954. ['rels', type2ct.rels[0]]
  3955. ].map(function(x) {
  3956. return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
  3957. });
  3958. function write_ct(ct, opts) {
  3959. var o = [], v;
  3960. o[o.length] = (XML_HEADER);
  3961. o[o.length] = (CTYPE_XML_ROOT);
  3962. o = o.concat(CTYPE_DEFAULTS);
  3963. /* only write first instance */
  3964. var f1 = function(w) {
  3965. if(ct[w] && ct[w].length > 0) {
  3966. v = ct[w][0];
  3967. o[o.length] = (writextag('Override', null, {
  3968. 'PartName': (v[0] == '/' ? "":"/") + v,
  3969. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  3970. }));
  3971. }
  3972. };
  3973. /* book type-specific */
  3974. var f2 = function(w) {
  3975. (ct[w]||[]).forEach(function(v) {
  3976. o[o.length] = (writextag('Override', null, {
  3977. 'PartName': (v[0] == '/' ? "":"/") + v,
  3978. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  3979. }));
  3980. });
  3981. };
  3982. /* standard type */
  3983. var f3 = function(t) {
  3984. (ct[t]||[]).forEach(function(v) {
  3985. o[o.length] = (writextag('Override', null, {
  3986. 'PartName': (v[0] == '/' ? "":"/") + v,
  3987. 'ContentType': type2ct[t][0]
  3988. }));
  3989. });
  3990. };
  3991. f1('workbooks');
  3992. f2('sheets');
  3993. f2('charts');
  3994. f3('themes');
  3995. ['strs', 'styles'].forEach(f1);
  3996. ['coreprops', 'extprops', 'custprops'].forEach(f3);
  3997. f3('vba');
  3998. f3('comments');
  3999. f3('drawings');
  4000. if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
  4001. return o.join("");
  4002. }
  4003. /* 9.3 Relationships */
  4004. var RELS = ({
  4005. WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4006. SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4007. HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  4008. VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  4009. XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  4010. XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  4011. XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  4012. CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  4013. CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  4014. VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
  4015. });
  4016. /* 9.3.3 Representing Relationships */
  4017. function get_rels_path(file) {
  4018. var n = file.lastIndexOf("/");
  4019. return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
  4020. }
  4021. function parse_rels(data, currentFilePath) {
  4022. var rels = {"!id":{}};
  4023. if (!data) return rels;
  4024. if (currentFilePath.charAt(0) !== '/') {
  4025. currentFilePath = '/'+currentFilePath;
  4026. }
  4027. var hash = {};
  4028. (data.match(tagregex)||[]).forEach(function(x) {
  4029. var y = parsexmltag(x);
  4030. /* 9.3.2.2 OPC_Relationships */
  4031. if (y[0] === '<Relationship') {
  4032. var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; if(y.TargetMode) rel.TargetMode = y.TargetMode;
  4033. var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
  4034. rels[canonictarget] = rel;
  4035. hash[y.Id] = rel;
  4036. }
  4037. });
  4038. rels["!id"] = hash;
  4039. return rels;
  4040. }
  4041. XMLNS.RELS = 'http://schemas.openxmlformats.org/package/2006/relationships';
  4042. var RELS_ROOT = writextag('Relationships', null, {
  4043. //'xmlns:ns0': XMLNS.RELS,
  4044. 'xmlns': XMLNS.RELS
  4045. });
  4046. /* TODO */
  4047. function write_rels(rels) {
  4048. var o = [XML_HEADER, RELS_ROOT];
  4049. keys(rels['!id']).forEach(function(rid) {
  4050. o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
  4051. });
  4052. if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
  4053. return o.join("");
  4054. }
  4055. var RELS_EXTERN = [RELS.HLINK, RELS.XPATH, RELS.XMISS];
  4056. function add_rels(rels, rId, f, type, relobj, targetmode) {
  4057. if(!relobj) relobj = {};
  4058. if(!rels['!id']) rels['!id'] = {};
  4059. if(rId < 0) for(rId = 1; rels['!id']['rId' + rId]; ++rId){/* empty */}
  4060. relobj.Id = 'rId' + rId;
  4061. relobj.Type = type;
  4062. relobj.Target = f;
  4063. if(targetmode) relobj.TargetMode = targetmode;
  4064. else if(RELS_EXTERN.indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
  4065. if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
  4066. rels['!id'][relobj.Id] = relobj;
  4067. rels[('/' + relobj.Target).replace("//","/")] = relobj;
  4068. return rId;
  4069. }
  4070. /* ECMA-376 Part II 11.1 Core Properties Part */
  4071. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  4072. var CORE_PROPS = [
  4073. ["cp:category", "Category"],
  4074. ["cp:contentStatus", "ContentStatus"],
  4075. ["cp:keywords", "Keywords"],
  4076. ["cp:lastModifiedBy", "LastAuthor"],
  4077. ["cp:lastPrinted", "LastPrinted"],
  4078. ["cp:revision", "RevNumber"],
  4079. ["cp:version", "Version"],
  4080. ["dc:creator", "Author"],
  4081. ["dc:description", "Comments"],
  4082. ["dc:identifier", "Identifier"],
  4083. ["dc:language", "Language"],
  4084. ["dc:subject", "Subject"],
  4085. ["dc:title", "Title"],
  4086. ["dcterms:created", "CreatedDate", 'date'],
  4087. ["dcterms:modified", "ModifiedDate", 'date']
  4088. ];
  4089. XMLNS.CORE_PROPS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
  4090. RELS.CORE_PROPS = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';
  4091. var CORE_PROPS_REGEX = (function() {
  4092. var r = new Array(CORE_PROPS.length);
  4093. for(var i = 0; i < CORE_PROPS.length; ++i) {
  4094. var f = CORE_PROPS[i];
  4095. var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
  4096. r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
  4097. }
  4098. return r;
  4099. })();
  4100. function parse_core_props(data) {
  4101. var p = {};
  4102. data = utf8read(data);
  4103. for(var i = 0; i < CORE_PROPS.length; ++i) {
  4104. var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
  4105. if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
  4106. if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
  4107. }
  4108. return p;
  4109. }
  4110. var CORE_PROPS_XML_ROOT = writextag('cp:coreProperties', null, {
  4111. //'xmlns': XMLNS.CORE_PROPS,
  4112. 'xmlns:cp': XMLNS.CORE_PROPS,
  4113. 'xmlns:dc': XMLNS.dc,
  4114. 'xmlns:dcterms': XMLNS.dcterms,
  4115. 'xmlns:dcmitype': XMLNS.dcmitype,
  4116. 'xmlns:xsi': XMLNS.xsi
  4117. });
  4118. function cp_doit(f, g, h, o, p) {
  4119. if(p[f] != null || g == null || g === "") return;
  4120. p[f] = g;
  4121. g = escapexml(g);
  4122. o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
  4123. }
  4124. function write_core_props(cp, _opts) {
  4125. var opts = _opts || {};
  4126. var o = [XML_HEADER, CORE_PROPS_XML_ROOT], p = {};
  4127. if(!cp && !opts.Props) return o.join("");
  4128. if(cp) {
  4129. if(cp.CreatedDate != null) cp_doit("dcterms:created", typeof cp.CreatedDate === "string" ? cp.CreatedDate : write_w3cdtf(cp.CreatedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
  4130. if(cp.ModifiedDate != null) cp_doit("dcterms:modified", typeof cp.ModifiedDate === "string" ? cp.ModifiedDate : write_w3cdtf(cp.ModifiedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
  4131. }
  4132. for(var i = 0; i != CORE_PROPS.length; ++i) {
  4133. var f = CORE_PROPS[i];
  4134. var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
  4135. if(v === true) v = "1";
  4136. else if(v === false) v = "0";
  4137. else if(typeof v == "number") v = String(v);
  4138. if(v != null) cp_doit(f[0], v, null, o, p);
  4139. }
  4140. if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
  4141. return o.join("");
  4142. }
  4143. /* 15.2.12.3 Extended File Properties Part */
  4144. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  4145. var EXT_PROPS = [
  4146. ["Application", "Application", "string"],
  4147. ["AppVersion", "AppVersion", "string"],
  4148. ["Company", "Company", "string"],
  4149. ["DocSecurity", "DocSecurity", "string"],
  4150. ["Manager", "Manager", "string"],
  4151. ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  4152. ["SharedDoc", "SharedDoc", "bool"],
  4153. ["LinksUpToDate", "LinksUpToDate", "bool"],
  4154. ["ScaleCrop", "ScaleCrop", "bool"],
  4155. ["HeadingPairs", "HeadingPairs", "raw"],
  4156. ["TitlesOfParts", "TitlesOfParts", "raw"]
  4157. ];
  4158. XMLNS.EXT_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
  4159. RELS.EXT_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';
  4160. var PseudoPropsPairs = [
  4161. "Worksheets", "SheetNames",
  4162. "NamedRanges", "DefinedNames",
  4163. "Chartsheets", "ChartNames"
  4164. ];
  4165. function load_props_pairs(HP, TOP, props, opts) {
  4166. var v = [];
  4167. if(typeof HP == "string") v = parseVector(HP, opts);
  4168. else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
  4169. var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
  4170. var idx = 0, len = 0;
  4171. if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
  4172. len = +(v[i+1].v);
  4173. switch(v[i].v) {
  4174. case "Worksheets":
  4175. case "工作表":
  4176. case "Листы":
  4177. case "أوراق العمل":
  4178. case "ワークシート":
  4179. case "גליונות עבודה":
  4180. case "Arbeitsblätter":
  4181. case "Çalışma Sayfaları":
  4182. case "Feuilles de calcul":
  4183. case "Fogli di lavoro":
  4184. case "Folhas de cálculo":
  4185. case "Planilhas":
  4186. case "Regneark":
  4187. case "Hojas de cálculo":
  4188. case "Werkbladen":
  4189. props.Worksheets = len;
  4190. props.SheetNames = parts.slice(idx, idx + len);
  4191. break;
  4192. case "Named Ranges":
  4193. case "Rangos con nombre":
  4194. case "名前付き一覧":
  4195. case "Benannte Bereiche":
  4196. case "Navngivne områder":
  4197. props.NamedRanges = len;
  4198. props.DefinedNames = parts.slice(idx, idx + len);
  4199. break;
  4200. case "Charts":
  4201. case "Diagramme":
  4202. props.Chartsheets = len;
  4203. props.ChartNames = parts.slice(idx, idx + len);
  4204. break;
  4205. }
  4206. idx += len;
  4207. }
  4208. }
  4209. function parse_ext_props(data, p, opts) {
  4210. var q = {}; if(!p) p = {};
  4211. data = utf8read(data);
  4212. EXT_PROPS.forEach(function(f) {
  4213. var xml = (data.match(matchtag(f[0]))||[])[1];
  4214. switch(f[2]) {
  4215. case "string": if(xml) p[f[1]] = unescapexml(xml); break;
  4216. case "bool": p[f[1]] = xml === "true"; break;
  4217. case "raw":
  4218. var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
  4219. if(cur && cur.length > 0) q[f[1]] = cur[1];
  4220. break;
  4221. }
  4222. });
  4223. if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);
  4224. return p;
  4225. }
  4226. var EXT_PROPS_XML_ROOT = writextag('Properties', null, {
  4227. 'xmlns': XMLNS.EXT_PROPS,
  4228. 'xmlns:vt': XMLNS.vt
  4229. });
  4230. function write_ext_props(cp) {
  4231. var o = [], W = writextag;
  4232. if(!cp) cp = {};
  4233. cp.Application = "SheetJS";
  4234. o[o.length] = (XML_HEADER);
  4235. o[o.length] = (EXT_PROPS_XML_ROOT);
  4236. EXT_PROPS.forEach(function(f) {
  4237. if(cp[f[1]] === undefined) return;
  4238. var v;
  4239. switch(f[2]) {
  4240. case 'string': v = escapexml(String(cp[f[1]])); break;
  4241. case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
  4242. }
  4243. if(v !== undefined) o[o.length] = (W(f[0], v));
  4244. });
  4245. /* TODO: HeadingPairs, TitlesOfParts */
  4246. o[o.length] = (W('HeadingPairs', W('vt:vector', W('vt:variant', '<vt:lpstr>Worksheets</vt:lpstr>')+W('vt:variant', W('vt:i4', String(cp.Worksheets))), {size:2, baseType:"variant"})));
  4247. o[o.length] = (W('TitlesOfParts', W('vt:vector', cp.SheetNames.map(function(s) { return "<vt:lpstr>" + escapexml(s) + "</vt:lpstr>"; }).join(""), {size: cp.Worksheets, baseType:"lpstr"})));
  4248. if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
  4249. return o.join("");
  4250. }
  4251. /* 15.2.12.2 Custom File Properties Part */
  4252. XMLNS.CUST_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
  4253. RELS.CUST_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';
  4254. var custregex = /<[^>]+>[^<]*/g;
  4255. function parse_cust_props(data, opts) {
  4256. var p = {}, name = "";
  4257. var m = data.match(custregex);
  4258. if(m) for(var i = 0; i != m.length; ++i) {
  4259. var x = m[i], y = parsexmltag(x);
  4260. switch(y[0]) {
  4261. case '<?xml': break;
  4262. case '<Properties': break;
  4263. case '<property': name = unescapexml(y.name); break;
  4264. case '</property>': name = null; break;
  4265. default: if (x.indexOf('<vt:') === 0) {
  4266. var toks = x.split('>');
  4267. var type = toks[0].slice(4), text = toks[1];
  4268. /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
  4269. switch(type) {
  4270. case 'lpstr': case 'bstr': case 'lpwstr':
  4271. p[name] = unescapexml(text);
  4272. break;
  4273. case 'bool':
  4274. p[name] = parsexmlbool(text);
  4275. break;
  4276. case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
  4277. p[name] = parseInt(text, 10);
  4278. break;
  4279. case 'r4': case 'r8': case 'decimal':
  4280. p[name] = parseFloat(text);
  4281. break;
  4282. case 'filetime': case 'date':
  4283. p[name] = parseDate(text);
  4284. break;
  4285. case 'cy': case 'error':
  4286. p[name] = unescapexml(text);
  4287. break;
  4288. default:
  4289. if(type.slice(-1) == '/') break;
  4290. if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
  4291. }
  4292. } else if(x.slice(0,2) === "</") {/* empty */
  4293. } else if(opts.WTF) throw new Error(x);
  4294. }
  4295. }
  4296. return p;
  4297. }
  4298. var CUST_PROPS_XML_ROOT = writextag('Properties', null, {
  4299. 'xmlns': XMLNS.CUST_PROPS,
  4300. 'xmlns:vt': XMLNS.vt
  4301. });
  4302. function write_cust_props(cp) {
  4303. var o = [XML_HEADER, CUST_PROPS_XML_ROOT];
  4304. if(!cp) return o.join("");
  4305. var pid = 1;
  4306. keys(cp).forEach(function custprop(k) { ++pid;
  4307. o[o.length] = (writextag('property', write_vt(cp[k], true), {
  4308. 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
  4309. 'pid': pid,
  4310. 'name': escapexml(k)
  4311. }));
  4312. });
  4313. if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
  4314. return o.join("");
  4315. }
  4316. /* from js-harb (C) 2014-present SheetJS */
  4317. var DBF = (function() {
  4318. var dbf_codepage_map = {
  4319. /* Code Pages Supported by Visual FoxPro */
  4320. 0x01: 437, 0x02: 850,
  4321. 0x03: 1252, 0x04: 10000,
  4322. 0x64: 852, 0x65: 866,
  4323. 0x66: 865, 0x67: 861,
  4324. 0x68: 895, 0x69: 620,
  4325. 0x6A: 737, 0x6B: 857,
  4326. 0x78: 950, 0x79: 949,
  4327. 0x7A: 936, 0x7B: 932,
  4328. 0x7C: 874, 0x7D: 1255,
  4329. 0x7E: 1256, 0x96: 10007,
  4330. 0x97: 10029, 0x98: 10006,
  4331. 0xC8: 1250, 0xC9: 1251,
  4332. 0xCA: 1254, 0xCB: 1253,
  4333. /* shapefile DBF extension */
  4334. 0x00: 20127, 0x08: 865,
  4335. 0x09: 437, 0x0A: 850,
  4336. 0x0B: 437, 0x0D: 437,
  4337. 0x0E: 850, 0x0F: 437,
  4338. 0x10: 850, 0x11: 437,
  4339. 0x12: 850, 0x13: 932,
  4340. 0x14: 850, 0x15: 437,
  4341. 0x16: 850, 0x17: 865,
  4342. 0x18: 437, 0x19: 437,
  4343. 0x1A: 850, 0x1B: 437,
  4344. 0x1C: 863, 0x1D: 850,
  4345. 0x1F: 852, 0x22: 852,
  4346. 0x23: 852, 0x24: 860,
  4347. 0x25: 850, 0x26: 866,
  4348. 0x37: 850, 0x40: 852,
  4349. 0x4D: 936, 0x4E: 949,
  4350. 0x4F: 950, 0x50: 874,
  4351. 0x57: 1252, 0x58: 1252,
  4352. 0x59: 1252, 0x6C: 863,
  4353. 0x86: 737, 0x87: 852,
  4354. 0x88: 857, 0xCC: 1257,
  4355. 0xFF: 16969
  4356. };
  4357. var dbf_reverse_map = evert({
  4358. 0x01: 437, 0x02: 850,
  4359. 0x03: 1252, 0x04: 10000,
  4360. 0x64: 852, 0x65: 866,
  4361. 0x66: 865, 0x67: 861,
  4362. 0x68: 895, 0x69: 620,
  4363. 0x6A: 737, 0x6B: 857,
  4364. 0x78: 950, 0x79: 949,
  4365. 0x7A: 936, 0x7B: 932,
  4366. 0x7C: 874, 0x7D: 1255,
  4367. 0x7E: 1256, 0x96: 10007,
  4368. 0x97: 10029, 0x98: 10006,
  4369. 0xC8: 1250, 0xC9: 1251,
  4370. 0xCA: 1254, 0xCB: 1253,
  4371. 0x00: 20127
  4372. });
  4373. var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
  4374. /* TODO: find an actual specification */
  4375. function dbf_to_aoa(buf, opts) {
  4376. var out = [];
  4377. var d = (new_raw_buf(1));
  4378. switch(opts.type) {
  4379. case 'base64': d = s2a(Base64.decode(buf)); break;
  4380. case 'binary': d = s2a(buf); break;
  4381. case 'buffer':
  4382. case 'array': d = buf; break;
  4383. }
  4384. prep_blob(d, 0);
  4385. /* header */
  4386. var ft = d.read_shift(1);
  4387. var memo = !!(ft & 0x88);
  4388. var vfp = false, l7 = false;
  4389. switch(ft) {
  4390. case 0x02: break; // dBASE II
  4391. case 0x03: break; // dBASE III
  4392. case 0x30: vfp = true; memo = true; break; // VFP
  4393. case 0x31: vfp = true; memo = true; break; // VFP with autoincrement
  4394. // 0x43 dBASE IV SQL table files
  4395. // 0x63 dBASE IV SQL system files
  4396. case 0x83: break; // dBASE III with memo
  4397. case 0x8B: break; // dBASE IV with memo
  4398. case 0x8C: l7 = true; break; // dBASE Level 7 with memo
  4399. // case 0xCB dBASE IV SQL table files with memo
  4400. case 0xF5: break; // FoxPro 2.x with memo
  4401. // case 0xFB FoxBASE
  4402. default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
  4403. }
  4404. var nrow = 0, fpos = 0x0209;
  4405. if(ft == 0x02) nrow = d.read_shift(2);
  4406. d.l += 3; // dBASE II stores DDMMYY date, others use YYMMDD
  4407. if(ft != 0x02) nrow = d.read_shift(4);
  4408. if(nrow > 1048576) nrow = 1e6;
  4409. if(ft != 0x02) fpos = d.read_shift(2); // header length
  4410. var rlen = d.read_shift(2); // record length
  4411. var /*flags = 0,*/ current_cp = opts.codepage || 1252;
  4412. if(ft != 0x02) { // 20 reserved bytes
  4413. d.l+=16;
  4414. /*flags = */d.read_shift(1);
  4415. //if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));
  4416. /* codepage present in FoxPro and dBASE Level 7 */
  4417. if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
  4418. d.l+=1;
  4419. d.l+=2;
  4420. }
  4421. if(l7) d.l += 36; // Level 7: 32 byte "Language driver name", 4 byte reserved
  4422. var fields = [], field = ({});
  4423. var hend = Math.min(d.length, (ft == 0x02 ? 0x209 : (fpos - 10 - (vfp ? 264 : 0))));
  4424. var ww = l7 ? 32 : 11;
  4425. while(d.l < hend && d[d.l] != 0x0d) {
  4426. field = ({});
  4427. field.name = cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)).replace(/[\u0000\r\n].*$/g,"");
  4428. d.l += ww;
  4429. field.type = String.fromCharCode(d.read_shift(1));
  4430. if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
  4431. field.len = d.read_shift(1);
  4432. if(ft == 0x02) field.offset = d.read_shift(2);
  4433. field.dec = d.read_shift(1);
  4434. if(field.name.length) fields.push(field);
  4435. if(ft != 0x02) d.l += l7 ? 13 : 14;
  4436. switch(field.type) {
  4437. case 'B': // Double (VFP) / Binary (dBASE L7)
  4438. if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  4439. break;
  4440. case 'G': // General (FoxPro and dBASE L7)
  4441. case 'P': // Picture (FoxPro and dBASE L7)
  4442. if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  4443. break;
  4444. case '+': // Autoincrement (dBASE L7 only)
  4445. case '0': // _NullFlags (VFP only)
  4446. case '@': // Timestamp (dBASE L7 only)
  4447. case 'C': // Character (dBASE II)
  4448. case 'D': // Date (dBASE III)
  4449. case 'F': // Float (dBASE IV)
  4450. case 'I': // Long (VFP and dBASE L7)
  4451. case 'L': // Logical (dBASE II)
  4452. case 'M': // Memo (dBASE III)
  4453. case 'N': // Number (dBASE II)
  4454. case 'O': // Double (dBASE L7 only)
  4455. case 'T': // Datetime (VFP only)
  4456. case 'Y': // Currency (VFP only)
  4457. break;
  4458. default: throw new Error('Unknown Field Type: ' + field.type);
  4459. }
  4460. }
  4461. if(d[d.l] !== 0x0D) d.l = fpos-1;
  4462. if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
  4463. d.l = fpos;
  4464. /* data */
  4465. var R = 0, C = 0;
  4466. out[0] = [];
  4467. for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
  4468. while(nrow-- > 0) {
  4469. if(d[d.l] === 0x2A) {
  4470. // TODO: record marked as deleted -- create a hidden row?
  4471. d.l+=rlen;
  4472. continue;
  4473. }
  4474. ++d.l;
  4475. out[++R] = []; C = 0;
  4476. for(C = 0; C != fields.length; ++C) {
  4477. var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
  4478. prep_blob(dd, 0);
  4479. var s = cptable.utils.decode(current_cp, dd);
  4480. switch(fields[C].type) {
  4481. case 'C':
  4482. // NOTE: it is conventional to write ' / / ' for empty dates
  4483. if(s.trim().length) out[R][C] = s.replace(/\s+$/,"");
  4484. break;
  4485. case 'D':
  4486. if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
  4487. else out[R][C] = s;
  4488. break;
  4489. case 'F': out[R][C] = parseFloat(s.trim()); break;
  4490. case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
  4491. case 'L': switch(s.trim().toUpperCase()) {
  4492. case 'Y': case 'T': out[R][C] = true; break;
  4493. case 'N': case 'F': out[R][C] = false; break;
  4494. case '': case '?': break;
  4495. default: throw new Error("DBF Unrecognized L:|" + s + "|");
  4496. } break;
  4497. case 'M': /* TODO: handle memo files */
  4498. if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
  4499. out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
  4500. break;
  4501. case 'N':
  4502. s = s.replace(/\u0000/g,"").trim();
  4503. // NOTE: dBASE II interprets " . " as 0
  4504. if(s && s != ".") out[R][C] = +s || 0; break;
  4505. case '@':
  4506. // NOTE: dBASE specs appear to be incorrect
  4507. out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400);
  4508. break;
  4509. case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
  4510. case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4; break;
  4511. case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
  4512. case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
  4513. /* falls through */
  4514. case 'G': case 'P': dd.l += fields[C].len; break;
  4515. case '0':
  4516. if(fields[C].name === '_NullFlags') break;
  4517. /* falls through */
  4518. default: throw new Error("DBF Unsupported data type " + fields[C].type);
  4519. }
  4520. }
  4521. }
  4522. if(ft != 0x02) if(d.l < d.length && d[d.l++] != 0x1A) throw new Error("DBF EOF Marker missing " + (d.l-1) + " of " + d.length + " " + d[d.l-1].toString(16));
  4523. if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
  4524. return out;
  4525. }
  4526. function dbf_to_sheet(buf, opts) {
  4527. var o = opts || {};
  4528. if(!o.dateNF) o.dateNF = "yyyymmdd";
  4529. return aoa_to_sheet(dbf_to_aoa(buf, o), o);
  4530. }
  4531. function dbf_to_workbook(buf, opts) {
  4532. try { return sheet_to_workbook(dbf_to_sheet(buf, opts), opts); }
  4533. catch(e) { if(opts && opts.WTF) throw e; }
  4534. return ({SheetNames:[],Sheets:{}});
  4535. }
  4536. var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
  4537. function sheet_to_dbf(ws, opts) {
  4538. var o = opts || {};
  4539. if(+o.codepage >= 0) set_cp(+o.codepage);
  4540. if(o.type == "string") throw new Error("Cannot write DBF to JS string");
  4541. var ba = buf_array();
  4542. var aoa = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
  4543. var headers = aoa[0], data = aoa.slice(1);
  4544. var i = 0, j = 0, hcnt = 0, rlen = 1;
  4545. for(i = 0; i < headers.length; ++i) {
  4546. if(i == null) continue;
  4547. ++hcnt;
  4548. if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
  4549. if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
  4550. if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
  4551. if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
  4552. }
  4553. var range = safe_decode_range(ws['!ref']);
  4554. var coltypes = [];
  4555. for(i = 0; i <= range.e.c - range.s.c; ++i) {
  4556. var col = [];
  4557. for(j=0; j < data.length; ++j) {
  4558. if(data[j][i] != null) col.push(data[j][i]);
  4559. }
  4560. if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
  4561. var guess = '', _guess = '';
  4562. for(j = 0; j < col.length; ++j) {
  4563. switch(typeof col[j]) {
  4564. /* TODO: check if L2 compat is desired */
  4565. case 'number': _guess = 'B'; break;
  4566. case 'string': _guess = 'C'; break;
  4567. case 'boolean': _guess = 'L'; break;
  4568. case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
  4569. default: _guess = 'C';
  4570. }
  4571. guess = guess && guess != _guess ? 'C' : _guess;
  4572. if(guess == 'C') break;
  4573. }
  4574. rlen += _RLEN[guess] || 0;
  4575. coltypes[i] = guess;
  4576. }
  4577. var h = ba.next(32);
  4578. h.write_shift(4, 0x13021130);
  4579. h.write_shift(4, data.length);
  4580. h.write_shift(2, 296 + 32 * hcnt);
  4581. h.write_shift(2, rlen);
  4582. for(i=0; i < 4; ++i) h.write_shift(4, 0);
  4583. h.write_shift(4, 0x00000000 | ((+dbf_reverse_map[current_ansi] || 0x03)<<8));
  4584. for(i = 0, j = 0; i < headers.length; ++i) {
  4585. if(headers[i] == null) continue;
  4586. var hf = ba.next(32);
  4587. var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
  4588. hf.write_shift(1, _f, "sbcs");
  4589. hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
  4590. hf.write_shift(4, j);
  4591. hf.write_shift(1, _RLEN[coltypes[i]] || 0);
  4592. hf.write_shift(1, 0);
  4593. hf.write_shift(1, 0x02);
  4594. hf.write_shift(4, 0);
  4595. hf.write_shift(1, 0);
  4596. hf.write_shift(4, 0);
  4597. hf.write_shift(4, 0);
  4598. j += _RLEN[coltypes[i]] || 0;
  4599. }
  4600. var hb = ba.next(264);
  4601. hb.write_shift(4, 0x0000000D);
  4602. for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
  4603. for(i=0; i < data.length; ++i) {
  4604. var rout = ba.next(rlen);
  4605. rout.write_shift(1, 0);
  4606. for(j=0; j<headers.length; ++j) {
  4607. if(headers[j] == null) continue;
  4608. switch(coltypes[j]) {
  4609. case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
  4610. case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
  4611. case 'D':
  4612. if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
  4613. else {
  4614. rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
  4615. rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
  4616. rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
  4617. } break;
  4618. case 'C':
  4619. var _s = String(data[i][j]||"");
  4620. rout.write_shift(1, _s, "sbcs");
  4621. for(hcnt=0; hcnt < 250-_s.length; ++hcnt) rout.write_shift(1, 0x20); break;
  4622. }
  4623. }
  4624. // data
  4625. }
  4626. ba.next(1).write_shift(1, 0x1A);
  4627. return ba.end();
  4628. }
  4629. return {
  4630. versions: DBF_SUPPORTED_VERSIONS,
  4631. to_workbook: dbf_to_workbook,
  4632. to_sheet: dbf_to_sheet,
  4633. from_sheet: sheet_to_dbf
  4634. };
  4635. })();
  4636. var SYLK = (function() {
  4637. /* TODO: stress test sequences */
  4638. var sylk_escapes = ({
  4639. AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
  4640. AE:'È', BE:'É', CE:'Ê', HE:'Ë',
  4641. AI:'Ì', BI:'Í', CI:'Î', HI:'Ï',
  4642. AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
  4643. AU:'Ù', BU:'Ú', CU:'Û', HU:'Ü',
  4644. Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
  4645. Ae:'è', Be:'é', Ce:'ê', He:'ë',
  4646. Ai:'ì', Bi:'í', Ci:'î', Hi:'ï',
  4647. Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
  4648. Au:'ù', Bu:'ú', Cu:'û', Hu:'ü',
  4649. KC:'Ç', Kc:'ç', q:'æ', z:'œ', a:'Æ', j:'Œ',
  4650. DN:209, Dn:241, Hy:255,
  4651. S:169, c:170, R:174, "B ":180,
  4652. 0:176, 1:177, 2:178,
  4653. 3:179, 5:181, 6:182,
  4654. 7:183, Q:185, k:186, b:208, i:216, l:222, s:240, y:248,
  4655. "!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
  4656. "+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
  4657. });
  4658. var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
  4659. var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
  4660. var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
  4661. sylk_escapes["|"] = 254;
  4662. /* TODO: find an actual specification */
  4663. function sylk_to_aoa(d, opts) {
  4664. switch(opts.type) {
  4665. case 'base64': return sylk_to_aoa_str(Base64.decode(d), opts);
  4666. case 'binary': return sylk_to_aoa_str(d, opts);
  4667. case 'buffer': return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  4668. case 'array': return sylk_to_aoa_str(cc2str(d), opts);
  4669. }
  4670. throw new Error("Unrecognized type " + opts.type);
  4671. }
  4672. function sylk_to_aoa_str(str, opts) {
  4673. var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr = [];
  4674. var formats = [];
  4675. var next_cell_format = null;
  4676. var sht = {}, rowinfo = [], colinfo = [], cw = [];
  4677. var Mval = 0, j;
  4678. if(+opts.codepage >= 0) set_cp(+opts.codepage);
  4679. for (; ri !== records.length; ++ri) {
  4680. Mval = 0;
  4681. var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
  4682. var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
  4683. var RT=record[0], val;
  4684. if(rstr.length > 0) switch(RT) {
  4685. case 'ID': break; /* header */
  4686. case 'E': break; /* EOF */
  4687. case 'B': break; /* dimensions */
  4688. case 'O': break; /* options? */
  4689. case 'W': break; /* window? */
  4690. case 'P':
  4691. if(record[1].charAt(0) == 'P')
  4692. formats.push(rstr.slice(3).replace(/;;/g, ";"));
  4693. break;
  4694. case 'C':
  4695. var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1;
  4696. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  4697. case 'A': break; // TODO: comment
  4698. case 'X': C = parseInt(record[rj].slice(1))-1; C_seen_X = true; break;
  4699. case 'Y':
  4700. R = parseInt(record[rj].slice(1))-1; if(!C_seen_X) C = 0;
  4701. for(j = arr.length; j <= R; ++j) arr[j] = [];
  4702. break;
  4703. case 'K':
  4704. val = record[rj].slice(1);
  4705. if(val.charAt(0) === '"') val = val.slice(1,val.length - 1);
  4706. else if(val === 'TRUE') val = true;
  4707. else if(val === 'FALSE') val = false;
  4708. else if(!isNaN(fuzzynum(val))) {
  4709. val = fuzzynum(val);
  4710. if(next_cell_format !== null && SSF.is_date(next_cell_format)) val = numdate(val);
  4711. } else if(!isNaN(fuzzydate(val).getDate())) {
  4712. val = parseDate(val);
  4713. }
  4714. if(typeof cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = cptable.utils.decode(opts.codepage, val);
  4715. C_seen_K = true;
  4716. break;
  4717. case 'E':
  4718. C_seen_E = true;
  4719. var formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
  4720. arr[R][C] = [arr[R][C], formula];
  4721. break;
  4722. case 'S':
  4723. C_seen_S = true;
  4724. arr[R][C] = [arr[R][C], "S5S"];
  4725. break;
  4726. case 'G': break; // unknown
  4727. case 'R': _R = parseInt(record[rj].slice(1))-1; break;
  4728. case 'C': _C = parseInt(record[rj].slice(1))-1; break;
  4729. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  4730. }
  4731. if(C_seen_K) {
  4732. if(arr[R][C] && arr[R][C].length == 2) arr[R][C][0] = val;
  4733. else arr[R][C] = val;
  4734. next_cell_format = null;
  4735. }
  4736. if(C_seen_S) {
  4737. if(C_seen_E) throw new Error("SYLK shared formula cannot have own formula");
  4738. var shrbase = _R > -1 && arr[_R][_C];
  4739. if(!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base");
  4740. arr[R][C][1] = shift_formula_str(shrbase[1], {r: R - _R, c: C - _C});
  4741. }
  4742. break;
  4743. case 'F':
  4744. var F_seen = 0;
  4745. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  4746. case 'X': C = parseInt(record[rj].slice(1))-1; ++F_seen; break;
  4747. case 'Y':
  4748. R = parseInt(record[rj].slice(1))-1; /*C = 0;*/
  4749. for(j = arr.length; j <= R; ++j) arr[j] = [];
  4750. break;
  4751. case 'M': Mval = parseInt(record[rj].slice(1)) / 20; break;
  4752. case 'F': break; /* ??? */
  4753. case 'G': break; /* hide grid */
  4754. case 'P':
  4755. next_cell_format = formats[parseInt(record[rj].slice(1))];
  4756. break;
  4757. case 'S': break; /* cell style */
  4758. case 'D': break; /* column */
  4759. case 'N': break; /* font */
  4760. case 'W':
  4761. cw = record[rj].slice(1).split(" ");
  4762. for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
  4763. Mval = parseInt(cw[2], 10);
  4764. colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval}; process_col(colinfo[j-1]);
  4765. } break;
  4766. case 'C': /* default column format */
  4767. C = parseInt(record[rj].slice(1))-1;
  4768. if(!colinfo[C]) colinfo[C] = {};
  4769. break;
  4770. case 'R': /* row properties */
  4771. R = parseInt(record[rj].slice(1))-1;
  4772. if(!rowinfo[R]) rowinfo[R] = {};
  4773. if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
  4774. else if(Mval === 0) rowinfo[R].hidden = true;
  4775. break;
  4776. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  4777. }
  4778. if(F_seen < 1) next_cell_format = null; break;
  4779. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  4780. }
  4781. }
  4782. if(rowinfo.length > 0) sht['!rows'] = rowinfo;
  4783. if(colinfo.length > 0) sht['!cols'] = colinfo;
  4784. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  4785. return [arr, sht];
  4786. }
  4787. function sylk_to_sheet(d, opts) {
  4788. var aoasht = sylk_to_aoa(d, opts);
  4789. var aoa = aoasht[0], ws = aoasht[1];
  4790. var o = aoa_to_sheet(aoa, opts);
  4791. keys(ws).forEach(function(k) { o[k] = ws[k]; });
  4792. return o;
  4793. }
  4794. function sylk_to_workbook(d, opts) { return sheet_to_workbook(sylk_to_sheet(d, opts), opts); }
  4795. function write_ws_cell_sylk(cell, ws, R, C) {
  4796. var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
  4797. switch(cell.t) {
  4798. case 'n':
  4799. o += (cell.v||0);
  4800. if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
  4801. case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
  4802. case 'e': o += cell.w || cell.v; break;
  4803. case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
  4804. case 's': o += '"' + cell.v.replace(/"/g,"") + '"'; break;
  4805. }
  4806. return o;
  4807. }
  4808. function write_ws_cols_sylk(out, cols) {
  4809. cols.forEach(function(col, i) {
  4810. var rec = "F;W" + (i+1) + " " + (i+1) + " ";
  4811. if(col.hidden) rec += "0";
  4812. else {
  4813. if(typeof col.width == 'number' && !col.wpx) col.wpx = width2px(col.width);
  4814. if(typeof col.wpx == 'number' && !col.wch) col.wch = px2char(col.wpx);
  4815. if(typeof col.wch == 'number') rec += Math.round(col.wch);
  4816. }
  4817. if(rec.charAt(rec.length - 1) != " ") out.push(rec);
  4818. });
  4819. }
  4820. function write_ws_rows_sylk(out, rows) {
  4821. rows.forEach(function(row, i) {
  4822. var rec = "F;";
  4823. if(row.hidden) rec += "M0;";
  4824. else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
  4825. else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
  4826. if(rec.length > 2) out.push(rec + "R" + (i+1));
  4827. });
  4828. }
  4829. function sheet_to_sylk(ws, opts) {
  4830. var preamble = ["ID;PWXL;N;E"], o = [];
  4831. var r = safe_decode_range(ws['!ref']), cell;
  4832. var dense = Array.isArray(ws);
  4833. var RS = "\r\n";
  4834. preamble.push("P;PGeneral");
  4835. preamble.push("F;P0;DG0G8;M255");
  4836. if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
  4837. if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);
  4838. preamble.push("B;Y" + (r.e.r - r.s.r + 1) + ";X" + (r.e.c - r.s.c + 1) + ";D" + [r.s.c,r.s.r,r.e.c,r.e.r].join(" "));
  4839. for(var R = r.s.r; R <= r.e.r; ++R) {
  4840. for(var C = r.s.c; C <= r.e.c; ++C) {
  4841. var coord = encode_cell({r:R,c:C});
  4842. cell = dense ? (ws[R]||[])[C]: ws[coord];
  4843. if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
  4844. o.push(write_ws_cell_sylk(cell, ws, R, C, opts));
  4845. }
  4846. }
  4847. return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
  4848. }
  4849. return {
  4850. to_workbook: sylk_to_workbook,
  4851. to_sheet: sylk_to_sheet,
  4852. from_sheet: sheet_to_sylk
  4853. };
  4854. })();
  4855. var DIF = (function() {
  4856. function dif_to_aoa(d, opts) {
  4857. switch(opts.type) {
  4858. case 'base64': return dif_to_aoa_str(Base64.decode(d), opts);
  4859. case 'binary': return dif_to_aoa_str(d, opts);
  4860. case 'buffer': return dif_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  4861. case 'array': return dif_to_aoa_str(cc2str(d), opts);
  4862. }
  4863. throw new Error("Unrecognized type " + opts.type);
  4864. }
  4865. function dif_to_aoa_str(str, opts) {
  4866. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  4867. for (; ri !== records.length; ++ri) {
  4868. if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
  4869. if (R < 0) continue;
  4870. var metadata = records[ri].trim().split(",");
  4871. var type = metadata[0], value = metadata[1];
  4872. ++ri;
  4873. var data = records[ri] || "";
  4874. while(((data.match(/["]/g)||[]).length & 1) && ri < records.length - 1) data += "\n" + records[++ri];
  4875. data = data.trim();
  4876. switch (+type) {
  4877. case -1:
  4878. if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
  4879. else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
  4880. break;
  4881. case 0:
  4882. if(data === 'TRUE') arr[R][C] = true;
  4883. else if(data === 'FALSE') arr[R][C] = false;
  4884. else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
  4885. else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
  4886. else arr[R][C] = value;
  4887. ++C; break;
  4888. case 1:
  4889. data = data.slice(1,data.length-1);
  4890. data = data.replace(/""/g, '"');
  4891. if(DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1);
  4892. arr[R][C++] = data !== '' ? data : null;
  4893. break;
  4894. }
  4895. if (data === 'EOD') break;
  4896. }
  4897. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  4898. return arr;
  4899. }
  4900. function dif_to_sheet(str, opts) { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
  4901. function dif_to_workbook(str, opts) { return sheet_to_workbook(dif_to_sheet(str, opts), opts); }
  4902. var sheet_to_dif = (function() {
  4903. var push_field = function pf(o, topic, v, n, s) {
  4904. o.push(topic);
  4905. o.push(v + "," + n);
  4906. o.push('"' + s.replace(/"/g,'""') + '"');
  4907. };
  4908. var push_value = function po(o, type, v, s) {
  4909. o.push(type + "," + v);
  4910. o.push(type == 1 ? '"' + s.replace(/"/g,'""') + '"' : s);
  4911. };
  4912. return function sheet_to_dif(ws) {
  4913. var o = [];
  4914. var r = safe_decode_range(ws['!ref']), cell;
  4915. var dense = Array.isArray(ws);
  4916. push_field(o, "TABLE", 0, 1, "sheetjs");
  4917. push_field(o, "VECTORS", 0, r.e.r - r.s.r + 1,"");
  4918. push_field(o, "TUPLES", 0, r.e.c - r.s.c + 1,"");
  4919. push_field(o, "DATA", 0, 0,"");
  4920. for(var R = r.s.r; R <= r.e.r; ++R) {
  4921. push_value(o, -1, 0, "BOT");
  4922. for(var C = r.s.c; C <= r.e.c; ++C) {
  4923. var coord = encode_cell({r:R,c:C});
  4924. cell = dense ? (ws[R]||[])[C] : ws[coord];
  4925. if(!cell) { push_value(o, 1, 0, ""); continue;}
  4926. switch(cell.t) {
  4927. case 'n':
  4928. var val = DIF_XL ? cell.w : cell.v;
  4929. if(!val && cell.v != null) val = cell.v;
  4930. if(val == null) {
  4931. if(DIF_XL && cell.f && !cell.F) push_value(o, 1, 0, "=" + cell.f);
  4932. else push_value(o, 1, 0, "");
  4933. }
  4934. else push_value(o, 0, val, "V");
  4935. break;
  4936. case 'b':
  4937. push_value(o, 0, cell.v ? 1 : 0, cell.v ? "TRUE" : "FALSE");
  4938. break;
  4939. case 's':
  4940. push_value(o, 1, 0, (!DIF_XL || isNaN(cell.v)) ? cell.v : '="' + cell.v + '"');
  4941. break;
  4942. case 'd':
  4943. if(!cell.w) cell.w = SSF.format(cell.z || SSF._table[14], datenum(parseDate(cell.v)));
  4944. if(DIF_XL) push_value(o, 0, cell.w, "V");
  4945. else push_value(o, 1, 0, cell.w);
  4946. break;
  4947. default: push_value(o, 1, 0, "");
  4948. }
  4949. }
  4950. }
  4951. push_value(o, -1, 0, "EOD");
  4952. var RS = "\r\n";
  4953. var oo = o.join(RS);
  4954. //while((oo.length & 0x7F) != 0) oo += "\0";
  4955. return oo;
  4956. };
  4957. })();
  4958. return {
  4959. to_workbook: dif_to_workbook,
  4960. to_sheet: dif_to_sheet,
  4961. from_sheet: sheet_to_dif
  4962. };
  4963. })();
  4964. var ETH = (function() {
  4965. function decode(s) { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
  4966. function encode(s) { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }
  4967. function eth_to_aoa(str, opts) {
  4968. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  4969. for (; ri !== records.length; ++ri) {
  4970. var record = records[ri].trim().split(":");
  4971. if(record[0] !== 'cell') continue;
  4972. var addr = decode_cell(record[1]);
  4973. if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
  4974. R = addr.r; C = addr.c;
  4975. switch(record[2]) {
  4976. case 't': arr[R][C] = decode(record[3]); break;
  4977. case 'v': arr[R][C] = +record[3]; break;
  4978. case 'vtf': var _f = record[record.length - 1];
  4979. /* falls through */
  4980. case 'vtc':
  4981. switch(record[3]) {
  4982. case 'nl': arr[R][C] = +record[4] ? true : false; break;
  4983. default: arr[R][C] = +record[4]; break;
  4984. }
  4985. if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
  4986. }
  4987. }
  4988. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  4989. return arr;
  4990. }
  4991. function eth_to_sheet(d, opts) { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
  4992. function eth_to_workbook(d, opts) { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }
  4993. var header = [
  4994. "socialcalc:version:1.5",
  4995. "MIME-Version: 1.0",
  4996. "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  4997. ].join("\n");
  4998. var sep = [
  4999. "--SocialCalcSpreadsheetControlSave",
  5000. "Content-type: text/plain; charset=UTF-8"
  5001. ].join("\n") + "\n";
  5002. /* TODO: the other parts */
  5003. var meta = [
  5004. "# SocialCalc Spreadsheet Control Save",
  5005. "part:sheet"
  5006. ].join("\n");
  5007. var end = "--SocialCalcSpreadsheetControlSave--";
  5008. function sheet_to_eth_data(ws) {
  5009. if(!ws || !ws['!ref']) return "";
  5010. var o = [], oo = [], cell, coord = "";
  5011. var r = decode_range(ws['!ref']);
  5012. var dense = Array.isArray(ws);
  5013. for(var R = r.s.r; R <= r.e.r; ++R) {
  5014. for(var C = r.s.c; C <= r.e.c; ++C) {
  5015. coord = encode_cell({r:R,c:C});
  5016. cell = dense ? (ws[R]||[])[C] : ws[coord];
  5017. if(!cell || cell.v == null || cell.t === 'z') continue;
  5018. oo = ["cell", coord, 't'];
  5019. switch(cell.t) {
  5020. case 's': case 'str': oo.push(encode(cell.v)); break;
  5021. case 'n':
  5022. if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
  5023. else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
  5024. break;
  5025. case 'b':
  5026. oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
  5027. oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
  5028. break;
  5029. case 'd':
  5030. var t = datenum(parseDate(cell.v));
  5031. oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
  5032. oo[5] = cell.w || SSF.format(cell.z || SSF._table[14], t);
  5033. break;
  5034. case 'e': continue;
  5035. }
  5036. o.push(oo.join(":"));
  5037. }
  5038. }
  5039. o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
  5040. o.push("valueformat:1:text-wiki");
  5041. //o.push("copiedfrom:" + ws['!ref']); // clipboard only
  5042. return o.join("\n");
  5043. }
  5044. function sheet_to_eth(ws) {
  5045. return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
  5046. // return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
  5047. }
  5048. return {
  5049. to_workbook: eth_to_workbook,
  5050. to_sheet: eth_to_sheet,
  5051. from_sheet: sheet_to_eth
  5052. };
  5053. })();
  5054. var PRN = (function() {
  5055. function set_text_arr(data, arr, R, C, o) {
  5056. if(o.raw) arr[R][C] = data;
  5057. else if(data === ""){/* empty */}
  5058. else if(data === 'TRUE') arr[R][C] = true;
  5059. else if(data === 'FALSE') arr[R][C] = false;
  5060. else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
  5061. else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
  5062. else arr[R][C] = data;
  5063. }
  5064. function prn_to_aoa_str(f, opts) {
  5065. var o = opts || {};
  5066. var arr = ([]);
  5067. if(!f || f.length === 0) return arr;
  5068. var lines = f.split(/[\r\n]/);
  5069. var L = lines.length - 1;
  5070. while(L >= 0 && lines[L].length === 0) --L;
  5071. var start = 10, idx = 0;
  5072. var R = 0;
  5073. for(; R <= L; ++R) {
  5074. idx = lines[R].indexOf(" ");
  5075. if(idx == -1) idx = lines[R].length; else idx++;
  5076. start = Math.max(start, idx);
  5077. }
  5078. for(R = 0; R <= L; ++R) {
  5079. arr[R] = [];
  5080. /* TODO: confirm that widths are always 10 */
  5081. var C = 0;
  5082. set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
  5083. for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
  5084. set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
  5085. }
  5086. if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
  5087. return arr;
  5088. }
  5089. // List of accepted CSV separators
  5090. var guess_seps = {
  5091. 0x2C: ',',
  5092. 0x09: "\t",
  5093. 0x3B: ';',
  5094. 0x7C: '|'
  5095. };
  5096. // CSV separator weights to be used in case of equal numbers
  5097. var guess_sep_weights = {
  5098. 0x2C: 3,
  5099. 0x09: 2,
  5100. 0x3B: 1,
  5101. 0x7C: 0
  5102. };
  5103. function guess_sep(str) {
  5104. var cnt = {}, instr = false, end = 0, cc = 0;
  5105. for(;end < str.length;++end) {
  5106. if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
  5107. else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
  5108. }
  5109. cc = [];
  5110. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  5111. cc.push([ cnt[end], end ]);
  5112. }
  5113. if ( !cc.length ) {
  5114. cnt = guess_sep_weights;
  5115. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  5116. cc.push([ cnt[end], end ]);
  5117. }
  5118. }
  5119. cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });
  5120. return guess_seps[cc.pop()[1]] || 0x2C;
  5121. }
  5122. function dsv_to_sheet_str(str, opts) {
  5123. var o = opts || {};
  5124. var sep = "";
  5125. if(DENSE != null && o.dense == null) o.dense = DENSE;
  5126. var ws = o.dense ? ([]) : ({});
  5127. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  5128. if(str.slice(0,4) == "sep=") {
  5129. // If the line ends in \r\n
  5130. if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
  5131. sep = str.charAt(4); str = str.slice(7);
  5132. }
  5133. // If line ends in \r OR \n
  5134. else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
  5135. sep = str.charAt(4); str = str.slice(6);
  5136. }
  5137. else sep = guess_sep(str.slice(0,1024));
  5138. }
  5139. else if(o && o.FS) sep = o.FS;
  5140. else sep = guess_sep(str.slice(0,1024));
  5141. var R = 0, C = 0, v = 0;
  5142. var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0, startcc=str.charCodeAt(0);
  5143. str = str.replace(/\r\n/mg, "\n");
  5144. var _re = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
  5145. function finish_cell() {
  5146. var s = str.slice(start, end);
  5147. var cell = ({});
  5148. if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
  5149. if(s.length === 0) cell.t = 'z';
  5150. else if(o.raw) { cell.t = 's'; cell.v = s; }
  5151. else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
  5152. else if(s.charCodeAt(0) == 0x3D) {
  5153. if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
  5154. else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
  5155. else { cell.t = 's'; cell.v = s; } }
  5156. else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
  5157. else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
  5158. else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
  5159. else if(!isNaN(fuzzydate(s).getDate()) || _re && s.match(_re)) {
  5160. cell.z = o.dateNF || SSF._table[14];
  5161. var k = 0;
  5162. if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; }
  5163. if(o.cellDates) { cell.t = 'd'; cell.v = parseDate(s, k); }
  5164. else { cell.t = 'n'; cell.v = datenum(parseDate(s, k)); }
  5165. if(o.cellText !== false) cell.w = SSF.format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
  5166. if(!o.cellNF) delete cell.z;
  5167. } else {
  5168. cell.t = 's';
  5169. cell.v = s;
  5170. }
  5171. if(cell.t == 'z'){}
  5172. else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
  5173. else ws[encode_cell({c:C,r:R})] = cell;
  5174. start = end+1; startcc = str.charCodeAt(start);
  5175. if(range.e.c < C) range.e.c = C;
  5176. if(range.e.r < R) range.e.r = R;
  5177. if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
  5178. }
  5179. outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
  5180. case 0x22: if(startcc === 0x22) instr = !instr; break;
  5181. case sepcc: case 0x0a: case 0x0d: if(!instr && finish_cell()) break outer; break;
  5182. default: break;
  5183. }
  5184. if(end - start > 0) finish_cell();
  5185. ws['!ref'] = encode_range(range);
  5186. return ws;
  5187. }
  5188. function prn_to_sheet_str(str, opts) {
  5189. if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
  5190. if(opts.FS) return dsv_to_sheet_str(str, opts);
  5191. if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
  5192. if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
  5193. return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
  5194. }
  5195. function prn_to_sheet(d, opts) {
  5196. var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
  5197. switch(opts.type) {
  5198. case 'base64': str = Base64.decode(d); break;
  5199. case 'binary': str = d; break;
  5200. case 'buffer':
  5201. if(opts.codepage == 65001) str = d.toString('utf8'); // TODO: test if buf
  5202. else if(opts.codepage && typeof cptable !== 'undefined') str = cptable.utils.decode(opts.codepage, d);
  5203. else str = has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d);
  5204. break;
  5205. case 'array': str = cc2str(d); break;
  5206. case 'string': str = d; break;
  5207. default: throw new Error("Unrecognized type " + opts.type);
  5208. }
  5209. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
  5210. else if(opts.type != 'string' && opts.codepage == 65001) str = utf8read(str);
  5211. else if((opts.type == 'binary') && typeof cptable !== 'undefined' && opts.codepage) str = cptable.utils.decode(opts.codepage, cptable.utils.encode(28591,str));
  5212. if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
  5213. return prn_to_sheet_str(str, opts);
  5214. }
  5215. function prn_to_workbook(d, opts) { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }
  5216. function sheet_to_prn(ws) {
  5217. var o = [];
  5218. var r = safe_decode_range(ws['!ref']), cell;
  5219. var dense = Array.isArray(ws);
  5220. for(var R = r.s.r; R <= r.e.r; ++R) {
  5221. var oo = [];
  5222. for(var C = r.s.c; C <= r.e.c; ++C) {
  5223. var coord = encode_cell({r:R,c:C});
  5224. cell = dense ? (ws[R]||[])[C] : ws[coord];
  5225. if(!cell || cell.v == null) { oo.push(" "); continue; }
  5226. var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
  5227. while(w.length < 10) w += " ";
  5228. oo.push(w + (C === 0 ? " " : ""));
  5229. }
  5230. o.push(oo.join(""));
  5231. }
  5232. return o.join("\n");
  5233. }
  5234. return {
  5235. to_workbook: prn_to_workbook,
  5236. to_sheet: prn_to_sheet,
  5237. from_sheet: sheet_to_prn
  5238. };
  5239. })();
  5240. /* Excel defaults to SYLK but warns if data is not valid */
  5241. function read_wb_ID(d, opts) {
  5242. var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
  5243. try {
  5244. var out = SYLK.to_workbook(d, o);
  5245. o.WTF = OLD_WTF;
  5246. return out;
  5247. } catch(e) {
  5248. o.WTF = OLD_WTF;
  5249. if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
  5250. return PRN.to_workbook(d, opts);
  5251. }
  5252. }
  5253. /* 18.4.7 rPr CT_RPrElt */
  5254. function parse_rpr(rpr) {
  5255. var font = {}, m = rpr.match(tagregex), i = 0;
  5256. var pass = false;
  5257. if(m) for(;i!=m.length; ++i) {
  5258. var y = parsexmltag(m[i]);
  5259. switch(y[0].replace(/\w*:/g,"")) {
  5260. /* 18.8.12 condense CT_BooleanProperty */
  5261. /* ** not required . */
  5262. case '<condense': break;
  5263. /* 18.8.17 extend CT_BooleanProperty */
  5264. /* ** not required . */
  5265. case '<extend': break;
  5266. /* 18.8.36 shadow CT_BooleanProperty */
  5267. /* ** not required . */
  5268. case '<shadow':
  5269. if(!y.val) break;
  5270. /* falls through */
  5271. case '<shadow>':
  5272. case '<shadow/>': font.shadow = 1; break;
  5273. case '</shadow>': break;
  5274. /* 18.4.1 charset CT_IntProperty TODO */
  5275. case '<charset':
  5276. if(y.val == '1') break;
  5277. font.cp = CS2CP[parseInt(y.val, 10)];
  5278. break;
  5279. /* 18.4.2 outline CT_BooleanProperty TODO */
  5280. case '<outline':
  5281. if(!y.val) break;
  5282. /* falls through */
  5283. case '<outline>':
  5284. case '<outline/>': font.outline = 1; break;
  5285. case '</outline>': break;
  5286. /* 18.4.5 rFont CT_FontName */
  5287. case '<rFont': font.name = y.val; break;
  5288. /* 18.4.11 sz CT_FontSize */
  5289. case '<sz': font.sz = y.val; break;
  5290. /* 18.4.10 strike CT_BooleanProperty */
  5291. case '<strike':
  5292. if(!y.val) break;
  5293. /* falls through */
  5294. case '<strike>':
  5295. case '<strike/>': font.strike = 1; break;
  5296. case '</strike>': break;
  5297. /* 18.4.13 u CT_UnderlineProperty */
  5298. case '<u':
  5299. if(!y.val) break;
  5300. switch(y.val) {
  5301. case 'double': font.uval = "double"; break;
  5302. case 'singleAccounting': font.uval = "single-accounting"; break;
  5303. case 'doubleAccounting': font.uval = "double-accounting"; break;
  5304. }
  5305. /* falls through */
  5306. case '<u>':
  5307. case '<u/>': font.u = 1; break;
  5308. case '</u>': break;
  5309. /* 18.8.2 b */
  5310. case '<b':
  5311. if(y.val == '0') break;
  5312. /* falls through */
  5313. case '<b>':
  5314. case '<b/>': font.b = 1; break;
  5315. case '</b>': break;
  5316. /* 18.8.26 i */
  5317. case '<i':
  5318. if(y.val == '0') break;
  5319. /* falls through */
  5320. case '<i>':
  5321. case '<i/>': font.i = 1; break;
  5322. case '</i>': break;
  5323. /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
  5324. case '<color':
  5325. if(y.rgb) font.color = y.rgb.slice(2,8);
  5326. break;
  5327. /* 18.8.18 family ST_FontFamily */
  5328. case '<family': font.family = y.val; break;
  5329. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
  5330. case '<vertAlign': font.valign = y.val; break;
  5331. /* 18.8.35 scheme CT_FontScheme TODO */
  5332. case '<scheme': break;
  5333. /* 18.2.10 extLst CT_ExtensionList ? */
  5334. case '<extLst': case '<extLst>': case '</extLst>': break;
  5335. case '<ext': pass = true; break;
  5336. case '</ext>': pass = false; break;
  5337. default:
  5338. if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
  5339. }
  5340. }
  5341. return font;
  5342. }
  5343. var parse_rs = (function() {
  5344. var tregex = matchtag("t"), rpregex = matchtag("rPr");
  5345. /* 18.4.4 r CT_RElt */
  5346. function parse_r(r) {
  5347. /* 18.4.12 t ST_Xstring */
  5348. var t = r.match(tregex)/*, cp = 65001*/;
  5349. if(!t) return {t:"s", v:""};
  5350. var o = ({t:'s', v:unescapexml(t[1])});
  5351. var rpr = r.match(rpregex);
  5352. if(rpr) o.s = parse_rpr(rpr[1]);
  5353. return o;
  5354. }
  5355. var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  5356. return function parse_rs(rs) {
  5357. return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
  5358. };
  5359. })();
  5360. /* Parse a list of <r> tags */
  5361. var rs_to_html = (function parse_rs_factory() {
  5362. var nlregex = /(\r\n|\n)/g;
  5363. function parse_rpr2(font, intro, outro) {
  5364. var style = [];
  5365. if(font.u) style.push("text-decoration: underline;");
  5366. if(font.uval) style.push("text-underline-style:" + font.uval + ";");
  5367. if(font.sz) style.push("font-size:" + font.sz + "pt;");
  5368. if(font.outline) style.push("text-effect: outline;");
  5369. if(font.shadow) style.push("text-shadow: auto;");
  5370. intro.push('<span style="' + style.join("") + '">');
  5371. if(font.b) { intro.push("<b>"); outro.push("</b>"); }
  5372. if(font.i) { intro.push("<i>"); outro.push("</i>"); }
  5373. if(font.strike) { intro.push("<s>"); outro.push("</s>"); }
  5374. var align = font.valign || "";
  5375. if(align == "superscript" || align == "super") align = "sup";
  5376. else if(align == "subscript") align = "sub";
  5377. if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }
  5378. outro.push("</span>");
  5379. return font;
  5380. }
  5381. /* 18.4.4 r CT_RElt */
  5382. function r_to_html(r) {
  5383. var terms = [[],r.v,[]];
  5384. if(!r.v) return "";
  5385. if(r.s) parse_rpr2(r.s, terms[0], terms[2]);
  5386. return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
  5387. }
  5388. return function parse_rs(rs) {
  5389. return rs.map(r_to_html).join("");
  5390. };
  5391. })();
  5392. /* 18.4.8 si CT_Rst */
  5393. var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
  5394. var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
  5395. function parse_si(x, opts) {
  5396. var html = opts ? opts.cellHTML : true;
  5397. var z = {};
  5398. if(!x) return { t: "" };
  5399. //var y;
  5400. /* 18.4.12 t ST_Xstring (Plaintext String) */
  5401. // TODO: is whitespace actually valid here?
  5402. if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
  5403. z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""));
  5404. z.r = utf8read(x);
  5405. if(html) z.h = escapehtml(z.t);
  5406. }
  5407. /* 18.4.4 r CT_RElt (Rich Text Run) */
  5408. else if((/*y = */x.match(sirregex))) {
  5409. z.r = utf8read(x);
  5410. z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")));
  5411. if(html) z.h = rs_to_html(parse_rs(z.r));
  5412. }
  5413. /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
  5414. /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
  5415. return z;
  5416. }
  5417. /* 18.4 Shared String Table */
  5418. var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
  5419. var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
  5420. var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
  5421. function parse_sst_xml(data, opts) {
  5422. var s = ([]), ss = "";
  5423. if(!data) return s;
  5424. /* 18.4.9 sst CT_Sst */
  5425. var sst = data.match(sstr0);
  5426. if(sst) {
  5427. ss = sst[2].replace(sstr1,"").split(sstr2);
  5428. for(var i = 0; i != ss.length; ++i) {
  5429. var o = parse_si(ss[i].trim(), opts);
  5430. if(o != null) s[s.length] = o;
  5431. }
  5432. sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
  5433. }
  5434. return s;
  5435. }
  5436. RELS.SST = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
  5437. var straywsregex = /^\s|\s$|[\t\n\r]/;
  5438. function write_sst_xml(sst, opts) {
  5439. if(!opts.bookSST) return "";
  5440. var o = [XML_HEADER];
  5441. o[o.length] = (writextag('sst', null, {
  5442. xmlns: XMLNS.main[0],
  5443. count: sst.Count,
  5444. uniqueCount: sst.Unique
  5445. }));
  5446. for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
  5447. var s = sst[i];
  5448. var sitag = "<si>";
  5449. if(s.r) sitag += s.r;
  5450. else {
  5451. sitag += "<t";
  5452. if(!s.t) s.t = "";
  5453. if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
  5454. sitag += ">" + escapexml(s.t) + "</t>";
  5455. }
  5456. sitag += "</si>";
  5457. o[o.length] = (sitag);
  5458. }
  5459. if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
  5460. return o.join("");
  5461. }
  5462. function hex2RGB(h) {
  5463. var o = h.slice(h[0]==="#"?1:0).slice(0,6);
  5464. return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
  5465. }
  5466. function rgb2Hex(rgb) {
  5467. for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
  5468. return o.toString(16).toUpperCase().slice(1);
  5469. }
  5470. function rgb2HSL(rgb) {
  5471. var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
  5472. var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
  5473. if(C === 0) return [0, 0, R];
  5474. var H6 = 0, S = 0, L2 = (M + m);
  5475. S = C / (L2 > 1 ? 2 - L2 : L2);
  5476. switch(M){
  5477. case R: H6 = ((G - B) / C + 6)%6; break;
  5478. case G: H6 = ((B - R) / C + 2); break;
  5479. case B: H6 = ((R - G) / C + 4); break;
  5480. }
  5481. return [H6 / 6, S, L2 / 2];
  5482. }
  5483. function hsl2RGB(hsl){
  5484. var H = hsl[0], S = hsl[1], L = hsl[2];
  5485. var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
  5486. var rgb = [m,m,m], h6 = 6*H;
  5487. var X;
  5488. if(S !== 0) switch(h6|0) {
  5489. case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
  5490. case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
  5491. case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
  5492. case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
  5493. case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
  5494. case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
  5495. }
  5496. for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
  5497. return rgb;
  5498. }
  5499. /* 18.8.3 bgColor tint algorithm */
  5500. function rgb_tint(hex, tint) {
  5501. if(tint === 0) return hex;
  5502. var hsl = rgb2HSL(hex2RGB(hex));
  5503. if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  5504. else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  5505. return rgb2Hex(hsl2RGB(hsl));
  5506. }
  5507. /* 18.3.1.13 width calculations */
  5508. /* [MS-OI29500] 2.1.595 Column Width & Formatting */
  5509. var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
  5510. function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
  5511. function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
  5512. function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
  5513. //function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
  5514. //function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
  5515. function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
  5516. /* XLSX/XLSB/XLS specify width in units of MDW */
  5517. function find_mdw_colw(collw) {
  5518. var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  5519. if(delta > 0.005) for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) if(Math.abs(collw - cycle_width(collw)) <= delta) { delta = Math.abs(collw - cycle_width(collw)); _MDW = MDW; }
  5520. MDW = _MDW;
  5521. }
  5522. /* XLML specifies width in terms of pixels */
  5523. /*function find_mdw_wpx(wpx) {
  5524. var delta = Infinity, guess = 0, _MDW = MIN_MDW;
  5525. for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
  5526. guess = char2width_(px2char_(wpx))*256;
  5527. guess = (guess) % 1;
  5528. if(guess > 0.5) guess--;
  5529. if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
  5530. }
  5531. MDW = _MDW;
  5532. }*/
  5533. function process_col(coll) {
  5534. if(coll.width) {
  5535. coll.wpx = width2px(coll.width);
  5536. coll.wch = px2char(coll.wpx);
  5537. coll.MDW = MDW;
  5538. } else if(coll.wpx) {
  5539. coll.wch = px2char(coll.wpx);
  5540. coll.width = char2width(coll.wch);
  5541. coll.MDW = MDW;
  5542. } else if(typeof coll.wch == 'number') {
  5543. coll.width = char2width(coll.wch);
  5544. coll.wpx = width2px(coll.width);
  5545. coll.MDW = MDW;
  5546. }
  5547. if(coll.customWidth) delete coll.customWidth;
  5548. }
  5549. var DEF_PPI = 96, PPI = DEF_PPI;
  5550. function px2pt(px) { return px * 96 / PPI; }
  5551. function pt2px(pt) { return pt * PPI / 96; }
  5552. /* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
  5553. var XLMLPatternTypeMap = {
  5554. "None": "none",
  5555. "Solid": "solid",
  5556. "Gray50": "mediumGray",
  5557. "Gray75": "darkGray",
  5558. "Gray25": "lightGray",
  5559. "HorzStripe": "darkHorizontal",
  5560. "VertStripe": "darkVertical",
  5561. "ReverseDiagStripe": "darkDown",
  5562. "DiagStripe": "darkUp",
  5563. "DiagCross": "darkGrid",
  5564. "ThickDiagCross": "darkTrellis",
  5565. "ThinHorzStripe": "lightHorizontal",
  5566. "ThinVertStripe": "lightVertical",
  5567. "ThinReverseDiagStripe": "lightDown",
  5568. "ThinHorzCross": "lightGrid"
  5569. };
  5570. /* 18.8.5 borders CT_Borders */
  5571. function parse_borders(t, styles, themes, opts) {
  5572. styles.Borders = [];
  5573. var border = {};
  5574. var pass = false;
  5575. (t[0].match(tagregex)||[]).forEach(function(x) {
  5576. var y = parsexmltag(x);
  5577. switch(strip_ns(y[0])) {
  5578. case '<borders': case '<borders>': case '</borders>': break;
  5579. /* 18.8.4 border CT_Border */
  5580. case '<border': case '<border>': case '<border/>':
  5581. border = {};
  5582. if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
  5583. if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
  5584. styles.Borders.push(border);
  5585. break;
  5586. case '</border>': break;
  5587. /* note: not in spec, appears to be CT_BorderPr */
  5588. case '<left/>': break;
  5589. case '<left': case '<left>': break;
  5590. case '</left>': break;
  5591. /* note: not in spec, appears to be CT_BorderPr */
  5592. case '<right/>': break;
  5593. case '<right': case '<right>': break;
  5594. case '</right>': break;
  5595. /* 18.8.43 top CT_BorderPr */
  5596. case '<top/>': break;
  5597. case '<top': case '<top>': break;
  5598. case '</top>': break;
  5599. /* 18.8.6 bottom CT_BorderPr */
  5600. case '<bottom/>': break;
  5601. case '<bottom': case '<bottom>': break;
  5602. case '</bottom>': break;
  5603. /* 18.8.13 diagonal CT_BorderPr */
  5604. case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
  5605. case '</diagonal>': break;
  5606. /* 18.8.25 horizontal CT_BorderPr */
  5607. case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
  5608. case '</horizontal>': break;
  5609. /* 18.8.44 vertical CT_BorderPr */
  5610. case '<vertical': case '<vertical>': case '<vertical/>': break;
  5611. case '</vertical>': break;
  5612. /* 18.8.37 start CT_BorderPr */
  5613. case '<start': case '<start>': case '<start/>': break;
  5614. case '</start>': break;
  5615. /* 18.8.16 end CT_BorderPr */
  5616. case '<end': case '<end>': case '<end/>': break;
  5617. case '</end>': break;
  5618. /* 18.8.? color CT_Color */
  5619. case '<color': case '<color>':
  5620. break;
  5621. case '<color/>': case '</color>': break;
  5622. /* 18.2.10 extLst CT_ExtensionList ? */
  5623. case '<extLst': case '<extLst>': case '</extLst>': break;
  5624. case '<ext': pass = true; break;
  5625. case '</ext>': pass = false; break;
  5626. default: if(opts && opts.WTF) {
  5627. if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
  5628. }
  5629. }
  5630. });
  5631. }
  5632. /* 18.8.21 fills CT_Fills */
  5633. function parse_fills(t, styles, themes, opts) {
  5634. styles.Fills = [];
  5635. var fill = {};
  5636. var pass = false;
  5637. (t[0].match(tagregex)||[]).forEach(function(x) {
  5638. var y = parsexmltag(x);
  5639. switch(strip_ns(y[0])) {
  5640. case '<fills': case '<fills>': case '</fills>': break;
  5641. /* 18.8.20 fill CT_Fill */
  5642. case '<fill>': case '<fill': case '<fill/>':
  5643. fill = {}; styles.Fills.push(fill); break;
  5644. case '</fill>': break;
  5645. /* 18.8.24 gradientFill CT_GradientFill */
  5646. case '<gradientFill>': break;
  5647. case '<gradientFill':
  5648. case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;
  5649. /* 18.8.32 patternFill CT_PatternFill */
  5650. case '<patternFill': case '<patternFill>':
  5651. if(y.patternType) fill.patternType = y.patternType;
  5652. break;
  5653. case '<patternFill/>': case '</patternFill>': break;
  5654. /* 18.8.3 bgColor CT_Color */
  5655. case '<bgColor':
  5656. if(!fill.bgColor) fill.bgColor = {};
  5657. if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
  5658. if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
  5659. if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
  5660. /* Excel uses ARGB strings */
  5661. if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
  5662. break;
  5663. case '<bgColor/>': case '</bgColor>': break;
  5664. /* 18.8.19 fgColor CT_Color */
  5665. case '<fgColor':
  5666. if(!fill.fgColor) fill.fgColor = {};
  5667. if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
  5668. if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
  5669. /* Excel uses ARGB strings */
  5670. if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
  5671. break;
  5672. case '<fgColor/>': case '</fgColor>': break;
  5673. /* 18.8.38 stop CT_GradientStop */
  5674. case '<stop': case '<stop/>': break;
  5675. case '</stop>': break;
  5676. /* 18.8.? color CT_Color */
  5677. case '<color': case '<color/>': break;
  5678. case '</color>': break;
  5679. /* 18.2.10 extLst CT_ExtensionList ? */
  5680. case '<extLst': case '<extLst>': case '</extLst>': break;
  5681. case '<ext': pass = true; break;
  5682. case '</ext>': pass = false; break;
  5683. default: if(opts && opts.WTF) {
  5684. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
  5685. }
  5686. }
  5687. });
  5688. }
  5689. /* 18.8.23 fonts CT_Fonts */
  5690. function parse_fonts(t, styles, themes, opts) {
  5691. styles.Fonts = [];
  5692. var font = {};
  5693. var pass = false;
  5694. (t[0].match(tagregex)||[]).forEach(function(x) {
  5695. var y = parsexmltag(x);
  5696. switch(strip_ns(y[0])) {
  5697. case '<fonts': case '<fonts>': case '</fonts>': break;
  5698. /* 18.8.22 font CT_Font */
  5699. case '<font': case '<font>': break;
  5700. case '</font>': case '<font/>':
  5701. styles.Fonts.push(font);
  5702. font = {};
  5703. break;
  5704. /* 18.8.29 name CT_FontName */
  5705. case '<name': if(y.val) font.name = utf8read(y.val); break;
  5706. case '<name/>': case '</name>': break;
  5707. /* 18.8.2 b CT_BooleanProperty */
  5708. case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
  5709. case '<b/>': font.bold = 1; break;
  5710. /* 18.8.26 i CT_BooleanProperty */
  5711. case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
  5712. case '<i/>': font.italic = 1; break;
  5713. /* 18.4.13 u CT_UnderlineProperty */
  5714. case '<u':
  5715. switch(y.val) {
  5716. case "none": font.underline = 0x00; break;
  5717. case "single": font.underline = 0x01; break;
  5718. case "double": font.underline = 0x02; break;
  5719. case "singleAccounting": font.underline = 0x21; break;
  5720. case "doubleAccounting": font.underline = 0x22; break;
  5721. } break;
  5722. case '<u/>': font.underline = 1; break;
  5723. /* 18.4.10 strike CT_BooleanProperty */
  5724. case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
  5725. case '<strike/>': font.strike = 1; break;
  5726. /* 18.4.2 outline CT_BooleanProperty */
  5727. case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
  5728. case '<outline/>': font.outline = 1; break;
  5729. /* 18.8.36 shadow CT_BooleanProperty */
  5730. case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
  5731. case '<shadow/>': font.shadow = 1; break;
  5732. /* 18.8.12 condense CT_BooleanProperty */
  5733. case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
  5734. case '<condense/>': font.condense = 1; break;
  5735. /* 18.8.17 extend CT_BooleanProperty */
  5736. case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
  5737. case '<extend/>': font.extend = 1; break;
  5738. /* 18.4.11 sz CT_FontSize */
  5739. case '<sz': if(y.val) font.sz = +y.val; break;
  5740. case '<sz/>': case '</sz>': break;
  5741. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
  5742. case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
  5743. case '<vertAlign/>': case '</vertAlign>': break;
  5744. /* 18.8.18 family CT_FontFamily */
  5745. case '<family': if(y.val) font.family = parseInt(y.val,10); break;
  5746. case '<family/>': case '</family>': break;
  5747. /* 18.8.35 scheme CT_FontScheme */
  5748. case '<scheme': if(y.val) font.scheme = y.val; break;
  5749. case '<scheme/>': case '</scheme>': break;
  5750. /* 18.4.1 charset CT_IntProperty */
  5751. case '<charset':
  5752. if(y.val == '1') break;
  5753. y.codepage = CS2CP[parseInt(y.val, 10)];
  5754. break;
  5755. /* 18.?.? color CT_Color */
  5756. case '<color':
  5757. if(!font.color) font.color = {};
  5758. if(y.auto) font.color.auto = parsexmlbool(y.auto);
  5759. if(y.rgb) font.color.rgb = y.rgb.slice(-6);
  5760. else if(y.indexed) {
  5761. font.color.index = parseInt(y.indexed, 10);
  5762. var icv = XLSIcv[font.color.index];
  5763. if(font.color.index == 81) icv = XLSIcv[1];
  5764. if(!icv) icv = XLSIcv[1]; //throw new Error(x); // note: 206 is valid
  5765. font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
  5766. } else if(y.theme) {
  5767. font.color.theme = parseInt(y.theme, 10);
  5768. if(y.tint) font.color.tint = parseFloat(y.tint);
  5769. if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
  5770. font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
  5771. }
  5772. }
  5773. break;
  5774. case '<color/>': case '</color>': break;
  5775. /* note: sometimes mc:AlternateContent appears bare */
  5776. case '<AlternateContent': pass = true; break;
  5777. case '</AlternateContent>': pass = false; break;
  5778. /* 18.2.10 extLst CT_ExtensionList ? */
  5779. case '<extLst': case '<extLst>': case '</extLst>': break;
  5780. case '<ext': pass = true; break;
  5781. case '</ext>': pass = false; break;
  5782. default: if(opts && opts.WTF) {
  5783. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
  5784. }
  5785. }
  5786. });
  5787. }
  5788. /* 18.8.31 numFmts CT_NumFmts */
  5789. function parse_numFmts(t, styles, opts) {
  5790. styles.NumberFmt = [];
  5791. var k/*Array<number>*/ = (keys(SSF._table));
  5792. for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = SSF._table[k[i]];
  5793. var m = t[0].match(tagregex);
  5794. if(!m) return;
  5795. for(i=0; i < m.length; ++i) {
  5796. var y = parsexmltag(m[i]);
  5797. switch(strip_ns(y[0])) {
  5798. case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
  5799. case '<numFmt': {
  5800. var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
  5801. styles.NumberFmt[j] = f;
  5802. if(j>0) {
  5803. if(j > 0x188) {
  5804. for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
  5805. styles.NumberFmt[j] = f;
  5806. }
  5807. SSF.load(f,j);
  5808. }
  5809. } break;
  5810. case '</numFmt>': break;
  5811. default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
  5812. }
  5813. }
  5814. }
  5815. function write_numFmts(NF) {
  5816. var o = ["<numFmts>"];
  5817. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  5818. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) o[o.length] = (writextag('numFmt',null,{numFmtId:i,formatCode:escapexml(NF[i])}));
  5819. });
  5820. if(o.length === 1) return "";
  5821. o[o.length] = ("</numFmts>");
  5822. o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
  5823. return o.join("");
  5824. }
  5825. /* 18.8.10 cellXfs CT_CellXfs */
  5826. var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
  5827. var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
  5828. function parse_cellXfs(t, styles, opts) {
  5829. styles.CellXf = [];
  5830. var xf;
  5831. var pass = false;
  5832. (t[0].match(tagregex)||[]).forEach(function(x) {
  5833. var y = parsexmltag(x), i = 0;
  5834. switch(strip_ns(y[0])) {
  5835. case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
  5836. /* 18.8.45 xf CT_Xf */
  5837. case '<xf': case '<xf/>':
  5838. xf = y;
  5839. delete xf[0];
  5840. for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
  5841. xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
  5842. for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
  5843. xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
  5844. if(styles.NumberFmt && xf.numFmtId > 0x188) {
  5845. for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
  5846. }
  5847. styles.CellXf.push(xf); break;
  5848. case '</xf>': break;
  5849. /* 18.8.1 alignment CT_CellAlignment */
  5850. case '<alignment': case '<alignment/>':
  5851. var alignment = {};
  5852. if(y.vertical) alignment.vertical = y.vertical;
  5853. if(y.horizontal) alignment.horizontal = y.horizontal;
  5854. if(y.textRotation != null) alignment.textRotation = y.textRotation;
  5855. if(y.indent) alignment.indent = y.indent;
  5856. if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
  5857. xf.alignment = alignment;
  5858. break;
  5859. case '</alignment>': break;
  5860. /* 18.8.33 protection CT_CellProtection */
  5861. case '<protection':
  5862. break;
  5863. case '</protection>': case '<protection/>': break;
  5864. /* note: sometimes mc:AlternateContent appears bare */
  5865. case '<AlternateContent': pass = true; break;
  5866. case '</AlternateContent>': pass = false; break;
  5867. /* 18.2.10 extLst CT_ExtensionList ? */
  5868. case '<extLst': case '<extLst>': case '</extLst>': break;
  5869. case '<ext': pass = true; break;
  5870. case '</ext>': pass = false; break;
  5871. default: if(opts && opts.WTF) {
  5872. if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
  5873. }
  5874. }
  5875. });
  5876. }
  5877. function write_cellXfs(cellXfs) {
  5878. var o = [];
  5879. o[o.length] = (writextag('cellXfs',null));
  5880. cellXfs.forEach(function(c) {
  5881. o[o.length] = (writextag('xf', null, c));
  5882. });
  5883. o[o.length] = ("</cellXfs>");
  5884. if(o.length === 2) return "";
  5885. o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
  5886. return o.join("");
  5887. }
  5888. /* 18.8 Styles CT_Stylesheet*/
  5889. var parse_sty_xml= (function make_pstyx() {
  5890. var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
  5891. var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
  5892. var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
  5893. var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
  5894. var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;
  5895. return function parse_sty_xml(data, themes, opts) {
  5896. var styles = {};
  5897. if(!data) return styles;
  5898. data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  5899. /* 18.8.39 styleSheet CT_Stylesheet */
  5900. var t;
  5901. /* 18.8.31 numFmts CT_NumFmts ? */
  5902. if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);
  5903. /* 18.8.23 fonts CT_Fonts ? */
  5904. if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);
  5905. /* 18.8.21 fills CT_Fills ? */
  5906. if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);
  5907. /* 18.8.5 borders CT_Borders ? */
  5908. if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);
  5909. /* 18.8.9 cellStyleXfs CT_CellStyleXfs ? */
  5910. /* 18.8.8 cellStyles CT_CellStyles ? */
  5911. /* 18.8.10 cellXfs CT_CellXfs ? */
  5912. if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);
  5913. /* 18.8.15 dxfs CT_Dxfs ? */
  5914. /* 18.8.42 tableStyles CT_TableStyles ? */
  5915. /* 18.8.11 colors CT_Colors ? */
  5916. /* 18.2.10 extLst CT_ExtensionList ? */
  5917. return styles;
  5918. };
  5919. })();
  5920. var STYLES_XML_ROOT = writextag('styleSheet', null, {
  5921. 'xmlns': XMLNS.main[0],
  5922. 'xmlns:vt': XMLNS.vt
  5923. });
  5924. RELS.STY = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
  5925. function write_sty_xml(wb, opts) {
  5926. var o = [XML_HEADER, STYLES_XML_ROOT], w;
  5927. if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
  5928. o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
  5929. o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  5930. o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
  5931. o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
  5932. if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
  5933. o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
  5934. o[o.length] = ('<dxfs count="0"/>');
  5935. o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
  5936. if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
  5937. return o.join("");
  5938. }
  5939. RELS.THEME = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
  5940. /* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
  5941. var XLSXThemeClrScheme = [
  5942. '</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
  5943. '</a:accent1>', '</a:accent2>', '</a:accent3>',
  5944. '</a:accent4>', '</a:accent5>', '</a:accent6>',
  5945. '</a:hlink>', '</a:folHlink>'
  5946. ];
  5947. /* 20.1.6.2 clrScheme CT_ColorScheme */
  5948. function parse_clrScheme(t, themes, opts) {
  5949. themes.themeElements.clrScheme = [];
  5950. var color = {};
  5951. (t[0].match(tagregex)||[]).forEach(function(x) {
  5952. var y = parsexmltag(x);
  5953. switch(y[0]) {
  5954. /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
  5955. case '<a:clrScheme': case '</a:clrScheme>': break;
  5956. /* 20.1.2.3.32 srgbClr CT_SRgbColor */
  5957. case '<a:srgbClr':
  5958. color.rgb = y.val; break;
  5959. /* 20.1.2.3.33 sysClr CT_SystemColor */
  5960. case '<a:sysClr':
  5961. color.rgb = y.lastClr; break;
  5962. /* 20.1.4.1.1 accent1 (Accent 1) */
  5963. /* 20.1.4.1.2 accent2 (Accent 2) */
  5964. /* 20.1.4.1.3 accent3 (Accent 3) */
  5965. /* 20.1.4.1.4 accent4 (Accent 4) */
  5966. /* 20.1.4.1.5 accent5 (Accent 5) */
  5967. /* 20.1.4.1.6 accent6 (Accent 6) */
  5968. /* 20.1.4.1.9 dk1 (Dark 1) */
  5969. /* 20.1.4.1.10 dk2 (Dark 2) */
  5970. /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
  5971. /* 20.1.4.1.19 hlink (Hyperlink) */
  5972. /* 20.1.4.1.22 lt1 (Light 1) */
  5973. /* 20.1.4.1.23 lt2 (Light 2) */
  5974. case '<a:dk1>': case '</a:dk1>':
  5975. case '<a:lt1>': case '</a:lt1>':
  5976. case '<a:dk2>': case '</a:dk2>':
  5977. case '<a:lt2>': case '</a:lt2>':
  5978. case '<a:accent1>': case '</a:accent1>':
  5979. case '<a:accent2>': case '</a:accent2>':
  5980. case '<a:accent3>': case '</a:accent3>':
  5981. case '<a:accent4>': case '</a:accent4>':
  5982. case '<a:accent5>': case '</a:accent5>':
  5983. case '<a:accent6>': case '</a:accent6>':
  5984. case '<a:hlink>': case '</a:hlink>':
  5985. case '<a:folHlink>': case '</a:folHlink>':
  5986. if (y[0].charAt(1) === '/') {
  5987. themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
  5988. color = {};
  5989. } else {
  5990. color.name = y[0].slice(3, y[0].length - 1);
  5991. }
  5992. break;
  5993. default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
  5994. }
  5995. });
  5996. }
  5997. /* 20.1.4.1.18 fontScheme CT_FontScheme */
  5998. function parse_fontScheme() { }
  5999. /* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
  6000. function parse_fmtScheme() { }
  6001. var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
  6002. var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
  6003. var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;
  6004. /* 20.1.6.10 themeElements CT_BaseStyles */
  6005. function parse_themeElements(data, themes, opts) {
  6006. themes.themeElements = {};
  6007. var t;
  6008. [
  6009. /* clrScheme CT_ColorScheme */
  6010. ['clrScheme', clrsregex, parse_clrScheme],
  6011. /* fontScheme CT_FontScheme */
  6012. ['fontScheme', fntsregex, parse_fontScheme],
  6013. /* fmtScheme CT_StyleMatrix */
  6014. ['fmtScheme', fmtsregex, parse_fmtScheme]
  6015. ].forEach(function(m) {
  6016. if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
  6017. m[2](t, themes, opts);
  6018. });
  6019. }
  6020. var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;
  6021. /* 14.2.7 Theme Part */
  6022. function parse_theme_xml(data, opts) {
  6023. /* 20.1.6.9 theme CT_OfficeStyleSheet */
  6024. if(!data || data.length === 0) return parse_theme_xml(write_theme());
  6025. var t;
  6026. var themes = {};
  6027. /* themeElements CT_BaseStyles */
  6028. if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
  6029. parse_themeElements(t[0], themes, opts);
  6030. themes.raw = data;
  6031. return themes;
  6032. }
  6033. function write_theme(Themes, opts) {
  6034. if(opts && opts.themeXLSX) return opts.themeXLSX;
  6035. if(Themes && typeof Themes.raw == "string") return Themes.raw;
  6036. var o = [XML_HEADER];
  6037. o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  6038. o[o.length] = '<a:themeElements>';
  6039. o[o.length] = '<a:clrScheme name="Office">';
  6040. o[o.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  6041. o[o.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  6042. o[o.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  6043. o[o.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  6044. o[o.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  6045. o[o.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  6046. o[o.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  6047. o[o.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  6048. o[o.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  6049. o[o.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  6050. o[o.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  6051. o[o.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  6052. o[o.length] = '</a:clrScheme>';
  6053. o[o.length] = '<a:fontScheme name="Office">';
  6054. o[o.length] = '<a:majorFont>';
  6055. o[o.length] = '<a:latin typeface="Cambria"/>';
  6056. o[o.length] = '<a:ea typeface=""/>';
  6057. o[o.length] = '<a:cs typeface=""/>';
  6058. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  6059. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  6060. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  6061. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  6062. o[o.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  6063. o[o.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  6064. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  6065. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  6066. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  6067. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  6068. o[o.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  6069. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  6070. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  6071. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  6072. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  6073. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  6074. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  6075. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  6076. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  6077. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  6078. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  6079. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  6080. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  6081. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  6082. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  6083. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  6084. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  6085. o[o.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  6086. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  6087. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  6088. o[o.length] = '</a:majorFont>';
  6089. o[o.length] = '<a:minorFont>';
  6090. o[o.length] = '<a:latin typeface="Calibri"/>';
  6091. o[o.length] = '<a:ea typeface=""/>';
  6092. o[o.length] = '<a:cs typeface=""/>';
  6093. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  6094. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  6095. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  6096. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  6097. o[o.length] = '<a:font script="Arab" typeface="Arial"/>';
  6098. o[o.length] = '<a:font script="Hebr" typeface="Arial"/>';
  6099. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  6100. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  6101. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  6102. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  6103. o[o.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  6104. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  6105. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  6106. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  6107. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  6108. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  6109. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  6110. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  6111. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  6112. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  6113. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  6114. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  6115. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  6116. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  6117. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  6118. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  6119. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  6120. o[o.length] = '<a:font script="Viet" typeface="Arial"/>';
  6121. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  6122. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  6123. o[o.length] = '</a:minorFont>';
  6124. o[o.length] = '</a:fontScheme>';
  6125. o[o.length] = '<a:fmtScheme name="Office">';
  6126. o[o.length] = '<a:fillStyleLst>';
  6127. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  6128. o[o.length] = '<a:gradFill rotWithShape="1">';
  6129. o[o.length] = '<a:gsLst>';
  6130. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  6131. o[o.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  6132. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  6133. o[o.length] = '</a:gsLst>';
  6134. o[o.length] = '<a:lin ang="16200000" scaled="1"/>';
  6135. o[o.length] = '</a:gradFill>';
  6136. o[o.length] = '<a:gradFill rotWithShape="1">';
  6137. o[o.length] = '<a:gsLst>';
  6138. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000"/><a:shade val="100000"/><a:satMod val="130000"/></a:schemeClr></a:gs>';
  6139. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000"/><a:shade val="100000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  6140. o[o.length] = '</a:gsLst>';
  6141. o[o.length] = '<a:lin ang="16200000" scaled="0"/>';
  6142. o[o.length] = '</a:gradFill>';
  6143. o[o.length] = '</a:fillStyleLst>';
  6144. o[o.length] = '<a:lnStyleLst>';
  6145. o[o.length] = '<a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/><a:satMod val="105000"/></a:schemeClr></a:solidFill><a:prstDash val="solid"/></a:ln>';
  6146. o[o.length] = '<a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  6147. o[o.length] = '<a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  6148. o[o.length] = '</a:lnStyleLst>';
  6149. o[o.length] = '<a:effectStyleLst>';
  6150. o[o.length] = '<a:effectStyle>';
  6151. o[o.length] = '<a:effectLst>';
  6152. o[o.length] = '<a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000"/></a:srgbClr></a:outerShdw>';
  6153. o[o.length] = '</a:effectLst>';
  6154. o[o.length] = '</a:effectStyle>';
  6155. o[o.length] = '<a:effectStyle>';
  6156. o[o.length] = '<a:effectLst>';
  6157. o[o.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  6158. o[o.length] = '</a:effectLst>';
  6159. o[o.length] = '</a:effectStyle>';
  6160. o[o.length] = '<a:effectStyle>';
  6161. o[o.length] = '<a:effectLst>';
  6162. o[o.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  6163. o[o.length] = '</a:effectLst>';
  6164. o[o.length] = '<a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="0" rev="0"/></a:camera><a:lightRig rig="threePt" dir="t"><a:rot lat="0" lon="0" rev="1200000"/></a:lightRig></a:scene3d>';
  6165. o[o.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  6166. o[o.length] = '</a:effectStyle>';
  6167. o[o.length] = '</a:effectStyleLst>';
  6168. o[o.length] = '<a:bgFillStyleLst>';
  6169. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  6170. o[o.length] = '<a:gradFill rotWithShape="1">';
  6171. o[o.length] = '<a:gsLst>';
  6172. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  6173. o[o.length] = '<a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000"/><a:shade val="99000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  6174. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  6175. o[o.length] = '</a:gsLst>';
  6176. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  6177. o[o.length] = '</a:gradFill>';
  6178. o[o.length] = '<a:gradFill rotWithShape="1">';
  6179. o[o.length] = '<a:gsLst>';
  6180. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  6181. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  6182. o[o.length] = '</a:gsLst>';
  6183. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  6184. o[o.length] = '</a:gradFill>';
  6185. o[o.length] = '</a:bgFillStyleLst>';
  6186. o[o.length] = '</a:fmtScheme>';
  6187. o[o.length] = '</a:themeElements>';
  6188. o[o.length] = '<a:objectDefaults>';
  6189. o[o.length] = '<a:spDef>';
  6190. o[o.length] = '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></a:style>';
  6191. o[o.length] = '</a:spDef>';
  6192. o[o.length] = '<a:lnDef>';
  6193. o[o.length] = '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="1"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1"/></a:fontRef></a:style>';
  6194. o[o.length] = '</a:lnDef>';
  6195. o[o.length] = '</a:objectDefaults>';
  6196. o[o.length] = '<a:extraClrSchemeLst/>';
  6197. o[o.length] = '</a:theme>';
  6198. return o.join("");
  6199. }
  6200. /* 18.14 Supplementary Workbook Data */
  6201. function parse_xlink_xml() {
  6202. //var opts = _opts || {};
  6203. //if(opts.WTF) throw "XLSX External Link";
  6204. }
  6205. /* [MS-XLSB] 2.1.7.25 External Link */
  6206. function parse_xlink_bin(data, rel, name, _opts) {
  6207. if(!data) return data;
  6208. var opts = _opts || {};
  6209. var pass = false, end = false;
  6210. recordhopper(data, function xlink_parse(val, R_n, RT) {
  6211. if(end) return;
  6212. switch(RT) {
  6213. case 0x0167: /* 'BrtSupTabs' */
  6214. case 0x016B: /* 'BrtExternTableStart' */
  6215. case 0x016C: /* 'BrtExternTableEnd' */
  6216. case 0x016E: /* 'BrtExternRowHdr' */
  6217. case 0x016F: /* 'BrtExternCellBlank' */
  6218. case 0x0170: /* 'BrtExternCellReal' */
  6219. case 0x0171: /* 'BrtExternCellBool' */
  6220. case 0x0172: /* 'BrtExternCellError' */
  6221. case 0x0173: /* 'BrtExternCellString' */
  6222. case 0x01D8: /* 'BrtExternValueMeta' */
  6223. case 0x0241: /* 'BrtSupNameStart' */
  6224. case 0x0242: /* 'BrtSupNameValueStart' */
  6225. case 0x0243: /* 'BrtSupNameValueEnd' */
  6226. case 0x0244: /* 'BrtSupNameNum' */
  6227. case 0x0245: /* 'BrtSupNameErr' */
  6228. case 0x0246: /* 'BrtSupNameSt' */
  6229. case 0x0247: /* 'BrtSupNameNil' */
  6230. case 0x0248: /* 'BrtSupNameBool' */
  6231. case 0x0249: /* 'BrtSupNameFmla' */
  6232. case 0x024A: /* 'BrtSupNameBits' */
  6233. case 0x024B: /* 'BrtSupNameEnd' */
  6234. break;
  6235. case 0x0023: /* 'BrtFRTBegin' */
  6236. pass = true; break;
  6237. case 0x0024: /* 'BrtFRTEnd' */
  6238. pass = false; break;
  6239. default:
  6240. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  6241. else if((R_n||"").indexOf("End") > 0){/* empty */}
  6242. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT.toString(16) + " " + R_n);
  6243. }
  6244. }, opts);
  6245. }
  6246. /* 20.5 DrawingML - SpreadsheetML Drawing */
  6247. RELS.IMG = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
  6248. RELS.DRAW = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
  6249. /* 20.5.2.35 wsDr CT_Drawing */
  6250. function parse_drawing(data, rels) {
  6251. if(!data) return "??";
  6252. /*
  6253. Chartsheet Drawing:
  6254. - 20.5.2.35 wsDr CT_Drawing
  6255. - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor
  6256. - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
  6257. - 20.1.2.2.16 graphic CT_GraphicalObject
  6258. - 20.1.2.2.17 graphicData CT_GraphicalObjectData
  6259. - chart reference
  6260. the actual type is based on the URI of the graphicData
  6261. TODO: handle embedded charts and other types of graphics
  6262. */
  6263. var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];
  6264. return rels['!id'][id].Target;
  6265. }
  6266. /* L.5.5.2 SpreadsheetML Comments + VML Schema */
  6267. var _shapeid = 1024;
  6268. function write_comments_vml(rId, comments) {
  6269. var csize = [21600, 21600];
  6270. /* L.5.2.1.2 Path Attribute */
  6271. var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
  6272. var o = [
  6273. writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
  6274. writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"}),
  6275. writextag("v:shapetype", [
  6276. writextag("v:stroke", null, {joinstyle:"miter"}),
  6277. writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
  6278. ].join(""), {id:"_x0000_t202", 'o:spt':202, coordsize:csize.join(","),path:bbox})
  6279. ];
  6280. while(_shapeid < rId * 1000) _shapeid += 1000;
  6281. comments.forEach(function(x) {
  6282. var c = decode_cell(x[0]);
  6283. var fillopts = {'color2':"#BEFF82", 'type':"gradient"};
  6284. if(fillopts.type == "gradient") fillopts.angle = "-180";
  6285. var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
  6286. var fillxml = writextag('v:fill', fillparm, fillopts);
  6287. var shadata = ({on:"t", 'obscured':"t"});
  6288. ++_shapeid;
  6289. o = o.concat([
  6290. '<v:shape' + wxt_helper({
  6291. id:'_x0000_s' + _shapeid,
  6292. type:"#_x0000_t202",
  6293. style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
  6294. fillcolor:"#ECFAD4",
  6295. strokecolor:"#edeaa1"
  6296. }) + '>',
  6297. fillxml,
  6298. writextag("v:shadow", null, shadata),
  6299. writextag("v:path", null, {'o:connecttype':"none"}),
  6300. '<v:textbox><div style="text-align:left"></div></v:textbox>',
  6301. '<x:ClientData ObjectType="Note">',
  6302. '<x:MoveWithCells/>',
  6303. '<x:SizeWithCells/>',
  6304. /* Part 4 19.4.2.3 Anchor (Anchor) */
  6305. writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
  6306. writetag('x:AutoFill', "False"),
  6307. writetag('x:Row', String(c.r)),
  6308. writetag('x:Column', String(c.c)),
  6309. x[1].hidden ? '' : '<x:Visible/>',
  6310. '</x:ClientData>',
  6311. '</v:shape>'
  6312. ]); });
  6313. o.push('</xml>');
  6314. return o.join("");
  6315. }
  6316. RELS.CMNT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
  6317. function sheet_insert_comments(sheet, comments) {
  6318. var dense = Array.isArray(sheet);
  6319. var cell;
  6320. comments.forEach(function(comment) {
  6321. var r = decode_cell(comment.ref);
  6322. if(dense) {
  6323. if(!sheet[r.r]) sheet[r.r] = [];
  6324. cell = sheet[r.r][r.c];
  6325. } else cell = sheet[comment.ref];
  6326. if (!cell) {
  6327. cell = ({t:"z"});
  6328. if(dense) sheet[r.r][r.c] = cell;
  6329. else sheet[comment.ref] = cell;
  6330. var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
  6331. if(range.s.r > r.r) range.s.r = r.r;
  6332. if(range.e.r < r.r) range.e.r = r.r;
  6333. if(range.s.c > r.c) range.s.c = r.c;
  6334. if(range.e.c < r.c) range.e.c = r.c;
  6335. var encoded = encode_range(range);
  6336. if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
  6337. }
  6338. if (!cell.c) cell.c = [];
  6339. var o = ({a: comment.author, t: comment.t, r: comment.r});
  6340. if(comment.h) o.h = comment.h;
  6341. cell.c.push(o);
  6342. });
  6343. }
  6344. /* 18.7 Comments */
  6345. function parse_comments_xml(data, opts) {
  6346. /* 18.7.6 CT_Comments */
  6347. if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
  6348. var authors = [];
  6349. var commentList = [];
  6350. var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
  6351. if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
  6352. if(x === "" || x.trim() === "") return;
  6353. var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
  6354. if(a) authors.push(a[1]);
  6355. });
  6356. var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
  6357. if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
  6358. if(x === "" || x.trim() === "") return;
  6359. var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
  6360. if(!cm) return;
  6361. var y = parsexmltag(cm[0]);
  6362. var comment = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid });
  6363. var cell = decode_cell(y.ref);
  6364. if(opts.sheetRows && opts.sheetRows <= cell.r) return;
  6365. var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
  6366. var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
  6367. comment.r = rt.r;
  6368. if(rt.r == "<t></t>") rt.t = rt.h = "";
  6369. comment.t = (rt.t||"").replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  6370. if(opts.cellHTML) comment.h = rt.h;
  6371. commentList.push(comment);
  6372. });
  6373. return commentList;
  6374. }
  6375. var CMNT_XML_ROOT = writextag('comments', null, { 'xmlns': XMLNS.main[0] });
  6376. function write_comments_xml(data) {
  6377. var o = [XML_HEADER, CMNT_XML_ROOT];
  6378. var iauthor = [];
  6379. o.push("<authors>");
  6380. data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
  6381. if(iauthor.indexOf(a) > -1) return;
  6382. iauthor.push(a);
  6383. o.push("<author>" + a + "</author>");
  6384. }); });
  6385. o.push("</authors>");
  6386. o.push("<commentList>");
  6387. data.forEach(function(d) {
  6388. d[1].forEach(function(c) {
  6389. /* 18.7.3 CT_Comment */
  6390. o.push('<comment ref="' + d[0] + '" authorId="' + iauthor.indexOf(escapexml(c.a)) + '"><text>');
  6391. o.push(writetag("t", c.t == null ? "" : escapexml(c.t)));
  6392. o.push('</text></comment>');
  6393. });
  6394. });
  6395. o.push("</commentList>");
  6396. if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
  6397. return o.join("");
  6398. }
  6399. var CT_VBA = "application/vnd.ms-office.vbaProject";
  6400. function make_vba_xls(cfb) {
  6401. var newcfb = CFB.utils.cfb_new({root:"R"});
  6402. cfb.FullPaths.forEach(function(p, i) {
  6403. if(p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/)) return;
  6404. var newpath = p.replace(/^[^\/]*/,"R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
  6405. CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  6406. });
  6407. return CFB.write(newcfb);
  6408. }
  6409. function fill_vba_xls(cfb, vba) {
  6410. vba.FullPaths.forEach(function(p, i) {
  6411. if(i == 0) return;
  6412. var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
  6413. if(newpath.slice(-1) !== "/") CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  6414. });
  6415. }
  6416. var VBAFMTS = [ "xlsb", "xlsm", "xlam", "biff8", "xla" ];
  6417. RELS.DS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet";
  6418. RELS.MS = "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet";
  6419. /* macro and dialog sheet stubs */
  6420. function parse_ds_bin() { return {'!type':'dialog'}; }
  6421. function parse_ds_xml() { return {'!type':'dialog'}; }
  6422. function parse_ms_bin() { return {'!type':'macro'}; }
  6423. function parse_ms_xml() { return {'!type':'macro'}; }
  6424. /* TODO: it will be useful to parse the function str */
  6425. var rc_to_a1 = (function(){
  6426. var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  6427. var rcbase = ({r:0,c:0});
  6428. function rcfunc($$,$1,$2,$3) {
  6429. var cRel = false, rRel = false;
  6430. if($2.length == 0) rRel = true;
  6431. else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }
  6432. if($3.length == 0) cRel = true;
  6433. else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }
  6434. var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;
  6435. if(cRel) C += rcbase.c; else --C;
  6436. if(rRel) R += rcbase.r; else --R;
  6437. return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
  6438. }
  6439. return function rc_to_a1(fstr, base) {
  6440. rcbase = base;
  6441. return fstr.replace(rcregex, rcfunc);
  6442. };
  6443. })();
  6444. var crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g;
  6445. var a1_to_rc =(function(){
  6446. return function a1_to_rc(fstr, base) {
  6447. return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  6448. var c = decode_col($3) - ($2 ? 0 : base.c);
  6449. var r = decode_row($5) - ($4 ? 0 : base.r);
  6450. var R = (r == 0 ? "" : !$4 ? "[" + r + "]" : (r+1));
  6451. var C = (c == 0 ? "" : !$2 ? "[" + c + "]" : (c+1));
  6452. return $1 + "R" + R + "C" + C;
  6453. });
  6454. };
  6455. })();
  6456. /* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
  6457. function shift_formula_str(f, delta) {
  6458. return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  6459. return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
  6460. });
  6461. }
  6462. function shift_formula_xlsx(f, range, cell) {
  6463. var r = decode_range(range), s = r.s, c = decode_cell(cell);
  6464. var delta = {r:c.r - s.r, c:c.c - s.c};
  6465. return shift_formula_str(f, delta);
  6466. }
  6467. /* TODO: parse formula */
  6468. function fuzzyfmla(f) {
  6469. if(f.length == 1) return false;
  6470. return true;
  6471. }
  6472. function _xlfn(f) {
  6473. return f.replace(/_xlfn\./g,"");
  6474. }
  6475. var strs = {}; // shared strings
  6476. var _ssfopts = {}; // spreadsheet formatting options
  6477. RELS.WS = [
  6478. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  6479. "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  6480. ];
  6481. /*global Map */
  6482. var browser_has_Map = typeof Map !== 'undefined';
  6483. function get_sst_id(sst, str, rev) {
  6484. var i = 0, len = sst.length;
  6485. if(rev) {
  6486. if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
  6487. var revarr = browser_has_Map ? rev.get(str) : rev[str];
  6488. for(; i < revarr.length; ++i) {
  6489. if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
  6490. }
  6491. }
  6492. } else for(; i < len; ++i) {
  6493. if(sst[i].t === str) { sst.Count ++; return i; }
  6494. }
  6495. sst[len] = ({t:str}); sst.Count ++; sst.Unique ++;
  6496. if(rev) {
  6497. if(browser_has_Map) {
  6498. if(!rev.has(str)) rev.set(str, []);
  6499. rev.get(str).push(len);
  6500. } else {
  6501. if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
  6502. rev[str].push(len);
  6503. }
  6504. }
  6505. return len;
  6506. }
  6507. function col_obj_w(C, col) {
  6508. var p = ({min:C+1,max:C+1});
  6509. /* wch (chars), wpx (pixels) */
  6510. var wch = -1;
  6511. if(col.MDW) MDW = col.MDW;
  6512. if(col.width != null) p.customWidth = 1;
  6513. else if(col.wpx != null) wch = px2char(col.wpx);
  6514. else if(col.wch != null) wch = col.wch;
  6515. if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
  6516. else if(col.width != null) p.width = col.width;
  6517. if(col.hidden) p.hidden = true;
  6518. if(col.level != null) { p.outlineLevel = p.level = col.level; }
  6519. return p;
  6520. }
  6521. function default_margins(margins, mode) {
  6522. if(!margins) return;
  6523. var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  6524. if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
  6525. if(margins.left == null) margins.left = defs[0];
  6526. if(margins.right == null) margins.right = defs[1];
  6527. if(margins.top == null) margins.top = defs[2];
  6528. if(margins.bottom == null) margins.bottom = defs[3];
  6529. if(margins.header == null) margins.header = defs[4];
  6530. if(margins.footer == null) margins.footer = defs[5];
  6531. }
  6532. function get_cell_style(styles, cell, opts) {
  6533. var z = opts.revssf[cell.z != null ? cell.z : "General"];
  6534. var i = 0x3c, len = styles.length;
  6535. if(z == null && opts.ssf) {
  6536. for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
  6537. SSF.load(cell.z, i);
  6538. // $FlowIgnore
  6539. opts.ssf[i] = cell.z;
  6540. opts.revssf[cell.z] = z = i;
  6541. break;
  6542. }
  6543. }
  6544. for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
  6545. styles[len] = {
  6546. numFmtId:z,
  6547. fontId:0,
  6548. fillId:0,
  6549. borderId:0,
  6550. xfId:0,
  6551. applyNumberFormat:1
  6552. };
  6553. return len;
  6554. }
  6555. function safe_format(p, fmtid, fillid, opts, themes, styles) {
  6556. try {
  6557. if(opts.cellNF) p.z = SSF._table[fmtid];
  6558. } catch(e) { if(opts.WTF) throw e; }
  6559. if(p.t === 'z' && !opts.cellStyles) return;
  6560. if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
  6561. if((!opts || opts.cellText !== false) && p.t !== 'z') try {
  6562. if(SSF._table[fmtid] == null) SSF.load(SSFImplicit[fmtid] || "General", fmtid);
  6563. if(p.t === 'e') p.w = p.w || BErr[p.v];
  6564. else if(fmtid === 0) {
  6565. if(p.t === 'n') {
  6566. if((p.v|0) === p.v) p.w = SSF._general_int(p.v);
  6567. else p.w = SSF._general_num(p.v);
  6568. }
  6569. else if(p.t === 'd') {
  6570. var dd = datenum(p.v);
  6571. if((dd|0) === dd) p.w = SSF._general_int(dd);
  6572. else p.w = SSF._general_num(dd);
  6573. }
  6574. else if(p.v === undefined) return "";
  6575. else p.w = SSF._general(p.v,_ssfopts);
  6576. }
  6577. else if(p.t === 'd') p.w = SSF.format(fmtid,datenum(p.v),_ssfopts);
  6578. else p.w = SSF.format(fmtid,p.v,_ssfopts);
  6579. } catch(e) { if(opts.WTF) throw e; }
  6580. if(!opts.cellStyles) return;
  6581. if(fillid != null) try {
  6582. p.s = styles.Fills[fillid];
  6583. if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
  6584. p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
  6585. if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
  6586. }
  6587. if (p.s.bgColor && p.s.bgColor.theme) {
  6588. p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
  6589. if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
  6590. }
  6591. } catch(e) { if(opts.WTF && styles.Fills) throw e; }
  6592. }
  6593. function check_ws(ws, sname, i) {
  6594. if(ws && ws['!ref']) {
  6595. var range = safe_decode_range(ws['!ref']);
  6596. if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
  6597. }
  6598. }
  6599. function parse_ws_xml_dim(ws, s) {
  6600. var d = safe_decode_range(s);
  6601. if(d.s.r<=d.e.r && d.s.c<=d.e.c && d.s.r>=0 && d.s.c>=0) ws["!ref"] = encode_range(d);
  6602. }
  6603. var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
  6604. var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
  6605. var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
  6606. var dimregex = /"(\w*:\w*)"/;
  6607. var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
  6608. var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
  6609. var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
  6610. var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
  6611. var sheetprregex2= /<(?:\w:)?sheetPr[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetPr)>/;
  6612. var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
  6613. /* 18.3 Worksheets */
  6614. function parse_ws_xml(data, opts, idx, rels, wb, themes, styles) {
  6615. if(!data) return data;
  6616. if(!rels) rels = {'!id':{}};
  6617. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  6618. /* 18.3.1.99 worksheet CT_Worksheet */
  6619. var s = opts.dense ? ([]) : ({});
  6620. var refguess = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} });
  6621. var data1 = "", data2 = "";
  6622. var mtch = data.match(sheetdataregex);
  6623. if(mtch) {
  6624. data1 = data.slice(0, mtch.index);
  6625. data2 = data.slice(mtch.index + mtch[0].length);
  6626. } else data1 = data2 = data;
  6627. /* 18.3.1.82 sheetPr CT_SheetPr */
  6628. var sheetPr = data1.match(sheetprregex);
  6629. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  6630. else if((sheetPr = data1.match(sheetprregex2))) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1]||"", s, wb, idx, styles, themes);
  6631. /* 18.3.1.35 dimension CT_SheetDimension */
  6632. var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
  6633. if(ridx > 0) {
  6634. var ref = data1.slice(ridx,ridx+50).match(dimregex);
  6635. if(ref) parse_ws_xml_dim(s, ref[1]);
  6636. }
  6637. /* 18.3.1.88 sheetViews CT_SheetViews */
  6638. var svs = data1.match(svsregex);
  6639. if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  6640. /* 18.3.1.17 cols CT_Cols */
  6641. var columns = [];
  6642. if(opts.cellStyles) {
  6643. /* 18.3.1.13 col CT_Col */
  6644. var cols = data1.match(colregex);
  6645. if(cols) parse_ws_xml_cols(columns, cols);
  6646. }
  6647. /* 18.3.1.80 sheetData CT_SheetData ? */
  6648. if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
  6649. /* 18.3.1.2 autoFilter CT_AutoFilter */
  6650. var afilter = data2.match(afregex);
  6651. if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);
  6652. /* 18.3.1.55 mergeCells CT_MergeCells */
  6653. var merges = [];
  6654. var _merge = data2.match(mergecregex);
  6655. if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
  6656. merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
  6657. /* 18.3.1.48 hyperlinks CT_Hyperlinks */
  6658. var hlink = data2.match(hlinkregex);
  6659. if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
  6660. /* 18.3.1.62 pageMargins CT_PageMargins */
  6661. var margins = data2.match(marginregex);
  6662. if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));
  6663. if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
  6664. if(opts.sheetRows > 0 && s["!ref"]) {
  6665. var tmpref = safe_decode_range(s["!ref"]);
  6666. if(opts.sheetRows <= +tmpref.e.r) {
  6667. tmpref.e.r = opts.sheetRows - 1;
  6668. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  6669. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  6670. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  6671. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  6672. s["!fullref"] = s["!ref"];
  6673. s["!ref"] = encode_range(tmpref);
  6674. }
  6675. }
  6676. if(columns.length > 0) s["!cols"] = columns;
  6677. if(merges.length > 0) s["!merges"] = merges;
  6678. return s;
  6679. }
  6680. function write_ws_xml_merges(merges) {
  6681. if(merges.length === 0) return "";
  6682. var o = '<mergeCells count="' + merges.length + '">';
  6683. for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
  6684. return o + '</mergeCells>';
  6685. }
  6686. /* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
  6687. function parse_ws_xml_sheetpr(sheetPr, s, wb, idx) {
  6688. var data = parsexmltag(sheetPr);
  6689. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  6690. if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
  6691. }
  6692. function parse_ws_xml_sheetpr2(sheetPr, body, s, wb, idx, styles, themes) {
  6693. parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s, wb, idx);
  6694. }
  6695. function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
  6696. var needed = false;
  6697. var props = {}, payload = null;
  6698. if(opts.bookType !== 'xlsx' && wb.vbaraw) {
  6699. var cname = wb.SheetNames[idx];
  6700. try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
  6701. needed = true;
  6702. props.codeName = utf8write(escapexml(cname));
  6703. }
  6704. if(ws && ws["!outline"]) {
  6705. var outlineprops = {summaryBelow:1, summaryRight:1};
  6706. if(ws["!outline"].above) outlineprops.summaryBelow = 0;
  6707. if(ws["!outline"].left) outlineprops.summaryRight = 0;
  6708. payload = (payload||"") + writextag('outlinePr', null, outlineprops);
  6709. }
  6710. if(!needed && !payload) return;
  6711. o[o.length] = (writextag('sheetPr', payload, props));
  6712. }
  6713. /* 18.3.1.85 sheetProtection CT_SheetProtection */
  6714. var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
  6715. var sheetprot_deftrue = [
  6716. "formatColumns", "formatRows", "formatCells",
  6717. "insertColumns", "insertRows", "insertHyperlinks",
  6718. "deleteColumns", "deleteRows",
  6719. "sort", "autoFilter", "pivotTables"
  6720. ];
  6721. function write_ws_xml_protection(sp) {
  6722. // algorithmName, hashValue, saltValue, spinCount
  6723. var o = ({sheet:1});
  6724. sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
  6725. sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
  6726. /* TODO: algorithm */
  6727. if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
  6728. return writextag('sheetProtection', null, o);
  6729. }
  6730. function parse_ws_xml_hlinks(s, data, rels) {
  6731. var dense = Array.isArray(s);
  6732. for(var i = 0; i != data.length; ++i) {
  6733. var val = parsexmltag(utf8read(data[i]), true);
  6734. if(!val.ref) return;
  6735. var rel = ((rels || {})['!id']||[])[val.id];
  6736. if(rel) {
  6737. val.Target = rel.Target;
  6738. if(val.location) val.Target += "#"+unescapexml(val.location);
  6739. } else {
  6740. val.Target = "#" + unescapexml(val.location);
  6741. rel = {Target: val.Target, TargetMode: 'Internal'};
  6742. }
  6743. val.Rel = rel;
  6744. if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
  6745. var rng = safe_decode_range(val.ref);
  6746. for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
  6747. var addr = encode_cell({c:C,r:R});
  6748. if(dense) {
  6749. if(!s[R]) s[R] = [];
  6750. if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
  6751. s[R][C].l = val;
  6752. } else {
  6753. if(!s[addr]) s[addr] = {t:"z",v:undefined};
  6754. s[addr].l = val;
  6755. }
  6756. }
  6757. }
  6758. }
  6759. function parse_ws_xml_margins(margin) {
  6760. var o = {};
  6761. ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
  6762. if(margin[k]) o[k] = parseFloat(margin[k]);
  6763. });
  6764. return o;
  6765. }
  6766. function write_ws_xml_margins(margin) {
  6767. default_margins(margin);
  6768. return writextag('pageMargins', null, margin);
  6769. }
  6770. function parse_ws_xml_cols(columns, cols) {
  6771. var seencol = false;
  6772. for(var coli = 0; coli != cols.length; ++coli) {
  6773. var coll = parsexmltag(cols[coli], true);
  6774. if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
  6775. var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
  6776. if(coll.outlineLevel) coll.level = (+coll.outlineLevel || 0);
  6777. delete coll.min; delete coll.max; coll.width = +coll.width;
  6778. if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
  6779. process_col(coll);
  6780. while(colm <= colM) columns[colm++] = dup(coll);
  6781. }
  6782. }
  6783. function write_ws_xml_cols(ws, cols) {
  6784. var o = ["<cols>"], col;
  6785. for(var i = 0; i != cols.length; ++i) {
  6786. if(!(col = cols[i])) continue;
  6787. o[o.length] = (writextag('col', null, col_obj_w(i, col)));
  6788. }
  6789. o[o.length] = "</cols>";
  6790. return o.join("");
  6791. }
  6792. function parse_ws_xml_autofilter(data) {
  6793. var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
  6794. return o;
  6795. }
  6796. function write_ws_xml_autofilter(data, ws, wb, idx) {
  6797. var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
  6798. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  6799. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  6800. var names = wb.Workbook.Names;
  6801. var range = decode_range(ref);
  6802. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  6803. for(var i = 0; i < names.length; ++i) {
  6804. var name = names[i];
  6805. if(name.Name != '_xlnm._FilterDatabase') continue;
  6806. if(name.Sheet != idx) continue;
  6807. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  6808. }
  6809. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  6810. return writextag("autoFilter", null, {ref:ref});
  6811. }
  6812. /* 18.3.1.88 sheetViews CT_SheetViews */
  6813. /* 18.3.1.87 sheetView CT_SheetView */
  6814. var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
  6815. function parse_ws_xml_sheetviews(data, wb) {
  6816. if(!wb.Views) wb.Views = [{}];
  6817. (data.match(sviewregex)||[]).forEach(function(r, i) {
  6818. var tag = parsexmltag(r);
  6819. // $FlowIgnore
  6820. if(!wb.Views[i]) wb.Views[i] = {};
  6821. // $FlowIgnore
  6822. if(+tag.zoomScale) wb.Views[i].zoom = +tag.zoomScale;
  6823. // $FlowIgnore
  6824. if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
  6825. });
  6826. }
  6827. function write_ws_xml_sheetviews(ws, opts, idx, wb) {
  6828. var sview = ({workbookViewId:"0"});
  6829. // $FlowIgnore
  6830. if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
  6831. return writextag("sheetViews", writextag("sheetView", null, sview), {});
  6832. }
  6833. function write_ws_xml_cell(cell, ref, ws, opts) {
  6834. if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z') return "";
  6835. var vv = "";
  6836. var oldt = cell.t, oldv = cell.v;
  6837. if(cell.t !== "z") switch(cell.t) {
  6838. case 'b': vv = cell.v ? "1" : "0"; break;
  6839. case 'n': vv = ''+cell.v; break;
  6840. case 'e': vv = BErr[cell.v]; break;
  6841. case 'd':
  6842. if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
  6843. else {
  6844. cell = dup(cell);
  6845. cell.t = 'n';
  6846. vv = ''+(cell.v = datenum(parseDate(cell.v)));
  6847. }
  6848. if(typeof cell.z === 'undefined') cell.z = SSF._table[14];
  6849. break;
  6850. default: vv = cell.v; break;
  6851. }
  6852. var v = writetag('v', escapexml(vv)), o = ({r:ref});
  6853. /* TODO: cell style */
  6854. var os = get_cell_style(opts.cellXfs, cell, opts);
  6855. if(os !== 0) o.s = os;
  6856. switch(cell.t) {
  6857. case 'n': break;
  6858. case 'd': o.t = "d"; break;
  6859. case 'b': o.t = "b"; break;
  6860. case 'e': o.t = "e"; break;
  6861. case 'z': break;
  6862. default: if(cell.v == null) { delete cell.t; break; }
  6863. if(cell.v.length > 32767) throw new Error("Text length must not exceed 32767 characters");
  6864. if(opts && opts.bookSST) {
  6865. v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
  6866. o.t = "s"; break;
  6867. }
  6868. o.t = "str"; break;
  6869. }
  6870. if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
  6871. if(typeof cell.f == "string" && cell.f) {
  6872. var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
  6873. v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
  6874. }
  6875. if(cell.l) ws['!links'].push([ref, cell.l]);
  6876. if(cell.c) ws['!comments'].push([ref, cell.c]);
  6877. return writextag('c', v, o);
  6878. }
  6879. var parse_ws_xml_data = (function() {
  6880. var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  6881. var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
  6882. var refregex = /ref=["']([^"']*)["']/;
  6883. var match_v = matchtag("v"), match_f = matchtag("f");
  6884. return function parse_ws_xml_data(sdata, s, opts, guess, themes, styles) {
  6885. var ri = 0, x = "", cells = [], cref = [], idx=0, i=0, cc=0, d="", p;
  6886. var tag, tagr = 0, tagc = 0;
  6887. var sstr, ftag;
  6888. var fmtid = 0, fillid = 0;
  6889. var do_format = Array.isArray(styles.CellXf), cf;
  6890. var arrayf = [];
  6891. var sharedf = [];
  6892. var dense = Array.isArray(s);
  6893. var rows = [], rowobj = {}, rowrite = false;
  6894. var sheetStubs = !!opts.sheetStubs;
  6895. for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
  6896. x = marr[mt].trim();
  6897. var xlen = x.length;
  6898. if(xlen === 0) continue;
  6899. /* 18.3.1.73 row CT_Row */
  6900. var rstarti = 0;
  6901. outa: for(ri = 0; ri < xlen; ++ri) switch(/*x.charCodeAt(ri)*/x[ri]) {
  6902. case ">" /*62*/:
  6903. if(/*x.charCodeAt(ri-1) != 47*/x[ri-1] != "/") { ++ri; break outa; }
  6904. if(opts && opts.cellStyles) {
  6905. // TODO: avoid duplication
  6906. tag = parsexmltag(x.slice(rstarti,ri), true);
  6907. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  6908. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  6909. rowobj = {}; rowrite = false;
  6910. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  6911. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  6912. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  6913. if(rowrite) rows[tagr-1] = rowobj;
  6914. }
  6915. break;
  6916. case "<" /*60*/: rstarti = ri; break;
  6917. }
  6918. if(rstarti >= ri) break;
  6919. tag = parsexmltag(x.slice(rstarti,ri), true);
  6920. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  6921. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  6922. if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
  6923. if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
  6924. if(opts && opts.cellStyles) {
  6925. rowobj = {}; rowrite = false;
  6926. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  6927. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  6928. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  6929. if(rowrite) rows[tagr-1] = rowobj;
  6930. }
  6931. /* 18.3.1.4 c CT_Cell */
  6932. cells = x.slice(ri).split(cellregex);
  6933. for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
  6934. cells = cells.slice(rslice);
  6935. for(ri = 0; ri != cells.length; ++ri) {
  6936. x = cells[ri].trim();
  6937. if(x.length === 0) continue;
  6938. cref = x.match(rregex); idx = ri; i=0; cc=0;
  6939. x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
  6940. if(cref != null && cref.length === 2) {
  6941. idx = 0; d=cref[1];
  6942. for(i=0; i != d.length; ++i) {
  6943. if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
  6944. idx = 26*idx + cc;
  6945. }
  6946. --idx;
  6947. tagc = idx;
  6948. } else ++tagc;
  6949. for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
  6950. tag = parsexmltag(x.slice(0,i), true);
  6951. if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
  6952. d = x.slice(i);
  6953. p = ({t:""});
  6954. if((cref=d.match(match_v))!= null && cref[1] !== '') p.v=unescapexml(cref[1]);
  6955. if(opts.cellFormula) {
  6956. if((cref=d.match(match_f))!= null && cref[1] !== '') {
  6957. /* TODO: match against XLSXFutureFunctions */
  6958. p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
  6959. if(!opts.xlfn) p.f = _xlfn(p.f);
  6960. if(cref[0].indexOf('t="array"') > -1) {
  6961. p.F = (d.match(refregex)||[])[1];
  6962. if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
  6963. } else if(cref[0].indexOf('t="shared"') > -1) {
  6964. // TODO: parse formula
  6965. ftag = parsexmltag(cref[0]);
  6966. var ___f = unescapexml(utf8read(cref[1]));
  6967. if(!opts.xlfn) ___f = _xlfn(___f);
  6968. sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
  6969. }
  6970. } else if((cref=d.match(/<f[^>]*\/>/))) {
  6971. ftag = parsexmltag(cref[0]);
  6972. if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
  6973. }
  6974. /* TODO: factor out contains logic */
  6975. var _tag = decode_cell(tag.r);
  6976. for(i = 0; i < arrayf.length; ++i)
  6977. if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
  6978. if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
  6979. p.F = arrayf[i][1];
  6980. }
  6981. if(tag.t == null && p.v === undefined) {
  6982. if(p.f || p.F) {
  6983. p.v = 0; p.t = "n";
  6984. } else if(!sheetStubs) continue;
  6985. else p.t = "z";
  6986. }
  6987. else p.t = tag.t || "n";
  6988. if(guess.s.c > tagc) guess.s.c = tagc;
  6989. if(guess.e.c < tagc) guess.e.c = tagc;
  6990. /* 18.18.11 t ST_CellType */
  6991. switch(p.t) {
  6992. case 'n':
  6993. if(p.v == "" || p.v == null) {
  6994. if(!sheetStubs) continue;
  6995. p.t = 'z';
  6996. } else p.v = parseFloat(p.v);
  6997. break;
  6998. case 's':
  6999. if(typeof p.v == 'undefined') {
  7000. if(!sheetStubs) continue;
  7001. p.t = 'z';
  7002. } else {
  7003. sstr = strs[parseInt(p.v, 10)];
  7004. p.v = sstr.t;
  7005. p.r = sstr.r;
  7006. if(opts.cellHTML) p.h = sstr.h;
  7007. }
  7008. break;
  7009. case 'str':
  7010. p.t = "s";
  7011. p.v = (p.v!=null) ? utf8read(p.v) : '';
  7012. if(opts.cellHTML) p.h = escapehtml(p.v);
  7013. break;
  7014. case 'inlineStr':
  7015. cref = d.match(isregex);
  7016. p.t = 's';
  7017. if(cref != null && (sstr = parse_si(cref[1]))) {
  7018. p.v = sstr.t;
  7019. if(opts.cellHTML) p.h = sstr.h;
  7020. } else p.v = "";
  7021. break;
  7022. case 'b': p.v = parsexmlbool(p.v); break;
  7023. case 'd':
  7024. if(opts.cellDates) p.v = parseDate(p.v, 1);
  7025. else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
  7026. break;
  7027. /* error string in .w, number in .v */
  7028. case 'e':
  7029. if(!opts || opts.cellText !== false) p.w = p.v;
  7030. p.v = RBErr[p.v]; break;
  7031. }
  7032. /* formatting */
  7033. fmtid = fillid = 0;
  7034. cf = null;
  7035. if(do_format && tag.s !== undefined) {
  7036. cf = styles.CellXf[tag.s];
  7037. if(cf != null) {
  7038. if(cf.numFmtId != null) fmtid = cf.numFmtId;
  7039. if(opts.cellStyles) {
  7040. if(cf.fillId != null) fillid = cf.fillId;
  7041. }
  7042. }
  7043. }
  7044. safe_format(p, fmtid, fillid, opts, themes, styles);
  7045. if(opts.cellDates && do_format && p.t == 'n' && SSF.is_date(SSF._table[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
  7046. if(dense) {
  7047. var _r = decode_cell(tag.r);
  7048. if(!s[_r.r]) s[_r.r] = [];
  7049. s[_r.r][_r.c] = p;
  7050. } else s[tag.r] = p;
  7051. }
  7052. }
  7053. if(rows.length > 0) s['!rows'] = rows;
  7054. }; })();
  7055. function write_ws_xml_data(ws, opts, idx, wb) {
  7056. var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
  7057. var dense = Array.isArray(ws);
  7058. var params = ({r:rr}), row, height = -1;
  7059. for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
  7060. for(R = range.s.r; R <= range.e.r; ++R) {
  7061. r = [];
  7062. rr = encode_row(R);
  7063. for(C = range.s.c; C <= range.e.c; ++C) {
  7064. ref = cols[C] + rr;
  7065. var _cell = dense ? (ws[R]||[])[C]: ws[ref];
  7066. if(_cell === undefined) continue;
  7067. if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
  7068. }
  7069. if(r.length > 0 || (rows && rows[R])) {
  7070. params = ({r:rr});
  7071. if(rows && rows[R]) {
  7072. row = rows[R];
  7073. if(row.hidden) params.hidden = 1;
  7074. height = -1;
  7075. if(row.hpx) height = px2pt(row.hpx);
  7076. else if(row.hpt) height = row.hpt;
  7077. if(height > -1) { params.ht = height; params.customHeight = 1; }
  7078. if(row.level) { params.outlineLevel = row.level; }
  7079. }
  7080. o[o.length] = (writextag('row', r.join(""), params));
  7081. }
  7082. }
  7083. if(rows) for(; R < rows.length; ++R) {
  7084. if(rows && rows[R]) {
  7085. params = ({r:R+1});
  7086. row = rows[R];
  7087. if(row.hidden) params.hidden = 1;
  7088. height = -1;
  7089. if (row.hpx) height = px2pt(row.hpx);
  7090. else if (row.hpt) height = row.hpt;
  7091. if (height > -1) { params.ht = height; params.customHeight = 1; }
  7092. if (row.level) { params.outlineLevel = row.level; }
  7093. o[o.length] = (writextag('row', "", params));
  7094. }
  7095. }
  7096. return o.join("");
  7097. }
  7098. var WS_XML_ROOT = writextag('worksheet', null, {
  7099. 'xmlns': XMLNS.main[0],
  7100. 'xmlns:r': XMLNS.r
  7101. });
  7102. function write_ws_xml(idx, opts, wb, rels) {
  7103. var o = [XML_HEADER, WS_XML_ROOT];
  7104. var s = wb.SheetNames[idx], sidx = 0, rdata = "";
  7105. var ws = wb.Sheets[s];
  7106. if(ws == null) ws = {};
  7107. var ref = ws['!ref'] || 'A1';
  7108. var range = safe_decode_range(ref);
  7109. if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
  7110. if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
  7111. range.e.c = Math.min(range.e.c, 0x3FFF);
  7112. range.e.r = Math.min(range.e.c, 0xFFFFF);
  7113. ref = encode_range(range);
  7114. }
  7115. if(!rels) rels = {};
  7116. ws['!comments'] = [];
  7117. var _drawing = [];
  7118. write_ws_xml_sheetpr(ws, wb, idx, opts, o);
  7119. o[o.length] = (writextag('dimension', null, {'ref': ref}));
  7120. o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
  7121. /* TODO: store in WB, process styles */
  7122. if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
  7123. defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
  7124. baseColWidth:opts.sheetFormat.baseColWidth||'10',
  7125. outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
  7126. }));
  7127. if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
  7128. o[sidx = o.length] = '<sheetData/>';
  7129. ws['!links'] = [];
  7130. if(ws['!ref'] != null) {
  7131. rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
  7132. if(rdata.length > 0) o[o.length] = (rdata);
  7133. }
  7134. if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
  7135. /* sheetCalcPr */
  7136. if(ws['!protect']) o[o.length] = write_ws_xml_protection(ws['!protect']);
  7137. /* protectedRanges */
  7138. /* scenarios */
  7139. if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
  7140. /* sortState */
  7141. /* dataConsolidate */
  7142. /* customSheetViews */
  7143. if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
  7144. /* phoneticPr */
  7145. /* conditionalFormatting */
  7146. /* dataValidations */
  7147. var relc = -1, rel, rId = -1;
  7148. if(ws['!links'].length > 0) {
  7149. o[o.length] = "<hyperlinks>";
  7150. ws['!links'].forEach(function(l) {
  7151. if(!l[1].Target) return;
  7152. rel = ({"ref":l[0]});
  7153. if(l[1].Target.charAt(0) != "#") {
  7154. rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
  7155. rel["r:id"] = "rId"+rId;
  7156. }
  7157. if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
  7158. if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
  7159. o[o.length] = writextag("hyperlink",null,rel);
  7160. });
  7161. o[o.length] = "</hyperlinks>";
  7162. }
  7163. delete ws['!links'];
  7164. /* printOptions */
  7165. if(ws['!margins'] != null) o[o.length] = write_ws_xml_margins(ws['!margins']);
  7166. /* pageSetup */
  7167. /* headerFooter */
  7168. /* rowBreaks */
  7169. /* colBreaks */
  7170. /* customProperties */
  7171. /* cellWatches */
  7172. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
  7173. /* smartTags */
  7174. if(_drawing.length > 0) {
  7175. rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  7176. o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
  7177. ws['!drawing'] = _drawing;
  7178. }
  7179. if(ws['!comments'].length > 0) {
  7180. rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  7181. o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
  7182. ws['!legacy'] = rId;
  7183. }
  7184. /* legacyDrawingHF */
  7185. /* picture */
  7186. /* oleObjects */
  7187. /* controls */
  7188. /* webPublishItems */
  7189. /* tableParts */
  7190. /* extLst */
  7191. if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
  7192. return o.join("");
  7193. }
  7194. RELS.CHART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
  7195. RELS.CHARTEX = "http://schemas.microsoft.com/office/2014/relationships/chartEx";
  7196. function parse_Cache(data) {
  7197. var col = [];
  7198. var num = data.match(/^<c:numCache>/);
  7199. var f;
  7200. /* 21.2.2.150 pt CT_NumVal */
  7201. (data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
  7202. var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
  7203. if(!q) return;
  7204. col[+q[1]] = num ? +q[2] : q[2];
  7205. });
  7206. /* 21.2.2.71 formatCode CT_Xstring */
  7207. var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);
  7208. (data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });
  7209. return [col, nf, f];
  7210. }
  7211. /* 21.2 DrawingML - Charts */
  7212. function parse_chart(data, name, opts, rels, wb, csheet) {
  7213. var cs = ((csheet || {"!type":"chart"}));
  7214. if(!data) return csheet;
  7215. /* 21.2.2.27 chart CT_Chart */
  7216. var C = 0, R = 0, col = "A";
  7217. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  7218. /* 21.2.2.120 numCache CT_NumData */
  7219. (data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
  7220. var cache = parse_Cache(nc);
  7221. refguess.s.r = refguess.s.c = 0;
  7222. refguess.e.c = C;
  7223. col = encode_col(C);
  7224. cache[0].forEach(function(n,i) {
  7225. cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
  7226. R = i;
  7227. });
  7228. if(refguess.e.r < R) refguess.e.r = R;
  7229. ++C;
  7230. });
  7231. if(C > 0) cs["!ref"] = encode_range(refguess);
  7232. return cs;
  7233. }
  7234. RELS.CS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet";
  7235. var CS_XML_ROOT = writextag('chartsheet', null, {
  7236. 'xmlns': XMLNS.main[0],
  7237. 'xmlns:r': XMLNS.r
  7238. });
  7239. /* 18.3 Worksheets also covers Chartsheets */
  7240. function parse_cs_xml(data, opts, idx, rels, wb) {
  7241. if(!data) return data;
  7242. /* 18.3.1.12 chartsheet CT_ChartSheet */
  7243. if(!rels) rels = {'!id':{}};
  7244. var s = ({'!type':"chart", '!drawel':null, '!rel':""});
  7245. var m;
  7246. /* 18.3.1.83 sheetPr CT_ChartsheetPr */
  7247. var sheetPr = data.match(sheetprregex);
  7248. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  7249. /* 18.3.1.36 drawing CT_Drawing */
  7250. if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];
  7251. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  7252. return s;
  7253. }
  7254. function write_cs_xml(idx, opts, wb, rels) {
  7255. var o = [XML_HEADER, CS_XML_ROOT];
  7256. o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
  7257. add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  7258. if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
  7259. return o.join("");
  7260. }
  7261. /* [MS-XLSB] 2.4.331 BrtCsProp */
  7262. function parse_BrtCsProp(data, length) {
  7263. data.l += 10;
  7264. var name = parse_XLWideString(data, length - 10);
  7265. return { name: name };
  7266. }
  7267. /* [MS-XLSB] 2.1.7.7 Chart Sheet */
  7268. function parse_cs_bin(data, opts, idx, rels, wb) {
  7269. if(!data) return data;
  7270. if(!rels) rels = {'!id':{}};
  7271. var s = {'!type':"chart", '!drawel':null, '!rel':""};
  7272. var state = [];
  7273. var pass = false;
  7274. recordhopper(data, function cs_parse(val, R_n, RT) {
  7275. switch(RT) {
  7276. case 0x0226: /* 'BrtDrawing' */
  7277. s['!rel'] = val; break;
  7278. case 0x028B: /* 'BrtCsProp' */
  7279. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  7280. if(val.name) wb.Sheets[idx].CodeName = val.name;
  7281. break;
  7282. case 0x0232: /* 'BrtBkHim' */
  7283. case 0x028C: /* 'BrtCsPageSetup' */
  7284. case 0x029D: /* 'BrtCsProtection' */
  7285. case 0x02A7: /* 'BrtCsProtectionIso' */
  7286. case 0x0227: /* 'BrtLegacyDrawing' */
  7287. case 0x0228: /* 'BrtLegacyDrawingHF' */
  7288. case 0x01DC: /* 'BrtMargins' */
  7289. case 0x0C00: /* 'BrtUid' */
  7290. break;
  7291. case 0x0023: /* 'BrtFRTBegin' */
  7292. pass = true; break;
  7293. case 0x0024: /* 'BrtFRTEnd' */
  7294. pass = false; break;
  7295. case 0x0025: /* 'BrtACBegin' */
  7296. state.push(R_n); break;
  7297. case 0x0026: /* 'BrtACEnd' */
  7298. state.pop(); break;
  7299. default:
  7300. if((R_n||"").indexOf("Begin") > 0) state.push(R_n);
  7301. else if((R_n||"").indexOf("End") > 0) state.pop();
  7302. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  7303. }
  7304. }, opts);
  7305. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  7306. return s;
  7307. }
  7308. function write_cs_bin() {
  7309. var ba = buf_array();
  7310. write_record(ba, "BrtBeginSheet");
  7311. /* [BrtCsProp] */
  7312. /* CSVIEWS */
  7313. /* [[BrtCsProtectionIso] BrtCsProtection] */
  7314. /* [USERCSVIEWS] */
  7315. /* [BrtMargins] */
  7316. /* [BrtCsPageSetup] */
  7317. /* [HEADERFOOTER] */
  7318. /* BrtDrawing */
  7319. /* [BrtLegacyDrawing] */
  7320. /* [BrtLegacyDrawingHF] */
  7321. /* [BrtBkHim] */
  7322. /* [WEBPUBITEMS] */
  7323. /* FRTCHARTSHEET */
  7324. write_record(ba, "BrtEndSheet");
  7325. return ba.end();
  7326. }
  7327. /* 18.2.28 (CT_WorkbookProtection) Defaults */
  7328. var WBPropsDef = [
  7329. ['allowRefreshQuery', false, "bool"],
  7330. ['autoCompressPictures', true, "bool"],
  7331. ['backupFile', false, "bool"],
  7332. ['checkCompatibility', false, "bool"],
  7333. ['CodeName', ''],
  7334. ['date1904', false, "bool"],
  7335. ['defaultThemeVersion', 0, "int"],
  7336. ['filterPrivacy', false, "bool"],
  7337. ['hidePivotFieldList', false, "bool"],
  7338. ['promptedSolutions', false, "bool"],
  7339. ['publishItems', false, "bool"],
  7340. ['refreshAllConnections', false, "bool"],
  7341. ['saveExternalLinkValues', true, "bool"],
  7342. ['showBorderUnselectedTables', true, "bool"],
  7343. ['showInkAnnotation', true, "bool"],
  7344. ['showObjects', 'all'],
  7345. ['showPivotChartFilter', false, "bool"],
  7346. ['updateLinks', 'userSet']
  7347. ];
  7348. /* 18.2.30 (CT_BookView) Defaults */
  7349. var WBViewDef = [
  7350. ['activeTab', 0, "int"],
  7351. ['autoFilterDateGrouping', true, "bool"],
  7352. ['firstSheet', 0, "int"],
  7353. ['minimized', false, "bool"],
  7354. ['showHorizontalScroll', true, "bool"],
  7355. ['showSheetTabs', true, "bool"],
  7356. ['showVerticalScroll', true, "bool"],
  7357. ['tabRatio', 600, "int"],
  7358. ['visibility', 'visible']
  7359. //window{Height,Width}, {x,y}Window
  7360. ];
  7361. /* 18.2.19 (CT_Sheet) Defaults */
  7362. var SheetDef = [
  7363. //['state', 'visible']
  7364. ];
  7365. /* 18.2.2 (CT_CalcPr) Defaults */
  7366. var CalcPrDef = [
  7367. ['calcCompleted', 'true'],
  7368. ['calcMode', 'auto'],
  7369. ['calcOnSave', 'true'],
  7370. ['concurrentCalc', 'true'],
  7371. ['fullCalcOnLoad', 'false'],
  7372. ['fullPrecision', 'true'],
  7373. ['iterate', 'false'],
  7374. ['iterateCount', '100'],
  7375. ['iterateDelta', '0.001'],
  7376. ['refMode', 'A1']
  7377. ];
  7378. /* 18.2.3 (CT_CustomWorkbookView) Defaults */
  7379. /*var CustomWBViewDef = [
  7380. ['autoUpdate', 'false'],
  7381. ['changesSavedWin', 'false'],
  7382. ['includeHiddenRowCol', 'true'],
  7383. ['includePrintSettings', 'true'],
  7384. ['maximized', 'false'],
  7385. ['minimized', 'false'],
  7386. ['onlySync', 'false'],
  7387. ['personalView', 'false'],
  7388. ['showComments', 'commIndicator'],
  7389. ['showFormulaBar', 'true'],
  7390. ['showHorizontalScroll', 'true'],
  7391. ['showObjects', 'all'],
  7392. ['showSheetTabs', 'true'],
  7393. ['showStatusbar', 'true'],
  7394. ['showVerticalScroll', 'true'],
  7395. ['tabRatio', '600'],
  7396. ['xWindow', '0'],
  7397. ['yWindow', '0']
  7398. ];*/
  7399. function push_defaults_array(target, defaults) {
  7400. for(var j = 0; j != target.length; ++j) { var w = target[j];
  7401. for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
  7402. if(w[z[0]] == null) w[z[0]] = z[1];
  7403. else switch(z[2]) {
  7404. case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
  7405. case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
  7406. }
  7407. }
  7408. }
  7409. }
  7410. function push_defaults(target, defaults) {
  7411. for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
  7412. if(target[z[0]] == null) target[z[0]] = z[1];
  7413. else switch(z[2]) {
  7414. case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
  7415. case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
  7416. }
  7417. }
  7418. }
  7419. function parse_wb_defaults(wb) {
  7420. push_defaults(wb.WBProps, WBPropsDef);
  7421. push_defaults(wb.CalcPr, CalcPrDef);
  7422. push_defaults_array(wb.WBView, WBViewDef);
  7423. push_defaults_array(wb.Sheets, SheetDef);
  7424. _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
  7425. }
  7426. function safe1904(wb) {
  7427. /* TODO: store date1904 somewhere else */
  7428. if(!wb.Workbook) return "false";
  7429. if(!wb.Workbook.WBProps) return "false";
  7430. return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
  7431. }
  7432. var badchars = "][*?\/\\".split("");
  7433. function check_ws_name(n, safe) {
  7434. if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
  7435. var _good = true;
  7436. badchars.forEach(function(c) {
  7437. if(n.indexOf(c) == -1) return;
  7438. if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
  7439. _good = false;
  7440. });
  7441. return _good;
  7442. }
  7443. function check_wb_names(N, S, codes) {
  7444. N.forEach(function(n,i) {
  7445. check_ws_name(n);
  7446. for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
  7447. if(codes) {
  7448. var cn = (S && S[i] && S[i].CodeName) || n;
  7449. if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
  7450. }
  7451. });
  7452. }
  7453. function check_wb(wb) {
  7454. if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
  7455. if(!wb.SheetNames.length) throw new Error("Workbook is empty");
  7456. var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
  7457. check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
  7458. for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
  7459. /* TODO: validate workbook */
  7460. }
  7461. /* 18.2 Workbook */
  7462. var wbnsregex = /<\w+:workbook/;
  7463. function parse_wb_xml(data, opts) {
  7464. if(!data) throw new Error("Could not find file");
  7465. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" };
  7466. var pass = false, xmlns = "xmlns";
  7467. var dname = {}, dnstart = 0;
  7468. data.replace(tagregex, function xml_wb(x, idx) {
  7469. var y = parsexmltag(x);
  7470. switch(strip_ns(y[0])) {
  7471. case '<?xml': break;
  7472. /* 18.2.27 workbook CT_Workbook 1 */
  7473. case '<workbook':
  7474. if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
  7475. wb.xmlns = y[xmlns];
  7476. break;
  7477. case '</workbook>': break;
  7478. /* 18.2.13 fileVersion CT_FileVersion ? */
  7479. case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
  7480. case '<fileVersion/>': case '</fileVersion>': break;
  7481. /* 18.2.12 fileSharing CT_FileSharing ? */
  7482. case '<fileSharing':
  7483. break;
  7484. case '<fileSharing/>': break;
  7485. /* 18.2.28 workbookPr CT_WorkbookPr ? */
  7486. case '<workbookPr':
  7487. case '<workbookPr/>':
  7488. WBPropsDef.forEach(function(w) {
  7489. if(y[w[0]] == null) return;
  7490. switch(w[2]) {
  7491. case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
  7492. case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
  7493. default: wb.WBProps[w[0]] = y[w[0]];
  7494. }
  7495. });
  7496. if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
  7497. break;
  7498. case '</workbookPr>': break;
  7499. /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
  7500. case '<workbookProtection':
  7501. break;
  7502. case '<workbookProtection/>': break;
  7503. /* 18.2.1 bookViews CT_BookViews ? */
  7504. case '<bookViews': case '<bookViews>': case '</bookViews>': break;
  7505. /* 18.2.30 workbookView CT_BookView + */
  7506. case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
  7507. case '</workbookView>': break;
  7508. /* 18.2.20 sheets CT_Sheets 1 */
  7509. case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
  7510. /* 18.2.19 sheet CT_Sheet + */
  7511. case '<sheet':
  7512. switch(y.state) {
  7513. case "hidden": y.Hidden = 1; break;
  7514. case "veryHidden": y.Hidden = 2; break;
  7515. default: y.Hidden = 0;
  7516. }
  7517. delete y.state;
  7518. y.name = unescapexml(utf8read(y.name));
  7519. delete y[0]; wb.Sheets.push(y); break;
  7520. case '</sheet>': break;
  7521. /* 18.2.15 functionGroups CT_FunctionGroups ? */
  7522. case '<functionGroups': case '<functionGroups/>': break;
  7523. /* 18.2.14 functionGroup CT_FunctionGroup + */
  7524. case '<functionGroup': break;
  7525. /* 18.2.9 externalReferences CT_ExternalReferences ? */
  7526. case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
  7527. /* 18.2.8 externalReference CT_ExternalReference + */
  7528. case '<externalReference': break;
  7529. /* 18.2.6 definedNames CT_DefinedNames ? */
  7530. case '<definedNames/>': break;
  7531. case '<definedNames>': case '<definedNames': pass=true; break;
  7532. case '</definedNames>': pass=false; break;
  7533. /* 18.2.5 definedName CT_DefinedName + */
  7534. case '<definedName': {
  7535. dname = {};
  7536. dname.Name = utf8read(y.name);
  7537. if(y.comment) dname.Comment = y.comment;
  7538. if(y.localSheetId) dname.Sheet = +y.localSheetId;
  7539. if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
  7540. dnstart = idx + x.length;
  7541. } break;
  7542. case '</definedName>': {
  7543. dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
  7544. wb.Names.push(dname);
  7545. } break;
  7546. case '<definedName/>': break;
  7547. /* 18.2.2 calcPr CT_CalcPr ? */
  7548. case '<calcPr': delete y[0]; wb.CalcPr = y; break;
  7549. case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
  7550. case '</calcPr>': break;
  7551. /* 18.2.16 oleSize CT_OleSize ? (ref required) */
  7552. case '<oleSize': break;
  7553. /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
  7554. case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
  7555. /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
  7556. case '<customWorkbookView': case '</customWorkbookView>': break;
  7557. /* 18.2.18 pivotCaches CT_PivotCaches ? */
  7558. case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
  7559. /* 18.2.17 pivotCache CT_PivotCache ? */
  7560. case '<pivotCache': break;
  7561. /* 18.2.21 smartTagPr CT_SmartTagPr ? */
  7562. case '<smartTagPr': case '<smartTagPr/>': break;
  7563. /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
  7564. case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
  7565. /* 18.2.22 smartTagType CT_SmartTagType ? */
  7566. case '<smartTagType': break;
  7567. /* 18.2.24 webPublishing CT_WebPublishing ? */
  7568. case '<webPublishing': case '<webPublishing/>': break;
  7569. /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
  7570. case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
  7571. /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
  7572. case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
  7573. /* 18.2.25 webPublishObject CT_WebPublishObject ? */
  7574. case '<webPublishObject': break;
  7575. /* 18.2.10 extLst CT_ExtensionList ? */
  7576. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  7577. /* 18.2.7 ext CT_Extension + */
  7578. case '<ext': pass=true; break; //TODO: check with versions of excel
  7579. case '</ext>': pass=false; break;
  7580. /* Others */
  7581. case '<ArchID': break;
  7582. case '<AlternateContent':
  7583. case '<AlternateContent>': pass=true; break;
  7584. case '</AlternateContent>': pass=false; break;
  7585. /* TODO */
  7586. case '<revisionPtr': break;
  7587. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
  7588. }
  7589. return x;
  7590. });
  7591. if(XMLNS.main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  7592. parse_wb_defaults(wb);
  7593. return wb;
  7594. }
  7595. var WB_XML_ROOT = writextag('workbook', null, {
  7596. 'xmlns': XMLNS.main[0],
  7597. //'xmlns:mx': XMLNS.mx,
  7598. //'xmlns:s': XMLNS.main[0],
  7599. 'xmlns:r': XMLNS.r
  7600. });
  7601. function write_wb_xml(wb) {
  7602. var o = [XML_HEADER];
  7603. o[o.length] = WB_XML_ROOT;
  7604. var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);
  7605. /* fileVersion */
  7606. /* fileSharing */
  7607. var workbookPr = ({codeName:"ThisWorkbook"});
  7608. if(wb.Workbook && wb.Workbook.WBProps) {
  7609. WBPropsDef.forEach(function(x) {
  7610. if((wb.Workbook.WBProps[x[0]]) == null) return;
  7611. if((wb.Workbook.WBProps[x[0]]) == x[1]) return;
  7612. workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]);
  7613. });
  7614. if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
  7615. }
  7616. o[o.length] = (writextag('workbookPr', null, workbookPr));
  7617. /* workbookProtection */
  7618. var sheets = wb.Workbook && wb.Workbook.Sheets || [];
  7619. var i = 0;
  7620. /* bookViews only written if first worksheet is hidden */
  7621. if(sheets && sheets[0] && !!sheets[0].Hidden) {
  7622. o[o.length] = "<bookViews>";
  7623. for(i = 0; i != wb.SheetNames.length; ++i) {
  7624. if(!sheets[i]) break;
  7625. if(!sheets[i].Hidden) break;
  7626. }
  7627. if(i == wb.SheetNames.length) i = 0;
  7628. o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
  7629. o[o.length] = "</bookViews>";
  7630. }
  7631. o[o.length] = "<sheets>";
  7632. for(i = 0; i != wb.SheetNames.length; ++i) {
  7633. var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))});
  7634. sht.sheetId = ""+(i+1);
  7635. sht["r:id"] = "rId"+(i+1);
  7636. if(sheets[i]) switch(sheets[i].Hidden) {
  7637. case 1: sht.state = "hidden"; break;
  7638. case 2: sht.state = "veryHidden"; break;
  7639. }
  7640. o[o.length] = (writextag('sheet',null,sht));
  7641. }
  7642. o[o.length] = "</sheets>";
  7643. /* functionGroups */
  7644. /* externalReferences */
  7645. if(write_names) {
  7646. o[o.length] = "<definedNames>";
  7647. if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
  7648. var d = {name:n.Name};
  7649. if(n.Comment) d.comment = n.Comment;
  7650. if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
  7651. if(n.Hidden) d.hidden = "1";
  7652. if(!n.Ref) return;
  7653. o[o.length] = writextag('definedName', escapexml(n.Ref), d);
  7654. });
  7655. o[o.length] = "</definedNames>";
  7656. }
  7657. /* calcPr */
  7658. /* oleSize */
  7659. /* customWorkbookViews */
  7660. /* pivotCaches */
  7661. /* smartTagPr */
  7662. /* smartTagTypes */
  7663. /* webPublishing */
  7664. /* fileRecoveryPr */
  7665. /* webPublishObjects */
  7666. /* extLst */
  7667. if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
  7668. return o.join("");
  7669. }
  7670. function parse_wb(data, name, opts) {
  7671. if(name.slice(-4)===".bin") return parse_wb_bin((data), opts);
  7672. return parse_wb_xml((data), opts);
  7673. }
  7674. function parse_ws(data, name, idx, opts, rels, wb, themes, styles) {
  7675. if(name.slice(-4)===".bin") return parse_ws_bin((data), opts, idx, rels, wb, themes, styles);
  7676. return parse_ws_xml((data), opts, idx, rels, wb, themes, styles);
  7677. }
  7678. function parse_cs(data, name, idx, opts, rels, wb, themes, styles) {
  7679. if(name.slice(-4)===".bin") return parse_cs_bin((data), opts, idx, rels, wb, themes, styles);
  7680. return parse_cs_xml((data), opts, idx, rels, wb, themes, styles);
  7681. }
  7682. function parse_ms(data, name, idx, opts, rels, wb, themes, styles) {
  7683. if(name.slice(-4)===".bin") return parse_ms_bin((data), opts, idx, rels, wb, themes, styles);
  7684. return parse_ms_xml((data), opts, idx, rels, wb, themes, styles);
  7685. }
  7686. function parse_ds(data, name, idx, opts, rels, wb, themes, styles) {
  7687. if(name.slice(-4)===".bin") return parse_ds_bin((data), opts, idx, rels, wb, themes, styles);
  7688. return parse_ds_xml((data), opts, idx, rels, wb, themes, styles);
  7689. }
  7690. function parse_sty(data, name, themes, opts) {
  7691. if(name.slice(-4)===".bin") return parse_sty_bin((data), themes, opts);
  7692. return parse_sty_xml((data), themes, opts);
  7693. }
  7694. function parse_theme(data, name, opts) {
  7695. return parse_theme_xml(data, opts);
  7696. }
  7697. function parse_sst(data, name, opts) {
  7698. if(name.slice(-4)===".bin") return parse_sst_bin((data), opts);
  7699. return parse_sst_xml((data), opts);
  7700. }
  7701. function parse_cmnt(data, name, opts) {
  7702. if(name.slice(-4)===".bin") return parse_comments_bin((data), opts);
  7703. return parse_comments_xml((data), opts);
  7704. }
  7705. function parse_cc(data, name, opts) {
  7706. if(name.slice(-4)===".bin") return parse_cc_bin((data), name, opts);
  7707. return parse_cc_xml((data), name, opts);
  7708. }
  7709. function parse_xlink(data, rel, name, opts) {
  7710. if(name.slice(-4)===".bin") return parse_xlink_bin((data), rel, name, opts);
  7711. return parse_xlink_xml((data), rel, name, opts);
  7712. }
  7713. function write_wb(wb, name, opts) {
  7714. return (name.slice(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
  7715. }
  7716. function write_ws(data, name, opts, wb, rels) {
  7717. return (name.slice(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb, rels);
  7718. }
  7719. // eslint-disable-next-line no-unused-vars
  7720. function write_cs(data, name, opts, wb, rels) {
  7721. return (name.slice(-4)===".bin" ? write_cs_bin : write_cs_xml)(data, opts, wb, rels);
  7722. }
  7723. function write_sty(data, name, opts) {
  7724. return (name.slice(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
  7725. }
  7726. function write_sst(data, name, opts) {
  7727. return (name.slice(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
  7728. }
  7729. function write_cmnt(data, name, opts) {
  7730. return (name.slice(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
  7731. }
  7732. /*
  7733. function write_cc(data, name:string, opts) {
  7734. return (name.slice(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
  7735. }
  7736. */
  7737. /* note: browser DOM element cannot see mso- style attrs, must parse */
  7738. var HTML_ = (function() {
  7739. function html_to_sheet(str, _opts) {
  7740. var opts = _opts || {};
  7741. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  7742. var ws = opts.dense ? ([]) : ({});
  7743. str = str.replace(/<!--.*?-->/g, "");
  7744. var mtch = str.match(/<table/i);
  7745. if(!mtch) throw new Error("Invalid HTML: could not find <table>");
  7746. var mtch2 = str.match(/<\/table/i);
  7747. var i = mtch.index, j = mtch2 && mtch2.index || str.length;
  7748. var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
  7749. var R = -1, C = 0, RS = 0, CS = 0;
  7750. var range = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
  7751. var merges = [];
  7752. for(i = 0; i < rows.length; ++i) {
  7753. var row = rows[i].trim();
  7754. var hd = row.slice(0,3).toLowerCase();
  7755. if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
  7756. if(hd != "<td" && hd != "<th") continue;
  7757. var cells = row.split(/<\/t[dh]>/i);
  7758. for(j = 0; j < cells.length; ++j) {
  7759. var cell = cells[j].trim();
  7760. if(!cell.match(/<t[dh]/i)) continue;
  7761. var m = cell, cc = 0;
  7762. /* TODO: parse styles etc */
  7763. while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
  7764. for(var midx = 0; midx < merges.length; ++midx) {
  7765. var _merge = merges[midx];
  7766. if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
  7767. }
  7768. var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
  7769. CS = tag.colspan ? +tag.colspan : 1;
  7770. if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
  7771. var _t = tag.t || tag["data-t"] || "";
  7772. /* TODO: generate stub cells */
  7773. if(!m.length) { C += CS; continue; }
  7774. m = htmldecode(m);
  7775. if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
  7776. if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
  7777. if(!m.length) continue;
  7778. var o = {t:'s', v:m};
  7779. if(opts.raw || !m.trim().length || _t == 's'){}
  7780. else if(m === 'TRUE') o = {t:'b', v:true};
  7781. else if(m === 'FALSE') o = {t:'b', v:false};
  7782. else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
  7783. else if(!isNaN(fuzzydate(m).getDate())) {
  7784. o = ({t:'d', v:parseDate(m)});
  7785. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  7786. o.z = opts.dateNF || SSF._table[14];
  7787. }
  7788. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
  7789. else ws[encode_cell({r:R, c:C})] = o;
  7790. C += CS;
  7791. }
  7792. }
  7793. ws['!ref'] = encode_range(range);
  7794. if(merges.length) ws["!merges"] = merges;
  7795. return ws;
  7796. }
  7797. function html_to_book(str, opts) {
  7798. var mtch = str.match(/<table.*?>[\s\S]*?<\/table>/gi);
  7799. if(!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find <table>");
  7800. if(mtch.length == 1) return sheet_to_workbook(html_to_sheet(mtch[0], opts), opts);
  7801. var wb = utils.book_new();
  7802. mtch.forEach(function(s, idx) { utils.book_append_sheet(wb, html_to_sheet(s, opts), "Sheet" + (idx+1)); });
  7803. return wb;
  7804. }
  7805. function make_html_row(ws, r, R, o) {
  7806. var M = (ws['!merges'] ||[]);
  7807. var oo = [];
  7808. for(var C = r.s.c; C <= r.e.c; ++C) {
  7809. var RS = 0, CS = 0;
  7810. for(var j = 0; j < M.length; ++j) {
  7811. if(M[j].s.r > R || M[j].s.c > C) continue;
  7812. if(M[j].e.r < R || M[j].e.c < C) continue;
  7813. if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
  7814. RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
  7815. }
  7816. if(RS < 0) continue;
  7817. var coord = encode_cell({r:R,c:C});
  7818. var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
  7819. /* TODO: html entities */
  7820. var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
  7821. var sp = ({});
  7822. if(RS > 1) sp.rowspan = RS;
  7823. if(CS > 1) sp.colspan = CS;
  7824. if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
  7825. else if(cell) {
  7826. sp["data-t"] = cell && cell.t || 'z';
  7827. if(cell.v != null) sp["data-v"] = cell.v;
  7828. if(cell.z != null) sp["data-z"] = cell.z;
  7829. if(cell.l && (cell.l.Target || "#").charAt(0) != "#") w = '<a href="' + cell.l.Target +'">' + w + '</a>';
  7830. }
  7831. sp.id = (o.id || "sjs") + "-" + coord;
  7832. oo.push(writextag('td', w, sp));
  7833. }
  7834. var preamble = "<tr>";
  7835. return preamble + oo.join("") + "</tr>";
  7836. }
  7837. function make_html_preamble(ws, R, o) {
  7838. var out = [];
  7839. return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
  7840. }
  7841. var _BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
  7842. var _END = '</body></html>';
  7843. function sheet_to_html(ws, opts/*, wb:?Workbook*/) {
  7844. var o = opts || {};
  7845. var header = o.header != null ? o.header : _BEGIN;
  7846. var footer = o.footer != null ? o.footer : _END;
  7847. var out = [header];
  7848. var r = decode_range(ws['!ref']);
  7849. o.dense = Array.isArray(ws);
  7850. out.push(make_html_preamble(ws, r, o));
  7851. for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
  7852. out.push("</table>" + footer);
  7853. return out.join("");
  7854. }
  7855. return {
  7856. to_workbook: html_to_book,
  7857. to_sheet: html_to_sheet,
  7858. _row: make_html_row,
  7859. BEGIN: _BEGIN,
  7860. END: _END,
  7861. _preamble: make_html_preamble,
  7862. from_sheet: sheet_to_html
  7863. };
  7864. })();
  7865. function sheet_add_dom(ws, table, _opts) {
  7866. var opts = _opts || {};
  7867. if(DENSE != null) opts.dense = DENSE;
  7868. var or_R = 0, or_C = 0;
  7869. if(opts.origin != null) {
  7870. if(typeof opts.origin == 'number') or_R = opts.origin;
  7871. else {
  7872. var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
  7873. or_R = _origin.r; or_C = _origin.c;
  7874. }
  7875. }
  7876. var rows = table.getElementsByTagName('tr');
  7877. var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
  7878. var range = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
  7879. if(ws["!ref"]) {
  7880. var _range = decode_range(ws["!ref"]);
  7881. range.s.r = Math.min(range.s.r, _range.s.r);
  7882. range.s.c = Math.min(range.s.c, _range.s.c);
  7883. range.e.r = Math.max(range.e.r, _range.e.r);
  7884. range.e.c = Math.max(range.e.c, _range.e.c);
  7885. if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
  7886. }
  7887. var merges = [], midx = 0;
  7888. var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  7889. var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  7890. if(!ws["!cols"]) ws['!cols'] = [];
  7891. for(; _R < rows.length && R < sheetRows; ++_R) {
  7892. var row = rows[_R];
  7893. if (is_dom_element_hidden(row)) {
  7894. if (opts.display) continue;
  7895. rowinfo[R] = {hidden: true};
  7896. }
  7897. var elts = (row.children);
  7898. for(_C = C = 0; _C < elts.length; ++_C) {
  7899. var elt = elts[_C];
  7900. if (opts.display && is_dom_element_hidden(elt)) continue;
  7901. var v = elt.hasAttribute('data-v') ? elt.getAttribute('data-v') : elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
  7902. var z = elt.getAttribute('data-z') || elt.getAttribute('z');
  7903. for(midx = 0; midx < merges.length; ++midx) {
  7904. var m = merges[midx];
  7905. if(m.s.c == C + or_C && m.s.r < R + or_R && R + or_R <= m.e.r) { C = m.e.c+1 - or_C; midx = -1; }
  7906. }
  7907. /* TODO: figure out how to extract nonstandard mso- style */
  7908. CS = +elt.getAttribute("colspan") || 1;
  7909. if( ((RS = (+elt.getAttribute("rowspan") || 1)))>1 || CS>1) merges.push({s:{r:R + or_R,c:C + or_C},e:{r:R + or_R + (RS||1) - 1, c:C + or_C + (CS||1) - 1}});
  7910. var o = {t:'s', v:v};
  7911. var _t = elt.getAttribute("data-t") || elt.getAttribute("t") || "";
  7912. if(v != null) {
  7913. if(v.length == 0) o.t = _t || 'z';
  7914. else if(opts.raw || v.trim().length == 0 || _t == "s"){}
  7915. else if(v === 'TRUE') o = {t:'b', v:true};
  7916. else if(v === 'FALSE') o = {t:'b', v:false};
  7917. else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
  7918. else if(!isNaN(fuzzydate(v).getDate())) {
  7919. o = ({t:'d', v:parseDate(v)});
  7920. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  7921. o.z = opts.dateNF || SSF._table[14];
  7922. }
  7923. }
  7924. if(o.z === undefined && z != null) o.z = z;
  7925. /* The first link is used. Links are assumed to be fully specified.
  7926. * TODO: The right way to process relative links is to make a new <a> */
  7927. var l = "", Aelts = elt.getElementsByTagName("A");
  7928. if(Aelts && Aelts.length) for(var Aelti = 0; Aelti < Aelts.length; ++Aelti) if(Aelts[Aelti].hasAttribute("href")) {
  7929. l = Aelts[Aelti].getAttribute("href"); if(l.charAt(0) != "#") break;
  7930. }
  7931. if(l && l.charAt(0) != "#") o.l = ({ Target: l });
  7932. if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
  7933. else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
  7934. if(range.e.c < C + or_C) range.e.c = C + or_C;
  7935. C += CS;
  7936. }
  7937. ++R;
  7938. }
  7939. if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
  7940. range.e.r = Math.max(range.e.r, R - 1 + or_R);
  7941. ws['!ref'] = encode_range(range);
  7942. if(R >= sheetRows) ws['!fullref'] = encode_range((range.e.r = rows.length-_R+R-1 + or_R,range)); // We can count the real number of rows to parse but we don't to improve the performance
  7943. return ws;
  7944. }
  7945. function parse_dom_table(table, _opts) {
  7946. var opts = _opts || {};
  7947. var ws = opts.dense ? ([]) : ({});
  7948. return sheet_add_dom(ws, table, _opts);
  7949. }
  7950. function table_to_book(table, opts) {
  7951. return sheet_to_workbook(parse_dom_table(table, opts), opts);
  7952. }
  7953. function is_dom_element_hidden(element) {
  7954. var display = '';
  7955. var get_computed_style = get_get_computed_style_function(element);
  7956. if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
  7957. if(!display) display = element.style.display; // Fallback for cases when getComputedStyle is not available (e.g. an old browser or some Node.js environments) or doesn't work (e.g. if the element is not inserted to a document)
  7958. return display === 'none';
  7959. }
  7960. /* global getComputedStyle */
  7961. function get_get_computed_style_function(element) {
  7962. // The proper getComputedStyle implementation is the one defined in the element window
  7963. if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
  7964. // If it is not available, try to get one from the global namespace
  7965. if(typeof getComputedStyle === 'function') return getComputedStyle;
  7966. return null;
  7967. }
  7968. /* OpenDocument */
  7969. var parse_content_xml = (function() {
  7970. var parse_text_p = function(text) {
  7971. /* 6.1.2 White Space Characters */
  7972. var fixed = text
  7973. .replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ")
  7974. .replace(/<text:s\/>/g," ")
  7975. .replace(/<text:s text:c="(\d+)"\/>/g, function($$,$1) { return Array(parseInt($1,10)+1).join(" "); })
  7976. .replace(/<text:tab[^>]*\/>/g,"\t")
  7977. .replace(/<text:line-break\/>/g,"\n");
  7978. var v = unescapexml(fixed.replace(/<[^>]*>/g,""));
  7979. return [v];
  7980. };
  7981. var number_formats = {
  7982. /* ods name: [short ssf fmt, long ssf fmt] */
  7983. day: ["d", "dd"],
  7984. month: ["m", "mm"],
  7985. year: ["y", "yy"],
  7986. hours: ["h", "hh"],
  7987. minutes: ["m", "mm"],
  7988. seconds: ["s", "ss"],
  7989. "am-pm": ["A/P", "AM/PM"],
  7990. "day-of-week": ["ddd", "dddd"],
  7991. era: ["e", "ee"],
  7992. /* there is no native representation of LO "Q" format */
  7993. quarter: ["\\Qm", "m\\\"th quarter\""]
  7994. };
  7995. return function pcx(d, _opts) {
  7996. var opts = _opts || {};
  7997. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  7998. var str = xlml_normalize(d);
  7999. var state = [], tmp;
  8000. var tag;
  8001. var NFtag = {name:""}, NF = "", pidx = 0;
  8002. var sheetag;
  8003. var rowtag;
  8004. var Sheets = {}, SheetNames = [];
  8005. var ws = opts.dense ? ([]) : ({});
  8006. var Rn, q;
  8007. var ctag = ({value:""});
  8008. var textp = "", textpidx = 0, textptag;
  8009. var textR = [];
  8010. var R = -1, C = -1, range = {s: {r:1000000,c:10000000}, e: {r:0, c:0}};
  8011. var row_ol = 0;
  8012. var number_format_map = {};
  8013. var merges = [], mrange = {}, mR = 0, mC = 0;
  8014. var rowinfo = [], rowpeat = 1, colpeat = 1;
  8015. var arrayf = [];
  8016. var WB = {Names:[]};
  8017. var atag = ({});
  8018. var _Ref = ["", ""];
  8019. var comments = [], comment = ({});
  8020. var creator = "", creatoridx = 0;
  8021. var isstub = false, intable = false;
  8022. var i = 0;
  8023. xlmlregex.lastIndex = 0;
  8024. str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  8025. while((Rn = xlmlregex.exec(str))) switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {
  8026. case 'table': case '工作表': // 9.1.2 <table:table>
  8027. if(Rn[1]==='/') {
  8028. if(range.e.c >= range.s.c && range.e.r >= range.s.r) ws['!ref'] = encode_range(range);
  8029. else ws['!ref'] = "A1:A1";
  8030. if(opts.sheetRows > 0 && opts.sheetRows <= range.e.r) {
  8031. ws['!fullref'] = ws['!ref'];
  8032. range.e.r = opts.sheetRows - 1;
  8033. ws['!ref'] = encode_range(range);
  8034. }
  8035. if(merges.length) ws['!merges'] = merges;
  8036. if(rowinfo.length) ws["!rows"] = rowinfo;
  8037. sheetag.name = sheetag['名称'] || sheetag.name;
  8038. if(typeof JSON !== 'undefined') JSON.stringify(sheetag);
  8039. SheetNames.push(sheetag.name);
  8040. Sheets[sheetag.name] = ws;
  8041. intable = false;
  8042. }
  8043. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  8044. sheetag = parsexmltag(Rn[0], false);
  8045. R = C = -1;
  8046. range.s.r = range.s.c = 10000000; range.e.r = range.e.c = 0;
  8047. ws = opts.dense ? ([]) : ({}); merges = [];
  8048. rowinfo = [];
  8049. intable = true;
  8050. }
  8051. break;
  8052. case 'table-row-group': // 9.1.9 <table:table-row-group>
  8053. if(Rn[1] === "/") --row_ol; else ++row_ol;
  8054. break;
  8055. case 'table-row': case '行': // 9.1.3 <table:table-row>
  8056. if(Rn[1] === '/') { R+=rowpeat; rowpeat = 1; break; }
  8057. rowtag = parsexmltag(Rn[0], false);
  8058. if(rowtag['行号']) R = rowtag['行号'] - 1; else if(R == -1) R = 0;
  8059. rowpeat = +rowtag['number-rows-repeated'] || 1;
  8060. /* TODO: remove magic */
  8061. if(rowpeat < 10) for(i = 0; i < rowpeat; ++i) if(row_ol > 0) rowinfo[R + i] = {level: row_ol};
  8062. C = -1; break;
  8063. case 'covered-table-cell': // 9.1.5 <table:covered-table-cell>
  8064. if(Rn[1] !== '/') ++C;
  8065. if(opts.sheetStubs) {
  8066. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = {t:'z'}; }
  8067. else ws[encode_cell({r:R,c:C})] = {t:'z'};
  8068. }
  8069. textp = ""; textR = [];
  8070. break; /* stub */
  8071. case 'table-cell': case '数据':
  8072. if(Rn[0].charAt(Rn[0].length-2) === '/') {
  8073. ++C;
  8074. ctag = parsexmltag(Rn[0], false);
  8075. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  8076. q = ({t:'z', v:null});
  8077. if(ctag.formula && opts.cellFormula != false) q.f = ods_to_csf_formula(unescapexml(ctag.formula));
  8078. if((ctag['数据类型'] || ctag['value-type']) == "string") {
  8079. q.t = "s"; q.v = unescapexml(ctag['string-value'] || "");
  8080. if(opts.dense) {
  8081. if(!ws[R]) ws[R] = [];
  8082. ws[R][C] = q;
  8083. } else {
  8084. ws[encode_cell({r:R,c:C})] = q;
  8085. }
  8086. }
  8087. C+= colpeat-1;
  8088. } else if(Rn[1]!=='/') {
  8089. ++C;
  8090. textp = ""; textpidx = 0; textR = [];
  8091. colpeat = 1;
  8092. var rptR = rowpeat ? R + rowpeat - 1 : R;
  8093. if(C > range.e.c) range.e.c = C;
  8094. if(C < range.s.c) range.s.c = C;
  8095. if(R < range.s.r) range.s.r = R;
  8096. if(rptR > range.e.r) range.e.r = rptR;
  8097. ctag = parsexmltag(Rn[0], false);
  8098. comments = []; comment = ({});
  8099. q = ({t:ctag['数据类型'] || ctag['value-type'], v:null});
  8100. if(opts.cellFormula) {
  8101. if(ctag.formula) ctag.formula = unescapexml(ctag.formula);
  8102. if(ctag['number-matrix-columns-spanned'] && ctag['number-matrix-rows-spanned']) {
  8103. mR = parseInt(ctag['number-matrix-rows-spanned'],10) || 0;
  8104. mC = parseInt(ctag['number-matrix-columns-spanned'],10) || 0;
  8105. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  8106. q.F = encode_range(mrange);
  8107. arrayf.push([mrange, q.F]);
  8108. }
  8109. if(ctag.formula) q.f = ods_to_csf_formula(ctag.formula);
  8110. else for(i = 0; i < arrayf.length; ++i)
  8111. if(R >= arrayf[i][0].s.r && R <= arrayf[i][0].e.r)
  8112. if(C >= arrayf[i][0].s.c && C <= arrayf[i][0].e.c)
  8113. q.F = arrayf[i][1];
  8114. }
  8115. if(ctag['number-columns-spanned'] || ctag['number-rows-spanned']) {
  8116. mR = parseInt(ctag['number-rows-spanned'],10) || 0;
  8117. mC = parseInt(ctag['number-columns-spanned'],10) || 0;
  8118. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  8119. merges.push(mrange);
  8120. }
  8121. /* 19.675.2 table:number-columns-repeated */
  8122. if(ctag['number-columns-repeated']) colpeat = parseInt(ctag['number-columns-repeated'], 10);
  8123. /* 19.385 office:value-type */
  8124. switch(q.t) {
  8125. case 'boolean': q.t = 'b'; q.v = parsexmlbool(ctag['boolean-value']); break;
  8126. case 'float': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  8127. case 'percentage': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  8128. case 'currency': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  8129. case 'date': q.t = 'd'; q.v = parseDate(ctag['date-value']);
  8130. if(!opts.cellDates) { q.t = 'n'; q.v = datenum(q.v); }
  8131. q.z = 'm/d/yy'; break;
  8132. case 'time': q.t = 'n'; q.v = parse_isodur(ctag['time-value'])/86400;
  8133. if(opts.cellDates) { q.t = 'd'; q.v = numdate(q.v); }
  8134. q.z = 'HH:MM:SS'; break;
  8135. case 'number': q.t = 'n'; q.v = parseFloat(ctag['数据数值']); break;
  8136. default:
  8137. if(q.t === 'string' || q.t === 'text' || !q.t) {
  8138. q.t = 's';
  8139. if(ctag['string-value'] != null) { textp = unescapexml(ctag['string-value']); textR = []; }
  8140. } else throw new Error('Unsupported value type ' + q.t);
  8141. }
  8142. } else {
  8143. isstub = false;
  8144. if(q.t === 's') {
  8145. q.v = textp || '';
  8146. if(textR.length) q.R = textR;
  8147. isstub = textpidx == 0;
  8148. }
  8149. if(atag.Target) q.l = atag;
  8150. if(comments.length > 0) { q.c = comments; comments = []; }
  8151. if(textp && opts.cellText !== false) q.w = textp;
  8152. if(isstub) { q.t = "z"; delete q.v; }
  8153. if(!isstub || opts.sheetStubs) {
  8154. if(!(opts.sheetRows && opts.sheetRows <= R)) {
  8155. for(var rpt = 0; rpt < rowpeat; ++rpt) {
  8156. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  8157. if(opts.dense) {
  8158. if(!ws[R + rpt]) ws[R + rpt] = [];
  8159. ws[R + rpt][C] = rpt == 0 ? q : dup(q);
  8160. while(--colpeat > 0) ws[R + rpt][C + colpeat] = dup(q);
  8161. } else {
  8162. ws[encode_cell({r:R + rpt,c:C})] = q;
  8163. while(--colpeat > 0) ws[encode_cell({r:R + rpt,c:C + colpeat})] = dup(q);
  8164. }
  8165. if(range.e.c <= C) range.e.c = C;
  8166. }
  8167. }
  8168. }
  8169. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  8170. C += colpeat-1; colpeat = 0;
  8171. q = {};
  8172. textp = ""; textR = [];
  8173. }
  8174. atag = ({});
  8175. break; // 9.1.4 <table:table-cell>
  8176. /* pure state */
  8177. case 'document': // TODO: <office:document> is the root for FODS
  8178. case 'document-content': case '电子表格文档': // 3.1.3.2 <office:document-content>
  8179. case 'spreadsheet': case '主体': // 3.7 <office:spreadsheet>
  8180. case 'scripts': // 3.12 <office:scripts>
  8181. case 'styles': // TODO <office:styles>
  8182. case 'font-face-decls': // 3.14 <office:font-face-decls>
  8183. case 'master-styles': // 3.15.4 <office:master-styles> -- relevant for FODS
  8184. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  8185. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  8186. break;
  8187. case 'annotation': // 14.1 <office:annotation>
  8188. if(Rn[1]==='/'){
  8189. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  8190. comment.t = textp;
  8191. if(textR.length) comment.R = textR;
  8192. comment.a = creator;
  8193. comments.push(comment);
  8194. }
  8195. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {state.push([Rn[3], false]);}
  8196. creator = ""; creatoridx = 0;
  8197. textp = ""; textpidx = 0; textR = [];
  8198. break;
  8199. case 'creator': // 4.3.2.7 <dc:creator>
  8200. if(Rn[1]==='/') { creator = str.slice(creatoridx,Rn.index); }
  8201. else creatoridx = Rn.index + Rn[0].length;
  8202. break;
  8203. /* ignore state */
  8204. case 'meta': case '元数据': // TODO: <office:meta> <uof:元数据> FODS/UOF
  8205. case 'settings': // TODO: <office:settings>
  8206. case 'config-item-set': // TODO: <office:config-item-set>
  8207. case 'config-item-map-indexed': // TODO: <office:config-item-map-indexed>
  8208. case 'config-item-map-entry': // TODO: <office:config-item-map-entry>
  8209. case 'config-item-map-named': // TODO: <office:config-item-map-entry>
  8210. case 'shapes': // 9.2.8 <table:shapes>
  8211. case 'frame': // 10.4.2 <draw:frame>
  8212. case 'text-box': // 10.4.3 <draw:text-box>
  8213. case 'image': // 10.4.4 <draw:image>
  8214. case 'data-pilot-tables': // 9.6.2 <table:data-pilot-tables>
  8215. case 'list-style': // 16.30 <text:list-style>
  8216. case 'form': // 13.13 <form:form>
  8217. case 'dde-links': // 9.8 <table:dde-links>
  8218. case 'event-listeners': // TODO
  8219. case 'chart': // TODO
  8220. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  8221. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], false]);
  8222. textp = ""; textpidx = 0; textR = [];
  8223. break;
  8224. case 'scientific-number': // TODO: <number:scientific-number>
  8225. break;
  8226. case 'currency-symbol': // TODO: <number:currency-symbol>
  8227. break;
  8228. case 'currency-style': // TODO: <number:currency-style>
  8229. break;
  8230. case 'number-style': // 16.27.2 <number:number-style>
  8231. case 'percentage-style': // 16.27.9 <number:percentage-style>
  8232. case 'date-style': // 16.27.10 <number:date-style>
  8233. case 'time-style': // 16.27.18 <number:time-style>
  8234. if(Rn[1]==='/'){
  8235. number_format_map[NFtag.name] = NF;
  8236. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  8237. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  8238. NF = "";
  8239. NFtag = parsexmltag(Rn[0], false);
  8240. state.push([Rn[3], true]);
  8241. } break;
  8242. case 'script': break; // 3.13 <office:script>
  8243. case 'libraries': break; // TODO: <ooo:libraries>
  8244. case 'automatic-styles': break; // 3.15.3 <office:automatic-styles>
  8245. case 'default-style': // TODO: <style:default-style>
  8246. case 'page-layout': break; // TODO: <style:page-layout>
  8247. case 'style': // 16.2 <style:style>
  8248. break;
  8249. case 'map': break; // 16.3 <style:map>
  8250. case 'font-face': break; // 16.21 <style:font-face>
  8251. case 'paragraph-properties': break; // 17.6 <style:paragraph-properties>
  8252. case 'table-properties': break; // 17.15 <style:table-properties>
  8253. case 'table-column-properties': break; // 17.16 <style:table-column-properties>
  8254. case 'table-row-properties': break; // 17.17 <style:table-row-properties>
  8255. case 'table-cell-properties': break; // 17.18 <style:table-cell-properties>
  8256. case 'number': // 16.27.3 <number:number>
  8257. switch(state[state.length-1][0]) {
  8258. case 'time-style':
  8259. case 'date-style':
  8260. tag = parsexmltag(Rn[0], false);
  8261. NF += number_formats[Rn[3]][tag.style==='long'?1:0]; break;
  8262. } break;
  8263. case 'fraction': break; // TODO 16.27.6 <number:fraction>
  8264. case 'day': // 16.27.11 <number:day>
  8265. case 'month': // 16.27.12 <number:month>
  8266. case 'year': // 16.27.13 <number:year>
  8267. case 'era': // 16.27.14 <number:era>
  8268. case 'day-of-week': // 16.27.15 <number:day-of-week>
  8269. case 'week-of-year': // 16.27.16 <number:week-of-year>
  8270. case 'quarter': // 16.27.17 <number:quarter>
  8271. case 'hours': // 16.27.19 <number:hours>
  8272. case 'minutes': // 16.27.20 <number:minutes>
  8273. case 'seconds': // 16.27.21 <number:seconds>
  8274. case 'am-pm': // 16.27.22 <number:am-pm>
  8275. switch(state[state.length-1][0]) {
  8276. case 'time-style':
  8277. case 'date-style':
  8278. tag = parsexmltag(Rn[0], false);
  8279. NF += number_formats[Rn[3]][tag.style==='long'?1:0]; break;
  8280. } break;
  8281. case 'boolean-style': break; // 16.27.23 <number:boolean-style>
  8282. case 'boolean': break; // 16.27.24 <number:boolean>
  8283. case 'text-style': break; // 16.27.25 <number:text-style>
  8284. case 'text': // 16.27.26 <number:text>
  8285. if(Rn[0].slice(-2) === "/>") break;
  8286. else if(Rn[1]==="/") switch(state[state.length-1][0]) {
  8287. case 'number-style':
  8288. case 'date-style':
  8289. case 'time-style':
  8290. NF += str.slice(pidx, Rn.index);
  8291. break;
  8292. }
  8293. else pidx = Rn.index + Rn[0].length;
  8294. break;
  8295. case 'named-range': // 9.4.12 <table:named-range>
  8296. tag = parsexmltag(Rn[0], false);
  8297. _Ref = ods_to_csf_3D(tag['cell-range-address']);
  8298. var nrange = ({Name:tag.name, Ref:_Ref[0] + '!' + _Ref[1]});
  8299. if(intable) nrange.Sheet = SheetNames.length;
  8300. WB.Names.push(nrange);
  8301. break;
  8302. case 'text-content': break; // 16.27.27 <number:text-content>
  8303. case 'text-properties': break; // 16.27.27 <style:text-properties>
  8304. case 'embedded-text': break; // 16.27.4 <number:embedded-text>
  8305. case 'body': case '电子表格': break; // 3.3 16.9.6 19.726.3
  8306. case 'forms': break; // 12.25.2 13.2
  8307. case 'table-column': break; // 9.1.6 <table:table-column>
  8308. case 'table-header-rows': break; // 9.1.7 <table:table-header-rows>
  8309. case 'table-rows': break; // 9.1.12 <table:table-rows>
  8310. /* TODO: outline levels */
  8311. case 'table-column-group': break; // 9.1.10 <table:table-column-group>
  8312. case 'table-header-columns': break; // 9.1.11 <table:table-header-columns>
  8313. case 'table-columns': break; // 9.1.12 <table:table-columns>
  8314. case 'null-date': break; // 9.4.2 <table:null-date> TODO: date1904
  8315. case 'graphic-properties': break; // 17.21 <style:graphic-properties>
  8316. case 'calculation-settings': break; // 9.4.1 <table:calculation-settings>
  8317. case 'named-expressions': break; // 9.4.11 <table:named-expressions>
  8318. case 'label-range': break; // 9.4.9 <table:label-range>
  8319. case 'label-ranges': break; // 9.4.10 <table:label-ranges>
  8320. case 'named-expression': break; // 9.4.13 <table:named-expression>
  8321. case 'sort': break; // 9.4.19 <table:sort>
  8322. case 'sort-by': break; // 9.4.20 <table:sort-by>
  8323. case 'sort-groups': break; // 9.4.22 <table:sort-groups>
  8324. case 'tab': break; // 6.1.4 <text:tab>
  8325. case 'line-break': break; // 6.1.5 <text:line-break>
  8326. case 'span': break; // 6.1.7 <text:span>
  8327. case 'p': case '文本串': // 5.1.3 <text:p>
  8328. if(['master-styles'].indexOf(state[state.length-1][0]) > -1) break;
  8329. if(Rn[1]==='/' && (!ctag || !ctag['string-value'])) {
  8330. var ptp = parse_text_p(str.slice(textpidx,Rn.index), textptag);
  8331. textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
  8332. } else { textptag = parsexmltag(Rn[0], false); textpidx = Rn.index + Rn[0].length; }
  8333. break; // <text:p>
  8334. case 's': break; // <text:s>
  8335. case 'database-range': // 9.4.15 <table:database-range>
  8336. if(Rn[1]==='/') break;
  8337. try {
  8338. _Ref = ods_to_csf_3D(parsexmltag(Rn[0])['target-range-address']);
  8339. Sheets[_Ref[0]]['!autofilter'] = { ref:_Ref[1] };
  8340. } catch(e) {/* empty */}
  8341. break;
  8342. case 'date': break; // <*:date>
  8343. case 'object': break; // 10.4.6.2 <draw:object>
  8344. case 'title': case '标题': break; // <*:title> OR <uof:标题>
  8345. case 'desc': break; // <*:desc>
  8346. case 'binary-data': break; // 10.4.5 TODO: b64 blob
  8347. /* 9.2 Advanced Tables */
  8348. case 'table-source': break; // 9.2.6
  8349. case 'scenario': break; // 9.2.6
  8350. case 'iteration': break; // 9.4.3 <table:iteration>
  8351. case 'content-validations': break; // 9.4.4 <table:
  8352. case 'content-validation': break; // 9.4.5 <table:
  8353. case 'help-message': break; // 9.4.6 <table:
  8354. case 'error-message': break; // 9.4.7 <table:
  8355. case 'database-ranges': break; // 9.4.14 <table:database-ranges>
  8356. case 'filter': break; // 9.5.2 <table:filter>
  8357. case 'filter-and': break; // 9.5.3 <table:filter-and>
  8358. case 'filter-or': break; // 9.5.4 <table:filter-or>
  8359. case 'filter-condition': break; // 9.5.5 <table:filter-condition>
  8360. case 'list-level-style-bullet': break; // 16.31 <text:
  8361. case 'list-level-style-number': break; // 16.32 <text:
  8362. case 'list-level-properties': break; // 17.19 <style:
  8363. /* 7.3 Document Fields */
  8364. case 'sender-firstname': // 7.3.6.2
  8365. case 'sender-lastname': // 7.3.6.3
  8366. case 'sender-initials': // 7.3.6.4
  8367. case 'sender-title': // 7.3.6.5
  8368. case 'sender-position': // 7.3.6.6
  8369. case 'sender-email': // 7.3.6.7
  8370. case 'sender-phone-private': // 7.3.6.8
  8371. case 'sender-fax': // 7.3.6.9
  8372. case 'sender-company': // 7.3.6.10
  8373. case 'sender-phone-work': // 7.3.6.11
  8374. case 'sender-street': // 7.3.6.12
  8375. case 'sender-city': // 7.3.6.13
  8376. case 'sender-postal-code': // 7.3.6.14
  8377. case 'sender-country': // 7.3.6.15
  8378. case 'sender-state-or-province': // 7.3.6.16
  8379. case 'author-name': // 7.3.7.1
  8380. case 'author-initials': // 7.3.7.2
  8381. case 'chapter': // 7.3.8
  8382. case 'file-name': // 7.3.9
  8383. case 'template-name': // 7.3.9
  8384. case 'sheet-name': // 7.3.9
  8385. break;
  8386. case 'event-listener':
  8387. break;
  8388. /* TODO: FODS Properties */
  8389. case 'initial-creator':
  8390. case 'creation-date':
  8391. case 'print-date':
  8392. case 'generator':
  8393. case 'document-statistic':
  8394. case 'user-defined':
  8395. case 'editing-duration':
  8396. case 'editing-cycles':
  8397. break;
  8398. /* TODO: FODS Config */
  8399. case 'config-item':
  8400. break;
  8401. /* TODO: style tokens */
  8402. case 'page-number': break; // TODO <text:page-number>
  8403. case 'page-count': break; // TODO <text:page-count>
  8404. case 'time': break; // TODO <text:time>
  8405. /* 9.3 Advanced Table Cells */
  8406. case 'cell-range-source': break; // 9.3.1 <table:
  8407. case 'detective': break; // 9.3.2 <table:
  8408. case 'operation': break; // 9.3.3 <table:
  8409. case 'highlighted-range': break; // 9.3.4 <table:
  8410. /* 9.6 Data Pilot Tables <table: */
  8411. case 'data-pilot-table': // 9.6.3
  8412. case 'source-cell-range': // 9.6.5
  8413. case 'source-service': // 9.6.6
  8414. case 'data-pilot-field': // 9.6.7
  8415. case 'data-pilot-level': // 9.6.8
  8416. case 'data-pilot-subtotals': // 9.6.9
  8417. case 'data-pilot-subtotal': // 9.6.10
  8418. case 'data-pilot-members': // 9.6.11
  8419. case 'data-pilot-member': // 9.6.12
  8420. case 'data-pilot-display-info': // 9.6.13
  8421. case 'data-pilot-sort-info': // 9.6.14
  8422. case 'data-pilot-layout-info': // 9.6.15
  8423. case 'data-pilot-field-reference': // 9.6.16
  8424. case 'data-pilot-groups': // 9.6.17
  8425. case 'data-pilot-group': // 9.6.18
  8426. case 'data-pilot-group-member': // 9.6.19
  8427. break;
  8428. /* 10.3 Drawing Shapes */
  8429. case 'rect': // 10.3.2
  8430. break;
  8431. /* 14.6 DDE Connections */
  8432. case 'dde-connection-decls': // 14.6.2 <text:
  8433. case 'dde-connection-decl': // 14.6.3 <text:
  8434. case 'dde-link': // 14.6.4 <table:
  8435. case 'dde-source': // 14.6.5 <office:
  8436. break;
  8437. case 'properties': break; // 13.7 <form:properties>
  8438. case 'property': break; // 13.8 <form:property>
  8439. case 'a': // 6.1.8 hyperlink
  8440. if(Rn[1]!== '/') {
  8441. atag = parsexmltag(Rn[0], false);
  8442. if(!atag.href) break;
  8443. atag.Target = unescapexml(atag.href); delete atag.href;
  8444. if(atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
  8445. _Ref = ods_to_csf_3D(atag.Target.slice(1));
  8446. atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
  8447. } else if(atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3);
  8448. }
  8449. break;
  8450. /* non-standard */
  8451. case 'table-protection': break;
  8452. case 'data-pilot-grand-total': break; // <table:
  8453. case 'office-document-common-attrs': break; // bare
  8454. default: switch(Rn[2]) {
  8455. case 'dc:': // TODO: properties
  8456. case 'calcext:': // ignore undocumented extensions
  8457. case 'loext:': // ignore undocumented extensions
  8458. case 'ooo:': // ignore undocumented extensions
  8459. case 'chartooo:': // ignore undocumented extensions
  8460. case 'draw:': // TODO: drawing
  8461. case 'style:': // TODO: styles
  8462. case 'chart:': // TODO: charts
  8463. case 'form:': // TODO: forms
  8464. case 'uof:': // TODO: uof
  8465. case '表:': // TODO: uof
  8466. case '字:': // TODO: uof
  8467. break;
  8468. default: if(opts.WTF) throw new Error(Rn);
  8469. }
  8470. }
  8471. var out = ({
  8472. Sheets: Sheets,
  8473. SheetNames: SheetNames,
  8474. Workbook: WB
  8475. });
  8476. if(opts.bookSheets) delete out.Sheets;
  8477. return out;
  8478. };
  8479. })();
  8480. function parse_ods(zip, opts) {
  8481. opts = opts || ({});
  8482. if(safegetzipfile(zip, 'META-INF/manifest.xml')) parse_manifest(getzipdata(zip, 'META-INF/manifest.xml'), opts);
  8483. var content = getzipstr(zip, 'content.xml');
  8484. if(!content) throw new Error("Missing content.xml in ODS / UOF file");
  8485. var wb = parse_content_xml(utf8read(content), opts);
  8486. if(safegetzipfile(zip, 'meta.xml')) wb.Props = parse_core_props(getzipdata(zip, 'meta.xml'));
  8487. return wb;
  8488. }
  8489. function parse_fods(data, opts) {
  8490. return parse_content_xml(data, opts);
  8491. }
  8492. /* OpenDocument */
  8493. var write_styles_ods = (function() {
  8494. var master_styles = [
  8495. '<office:master-styles>',
  8496. '<style:master-page style:name="mp1" style:page-layout-name="mp1">',
  8497. '<style:header/>',
  8498. '<style:header-left style:display="false"/>',
  8499. '<style:footer/>',
  8500. '<style:footer-left style:display="false"/>',
  8501. '</style:master-page>',
  8502. '</office:master-styles>'
  8503. ].join("");
  8504. var payload = '<office:document-styles ' + wxt_helper({
  8505. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  8506. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  8507. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  8508. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  8509. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  8510. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  8511. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  8512. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  8513. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  8514. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  8515. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  8516. 'office:version': "1.2"
  8517. }) + '>' + master_styles + '</office:document-styles>';
  8518. return function wso() {
  8519. return XML_HEADER + payload;
  8520. };
  8521. })();
  8522. var write_content_ods = (function() {
  8523. /* 6.1.2 White Space Characters */
  8524. var write_text_p = function(text) {
  8525. return escapexml(text)
  8526. .replace(/ +/g, function($$){return '<text:s text:c="'+$$.length+'"/>';})
  8527. .replace(/\t/g, "<text:tab/>")
  8528. .replace(/\n/g, "</text:p><text:p>")
  8529. .replace(/^ /, "<text:s/>").replace(/ $/, "<text:s/>");
  8530. };
  8531. var null_cell_xml = ' <table:table-cell />\n';
  8532. var covered_cell_xml = ' <table:covered-table-cell/>\n';
  8533. var write_ws = function(ws, wb, i) {
  8534. /* Section 9 Tables */
  8535. var o = [];
  8536. o.push(' <table:table table:name="' + escapexml(wb.SheetNames[i]) + '" table:style-name="ta1">\n');
  8537. var R=0,C=0, range = decode_range(ws['!ref']||"A1");
  8538. var marr = ws['!merges'] || [], mi = 0;
  8539. var dense = Array.isArray(ws);
  8540. if(ws["!cols"]) {
  8541. for(C = 0; C <= range.e.c; ++C) o.push(' <table:table-column' + (ws["!cols"][C] ? ' table:style-name="co' + ws["!cols"][C].ods + '"' : '') + '></table:table-column>\n');
  8542. }
  8543. var H = "", ROWS = ws["!rows"]||[];
  8544. for(R = 0; R < range.s.r; ++R) {
  8545. H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
  8546. o.push(' <table:table-row' + H + '></table:table-row>\n');
  8547. }
  8548. for(; R <= range.e.r; ++R) {
  8549. H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
  8550. o.push(' <table:table-row' + H + '>\n');
  8551. for(C=0; C < range.s.c; ++C) o.push(null_cell_xml);
  8552. for(; C <= range.e.c; ++C) {
  8553. var skip = false, ct = {}, textp = "";
  8554. for(mi = 0; mi != marr.length; ++mi) {
  8555. if(marr[mi].s.c > C) continue;
  8556. if(marr[mi].s.r > R) continue;
  8557. if(marr[mi].e.c < C) continue;
  8558. if(marr[mi].e.r < R) continue;
  8559. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  8560. ct['table:number-columns-spanned'] = (marr[mi].e.c - marr[mi].s.c + 1);
  8561. ct['table:number-rows-spanned'] = (marr[mi].e.r - marr[mi].s.r + 1);
  8562. break;
  8563. }
  8564. if(skip) { o.push(covered_cell_xml); continue; }
  8565. var ref = encode_cell({r:R, c:C}), cell = dense ? (ws[R]||[])[C]: ws[ref];
  8566. if(cell && cell.f) {
  8567. ct['table:formula'] = escapexml(csf_to_ods_formula(cell.f));
  8568. if(cell.F) {
  8569. if(cell.F.slice(0, ref.length) == ref) {
  8570. var _Fref = decode_range(cell.F);
  8571. ct['table:number-matrix-columns-spanned'] = (_Fref.e.c - _Fref.s.c + 1);
  8572. ct['table:number-matrix-rows-spanned'] = (_Fref.e.r - _Fref.s.r + 1);
  8573. }
  8574. }
  8575. }
  8576. if(!cell) { o.push(null_cell_xml); continue; }
  8577. switch(cell.t) {
  8578. case 'b':
  8579. textp = (cell.v ? 'TRUE' : 'FALSE');
  8580. ct['office:value-type'] = "boolean";
  8581. ct['office:boolean-value'] = (cell.v ? 'true' : 'false');
  8582. break;
  8583. case 'n':
  8584. textp = (cell.w||String(cell.v||0));
  8585. ct['office:value-type'] = "float";
  8586. ct['office:value'] = (cell.v||0);
  8587. break;
  8588. case 's': case 'str':
  8589. textp = cell.v == null ? "" : cell.v;
  8590. ct['office:value-type'] = "string";
  8591. break;
  8592. case 'd':
  8593. textp = (cell.w||(parseDate(cell.v).toISOString()));
  8594. ct['office:value-type'] = "date";
  8595. ct['office:date-value'] = (parseDate(cell.v).toISOString());
  8596. ct['table:style-name'] = "ce1";
  8597. break;
  8598. //case 'e':
  8599. default: o.push(null_cell_xml); continue;
  8600. }
  8601. var text_p = write_text_p(textp);
  8602. if(cell.l && cell.l.Target) {
  8603. var _tgt = cell.l.Target;
  8604. _tgt = _tgt.charAt(0) == "#" ? "#" + csf_to_ods_3D(_tgt.slice(1)) : _tgt;
  8605. // TODO: choose correct parent path format based on link delimiters
  8606. if(_tgt.charAt(0) != "#" && !_tgt.match(/^\w+:/)) _tgt = '../' + _tgt;
  8607. text_p = writextag('text:a', text_p, {'xlink:href': _tgt.replace(/&/g, "&amp;")});
  8608. }
  8609. o.push(' ' + writextag('table:table-cell', writextag('text:p', text_p, {}), ct) + '\n');
  8610. }
  8611. o.push(' </table:table-row>\n');
  8612. }
  8613. o.push(' </table:table>\n');
  8614. return o.join("");
  8615. };
  8616. var write_automatic_styles_ods = function(o, wb) {
  8617. o.push(' <office:automatic-styles>\n');
  8618. o.push(' <number:date-style style:name="N37" number:automatic-order="true">\n');
  8619. o.push(' <number:month number:style="long"/>\n');
  8620. o.push(' <number:text>/</number:text>\n');
  8621. o.push(' <number:day number:style="long"/>\n');
  8622. o.push(' <number:text>/</number:text>\n');
  8623. o.push(' <number:year/>\n');
  8624. o.push(' </number:date-style>\n');
  8625. /* column styles */
  8626. var cidx = 0;
  8627. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  8628. if(!ws) return;
  8629. if(ws["!cols"]) {
  8630. for(var C = 0; C < ws["!cols"].length; ++C) if(ws["!cols"][C]) {
  8631. var colobj = ws["!cols"][C];
  8632. if(colobj.width == null && colobj.wpx == null && colobj.wch == null) continue;
  8633. process_col(colobj);
  8634. colobj.ods = cidx;
  8635. var w = ws["!cols"][C].wpx + "px";
  8636. o.push(' <style:style style:name="co' + cidx + '" style:family="table-column">\n');
  8637. o.push(' <style:table-column-properties fo:break-before="auto" style:column-width="' + w + '"/>\n');
  8638. o.push(' </style:style>\n');
  8639. ++cidx;
  8640. }
  8641. }
  8642. });
  8643. /* row styles */
  8644. var ridx = 0;
  8645. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  8646. if(!ws) return;
  8647. if(ws["!rows"]) {
  8648. for(var R = 0; R < ws["!rows"].length; ++R) if(ws["!rows"][R]) {
  8649. ws["!rows"][R].ods = ridx;
  8650. var h = ws["!rows"][R].hpx + "px";
  8651. o.push(' <style:style style:name="ro' + ridx + '" style:family="table-row">\n');
  8652. o.push(' <style:table-row-properties fo:break-before="auto" style:row-height="' + h + '"/>\n');
  8653. o.push(' </style:style>\n');
  8654. ++ridx;
  8655. }
  8656. }
  8657. });
  8658. /* table */
  8659. o.push(' <style:style style:name="ta1" style:family="table" style:master-page-name="mp1">\n');
  8660. o.push(' <style:table-properties table:display="true" style:writing-mode="lr-tb"/>\n');
  8661. o.push(' </style:style>\n');
  8662. /* table cells, text */
  8663. o.push(' <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N37"/>\n');
  8664. /* page-layout */
  8665. o.push(' </office:automatic-styles>\n');
  8666. };
  8667. return function wcx(wb, opts) {
  8668. var o = [XML_HEADER];
  8669. /* 3.1.3.2 */
  8670. var attr = wxt_helper({
  8671. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  8672. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  8673. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  8674. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  8675. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  8676. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  8677. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  8678. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  8679. 'xmlns:meta': "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
  8680. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  8681. 'xmlns:presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
  8682. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  8683. 'xmlns:chart': "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
  8684. 'xmlns:dr3d': "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
  8685. 'xmlns:math': "http://www.w3.org/1998/Math/MathML",
  8686. 'xmlns:form': "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
  8687. 'xmlns:script': "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
  8688. 'xmlns:ooo': "http://openoffice.org/2004/office",
  8689. 'xmlns:ooow': "http://openoffice.org/2004/writer",
  8690. 'xmlns:oooc': "http://openoffice.org/2004/calc",
  8691. 'xmlns:dom': "http://www.w3.org/2001/xml-events",
  8692. 'xmlns:xforms': "http://www.w3.org/2002/xforms",
  8693. 'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
  8694. 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
  8695. 'xmlns:sheet': "urn:oasis:names:tc:opendocument:sh33tjs:1.0",
  8696. 'xmlns:rpt': "http://openoffice.org/2005/report",
  8697. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  8698. 'xmlns:xhtml': "http://www.w3.org/1999/xhtml",
  8699. 'xmlns:grddl': "http://www.w3.org/2003/g/data-view#",
  8700. 'xmlns:tableooo': "http://openoffice.org/2009/table",
  8701. 'xmlns:drawooo': "http://openoffice.org/2010/draw",
  8702. 'xmlns:calcext': "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
  8703. 'xmlns:loext': "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
  8704. 'xmlns:field': "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
  8705. 'xmlns:formx': "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
  8706. 'xmlns:css3t': "http://www.w3.org/TR/css3-text/",
  8707. 'office:version': "1.2"
  8708. });
  8709. var fods = wxt_helper({
  8710. 'xmlns:config': "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
  8711. 'office:mimetype': "application/vnd.oasis.opendocument.spreadsheet"
  8712. });
  8713. if(opts.bookType == "fods") {
  8714. o.push('<office:document' + attr + fods + '>\n');
  8715. o.push(write_meta_ods().replace(/office:document-meta/g, "office:meta"));
  8716. // TODO: settings (equiv of settings.xml for ODS)
  8717. } else o.push('<office:document-content' + attr + '>\n');
  8718. // o.push(' <office:scripts/>\n');
  8719. write_automatic_styles_ods(o, wb);
  8720. o.push(' <office:body>\n');
  8721. o.push(' <office:spreadsheet>\n');
  8722. for(var i = 0; i != wb.SheetNames.length; ++i) o.push(write_ws(wb.Sheets[wb.SheetNames[i]], wb, i, opts));
  8723. o.push(' </office:spreadsheet>\n');
  8724. o.push(' </office:body>\n');
  8725. if(opts.bookType == "fods") o.push('</office:document>');
  8726. else o.push('</office:document-content>');
  8727. return o.join("");
  8728. };
  8729. })();
  8730. function write_ods(wb, opts) {
  8731. if(opts.bookType == "fods") return write_content_ods(wb, opts);
  8732. var zip = zip_new();
  8733. var f = "";
  8734. var manifest = [];
  8735. var rdf = [];
  8736. /* Part 3 Section 3.3 MIME Media Type */
  8737. f = "mimetype";
  8738. zip_add_file(zip, f, "application/vnd.oasis.opendocument.spreadsheet");
  8739. /* Part 1 Section 2.2 Documents */
  8740. f = "content.xml";
  8741. zip_add_file(zip, f, write_content_ods(wb, opts));
  8742. manifest.push([f, "text/xml"]);
  8743. rdf.push([f, "ContentFile"]);
  8744. /* TODO: these are hard-coded styles to satiate excel */
  8745. f = "styles.xml";
  8746. zip_add_file(zip, f, write_styles_ods(wb, opts));
  8747. manifest.push([f, "text/xml"]);
  8748. rdf.push([f, "StylesFile"]);
  8749. /* TODO: this is hard-coded to satiate excel */
  8750. f = "meta.xml";
  8751. zip_add_file(zip, f, XML_HEADER + write_meta_ods());
  8752. manifest.push([f, "text/xml"]);
  8753. rdf.push([f, "MetadataFile"]);
  8754. /* Part 3 Section 6 Metadata Manifest File */
  8755. f = "manifest.rdf";
  8756. zip_add_file(zip, f, write_rdf(rdf/*, opts*/));
  8757. manifest.push([f, "application/rdf+xml"]);
  8758. /* Part 3 Section 4 Manifest File */
  8759. f = "META-INF/manifest.xml";
  8760. zip_add_file(zip, f, write_manifest(manifest/*, opts*/));
  8761. return zip;
  8762. }
  8763. function write_sheet_index(wb, sheet) {
  8764. if(!sheet) return 0;
  8765. var idx = wb.SheetNames.indexOf(sheet);
  8766. if(idx == -1) throw new Error("Sheet not found: " + sheet);
  8767. return idx;
  8768. }
  8769. function write_obj_str(factory) {
  8770. return function write_str(wb, o) {
  8771. var idx = write_sheet_index(wb, o.sheet);
  8772. return factory.from_sheet(wb.Sheets[wb.SheetNames[idx]], o, wb);
  8773. };
  8774. }
  8775. var write_htm_str = write_obj_str(HTML_);
  8776. var write_csv_str = write_obj_str({from_sheet:sheet_to_csv});
  8777. var write_slk_str = write_obj_str(typeof SYLK !== "undefined" ? SYLK : {});
  8778. var write_dif_str = write_obj_str(typeof DIF !== "undefined" ? DIF : {});
  8779. var write_prn_str = write_obj_str(typeof PRN !== "undefined" ? PRN : {});
  8780. var write_rtf_str = write_obj_str(typeof RTF !== "undefined" ? RTF : {});
  8781. var write_txt_str = write_obj_str({from_sheet:sheet_to_txt});
  8782. var write_dbf_buf = write_obj_str(typeof DBF !== "undefined" ? DBF : {});
  8783. var write_eth_str = write_obj_str(typeof ETH !== "undefined" ? ETH : {});
  8784. var write_wk1_buf = write_obj_str(typeof WK_ !== "undefined" ? {from_sheet:WK_.sheet_to_wk1} : {});
  8785. function fix_opts_func(defaults) {
  8786. return function fix_opts(opts) {
  8787. for(var i = 0; i != defaults.length; ++i) {
  8788. var d = defaults[i];
  8789. if(opts[d[0]] === undefined) opts[d[0]] = d[1];
  8790. if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
  8791. }
  8792. };
  8793. }
  8794. var fix_read_opts = function(opts) {
  8795. fix_opts_func([
  8796. ['cellNF', false], /* emit cell number format string as .z */
  8797. ['cellHTML', true], /* emit html string as .h */
  8798. ['cellFormula', true], /* emit formulae as .f */
  8799. ['cellStyles', false], /* emits style/theme as .s */
  8800. ['cellText', true], /* emit formatted text as .w */
  8801. ['cellDates', false], /* emit date cells with type `d` */
  8802. ['sheetStubs', false], /* emit empty cells */
  8803. ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
  8804. ['bookDeps', false], /* parse calculation chains */
  8805. ['bookSheets', false], /* only try to get sheet names (no Sheets) */
  8806. ['bookProps', false], /* only try to get properties (no Sheets) */
  8807. ['bookFiles', false], /* include raw file structure (keys, files, cfb) */
  8808. ['bookVBA', false], /* include vba raw data (vbaraw) */
  8809. ['password',''], /* password */
  8810. ['WTF', false] /* WTF mode (throws errors) */
  8811. ])(opts);
  8812. };
  8813. var fix_write_opts = fix_opts_func([
  8814. ['cellDates', false], /* write date cells with type `d` */
  8815. ['bookSST', false], /* Generate Shared String Table */
  8816. ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
  8817. ['compression', false], /* Use file compression */
  8818. ['WTF', false] /* WTF mode (throws errors) */
  8819. ]);
  8820. function get_sheet_type(n) {
  8821. if(RELS.WS.indexOf(n) > -1) return "sheet";
  8822. if(RELS.CS && n == RELS.CS) return "chart";
  8823. if(RELS.DS && n == RELS.DS) return "dialog";
  8824. if(RELS.MS && n == RELS.MS) return "macro";
  8825. return (n && n.length) ? n : "sheet";
  8826. }
  8827. function safe_parse_wbrels(wbrels, sheets) {
  8828. if(!wbrels) return 0;
  8829. try {
  8830. wbrels = sheets.map(function pwbr(w) { if(!w.id) w.id = w.strRelID; return [w.name, wbrels['!id'][w.id].Target, get_sheet_type(wbrels['!id'][w.id].Type)]; });
  8831. } catch(e) { return null; }
  8832. return !wbrels || wbrels.length === 0 ? null : wbrels;
  8833. }
  8834. function safe_parse_sheet(zip, path, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles) {
  8835. try {
  8836. sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
  8837. var data = getzipdata(zip, path);
  8838. var _ws;
  8839. switch(stype) {
  8840. case 'sheet': _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  8841. case 'chart': _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
  8842. if(!_ws || !_ws['!drawel']) break;
  8843. var dfile = resolve_path(_ws['!drawel'].Target, path);
  8844. var drelsp = get_rels_path(dfile);
  8845. var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
  8846. var chartp = resolve_path(draw, dfile);
  8847. var crelsp = get_rels_path(chartp);
  8848. _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
  8849. break;
  8850. case 'macro': _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  8851. case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  8852. default: throw new Error("Unrecognized sheet type " + stype);
  8853. }
  8854. sheets[sheet] = _ws;
  8855. /* scan rels for comments */
  8856. var comments = [];
  8857. if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
  8858. if(sheetRels[sheet][n].Type == RELS.CMNT) {
  8859. var dfile = resolve_path(sheetRels[sheet][n].Target, path);
  8860. comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
  8861. if(!comments || !comments.length) return;
  8862. sheet_insert_comments(_ws, comments);
  8863. }
  8864. });
  8865. } catch(e) { if(opts.WTF) throw e; }
  8866. }
  8867. function strip_front_slash(x) { return x.charAt(0) == '/' ? x.slice(1) : x; }
  8868. function parse_zip(zip, opts) {
  8869. make_ssf(SSF);
  8870. opts = opts || {};
  8871. fix_read_opts(opts);
  8872. /* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
  8873. if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
  8874. /* UOC */
  8875. if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
  8876. /* Numbers */
  8877. if(safegetzipfile(zip, 'Index/Document.iwa')) throw new Error('Unsupported NUMBERS file');
  8878. if(!safegetzipfile(zip, '[Content_Types].xml')) {
  8879. if(safegetzipfile(zip, 'index.xml.gz')) throw new Error('Unsupported NUMBERS 08 file');
  8880. if(safegetzipfile(zip, 'index.xml')) throw new Error('Unsupported NUMBERS 09 file');
  8881. throw new Error('Unsupported ZIP file');
  8882. }
  8883. var entries = zipentries(zip);
  8884. var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')));
  8885. var xlsb = false;
  8886. var sheets, binname;
  8887. if(dir.workbooks.length === 0) {
  8888. binname = "xl/workbook.xml";
  8889. if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
  8890. }
  8891. if(dir.workbooks.length === 0) {
  8892. binname = "xl/workbook.bin";
  8893. if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
  8894. dir.workbooks.push(binname);
  8895. xlsb = true;
  8896. }
  8897. if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  8898. var themes = ({});
  8899. var styles = ({});
  8900. if(!opts.bookSheets && !opts.bookProps) {
  8901. strs = [];
  8902. if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }
  8903. if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"",dir.themes[0], opts);
  8904. if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  8905. }
  8906. /*var externbooks = */dir.links.map(function(link) {
  8907. try {
  8908. var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
  8909. return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
  8910. } catch(e) {}
  8911. });
  8912. var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  8913. var props = {}, propdata = "";
  8914. if(dir.coreprops.length) {
  8915. propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
  8916. if(propdata) props = parse_core_props(propdata);
  8917. if(dir.extprops.length !== 0) {
  8918. propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
  8919. if(propdata) parse_ext_props(propdata, props, opts);
  8920. }
  8921. }
  8922. var custprops = {};
  8923. if(!opts.bookSheets || opts.bookProps) {
  8924. if (dir.custprops.length !== 0) {
  8925. propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
  8926. if(propdata) custprops = parse_cust_props(propdata, opts);
  8927. }
  8928. }
  8929. var out = ({});
  8930. if(opts.bookSheets || opts.bookProps) {
  8931. if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
  8932. else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
  8933. if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
  8934. if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
  8935. if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  8936. }
  8937. sheets = {};
  8938. var deps = {};
  8939. if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);
  8940. var i=0;
  8941. var sheetRels = ({});
  8942. var path, relsPath;
  8943. {
  8944. var wbsheets = wb.Sheets;
  8945. props.Worksheets = wbsheets.length;
  8946. props.SheetNames = [];
  8947. for(var j = 0; j != wbsheets.length; ++j) {
  8948. props.SheetNames[j] = wbsheets[j].name;
  8949. }
  8950. }
  8951. var wbext = xlsb ? "bin" : "xml";
  8952. var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  8953. var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
  8954. if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
  8955. var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile);
  8956. if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  8957. /* Numbers iOS hack */
  8958. var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
  8959. wsloop: for(i = 0; i != props.Worksheets; ++i) {
  8960. var stype = "sheet";
  8961. if(wbrels && wbrels[i]) {
  8962. path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
  8963. if(!safegetzipfile(zip, path)) path = wbrels[i][1];
  8964. if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
  8965. stype = wbrels[i][2];
  8966. } else {
  8967. path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
  8968. path = path.replace(/sheet0\./,"sheet.");
  8969. }
  8970. relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
  8971. if(opts && opts.sheets != null) switch(typeof opts.sheets) {
  8972. case "number": if(i != opts.sheets) continue wsloop; break;
  8973. case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
  8974. default: if(Array.isArray && Array.isArray(opts.sheets)) {
  8975. var snjseen = false;
  8976. for(var snj = 0; snj != opts.sheets.length; ++snj) {
  8977. if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
  8978. if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
  8979. }
  8980. if(!snjseen) continue wsloop;
  8981. }
  8982. }
  8983. safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
  8984. }
  8985. out = ({
  8986. Directory: dir,
  8987. Workbook: wb,
  8988. Props: props,
  8989. Custprops: custprops,
  8990. Deps: deps,
  8991. Sheets: sheets,
  8992. SheetNames: props.SheetNames,
  8993. Strings: strs,
  8994. Styles: styles,
  8995. Themes: themes,
  8996. SSF: SSF.get_table()
  8997. });
  8998. if(opts && opts.bookFiles) {
  8999. if(zip.files) {
  9000. out.keys = entries;
  9001. out.files = zip.files;
  9002. } else {
  9003. out.keys = [];
  9004. out.files = {};
  9005. zip.FullPaths.forEach(function(p, idx) {
  9006. p = p.replace(/^Root Entry[\/]/, "");
  9007. out.keys.push(p);
  9008. out.files[p] = zip.FileIndex[idx];
  9009. });
  9010. }
  9011. }
  9012. if(opts && opts.bookVBA) {
  9013. if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
  9014. else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
  9015. }
  9016. return out;
  9017. }
  9018. /* [MS-OFFCRYPTO] 2.1.1 */
  9019. function parse_xlsxcfb(cfb, _opts) {
  9020. var opts = _opts || {};
  9021. var f = 'Workbook', data = CFB.find(cfb, f);
  9022. try {
  9023. f = '/!DataSpaces/Version';
  9024. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  9025. /*var version = */parse_DataSpaceVersionInfo(data.content);
  9026. /* 2.3.4.1 */
  9027. f = '/!DataSpaces/DataSpaceMap';
  9028. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  9029. var dsm = parse_DataSpaceMap(data.content);
  9030. if(dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage")
  9031. throw new Error("ECMA-376 Encrypted file bad " + f);
  9032. /* 2.3.4.2 */
  9033. f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
  9034. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  9035. var seds = parse_DataSpaceDefinition(data.content);
  9036. if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
  9037. throw new Error("ECMA-376 Encrypted file bad " + f);
  9038. /* 2.3.4.3 */
  9039. f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
  9040. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  9041. /*var hdr = */parse_Primary(data.content);
  9042. } catch(e) {}
  9043. f = '/EncryptionInfo';
  9044. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  9045. var einfo = parse_EncryptionInfo(data.content);
  9046. /* 2.3.4.4 */
  9047. f = '/EncryptedPackage';
  9048. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  9049. /*global decrypt_agile */
  9050. if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  9051. /*global decrypt_std76 */
  9052. if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  9053. throw new Error("File is password-protected");
  9054. }
  9055. function write_zip(wb, opts) {
  9056. _shapeid = 1024;
  9057. if(opts.bookType == "ods") return write_ods(wb, opts);
  9058. if(wb && !wb.SSF) {
  9059. wb.SSF = SSF.get_table();
  9060. }
  9061. if(wb && wb.SSF) {
  9062. make_ssf(SSF); SSF.load_table(wb.SSF);
  9063. // $FlowIgnore
  9064. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  9065. opts.ssf = wb.SSF;
  9066. }
  9067. opts.rels = {}; opts.wbrels = {};
  9068. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  9069. if(browser_has_Map) opts.revStrings = new Map();
  9070. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  9071. var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
  9072. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  9073. var ct = new_ct();
  9074. fix_write_opts(opts = opts || {});
  9075. var zip = zip_new();
  9076. var f = "", rId = 0;
  9077. opts.cellXfs = [];
  9078. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  9079. if(!wb.Props) wb.Props = {};
  9080. f = "docProps/core.xml";
  9081. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  9082. ct.coreprops.push(f);
  9083. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  9084. f = "docProps/app.xml";
  9085. if(wb.Props && wb.Props.SheetNames){/* empty */}
  9086. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  9087. else {
  9088. var _sn = [];
  9089. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  9090. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  9091. wb.Props.SheetNames = _sn;
  9092. }
  9093. wb.Props.Worksheets = wb.Props.SheetNames.length;
  9094. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  9095. ct.extprops.push(f);
  9096. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  9097. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  9098. f = "docProps/custom.xml";
  9099. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  9100. ct.custprops.push(f);
  9101. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  9102. }
  9103. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  9104. var wsrels = {'!id':{}};
  9105. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  9106. var _type = (ws || {})["!type"] || "sheet";
  9107. switch(_type) {
  9108. case "chart":
  9109. /* falls through */
  9110. default:
  9111. f = "xl/worksheets/sheet" + rId + "." + wbext;
  9112. zip_add_file(zip, f, write_ws(rId-1, f, opts, wb, wsrels));
  9113. ct.sheets.push(f);
  9114. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  9115. }
  9116. if(ws) {
  9117. var comments = ws['!comments'];
  9118. var need_vml = false;
  9119. if(comments && comments.length > 0) {
  9120. var cf = "xl/comments" + rId + "." + wbext;
  9121. zip_add_file(zip, cf, write_cmnt(comments, cf, opts));
  9122. ct.comments.push(cf);
  9123. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  9124. need_vml = true;
  9125. }
  9126. if(ws['!legacy']) {
  9127. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
  9128. }
  9129. delete ws['!comments'];
  9130. delete ws['!legacy'];
  9131. }
  9132. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  9133. }
  9134. if(opts.Strings != null && opts.Strings.length > 0) {
  9135. f = "xl/sharedStrings." + wbext;
  9136. zip_add_file(zip, f, write_sst(opts.Strings, f, opts));
  9137. ct.strs.push(f);
  9138. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  9139. }
  9140. f = "xl/workbook." + wbext;
  9141. zip_add_file(zip, f, write_wb(wb, f, opts));
  9142. ct.workbooks.push(f);
  9143. add_rels(opts.rels, 1, f, RELS.WB);
  9144. /* TODO: something more intelligent with themes */
  9145. f = "xl/theme/theme1.xml";
  9146. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  9147. ct.themes.push(f);
  9148. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  9149. /* TODO: something more intelligent with styles */
  9150. f = "xl/styles." + wbext;
  9151. zip_add_file(zip, f, write_sty(wb, f, opts));
  9152. ct.styles.push(f);
  9153. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  9154. if(wb.vbaraw && vbafmt) {
  9155. f = "xl/vbaProject.bin";
  9156. zip_add_file(zip, f, wb.vbaraw);
  9157. ct.vba.push(f);
  9158. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  9159. }
  9160. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  9161. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  9162. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  9163. delete opts.revssf; delete opts.ssf;
  9164. return zip;
  9165. }
  9166. function firstbyte(f,o) {
  9167. var x = "";
  9168. switch((o||{}).type || "base64") {
  9169. case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  9170. case 'base64': x = Base64.decode(f.slice(0,12)); break;
  9171. case 'binary': x = f; break;
  9172. case 'array': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  9173. default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
  9174. }
  9175. return [x.charCodeAt(0), x.charCodeAt(1), x.charCodeAt(2), x.charCodeAt(3), x.charCodeAt(4), x.charCodeAt(5), x.charCodeAt(6), x.charCodeAt(7)];
  9176. }
  9177. function read_cfb(cfb, opts) {
  9178. if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  9179. return parse_xlscfb(cfb, opts);
  9180. }
  9181. function read_zip(data, opts) {
  9182. var zip, d = data;
  9183. var o = opts||{};
  9184. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  9185. zip = zip_read(d, o);
  9186. return parse_zip(zip, o);
  9187. }
  9188. function read_plaintext(data, o) {
  9189. var i = 0;
  9190. main: while(i < data.length) switch(data.charCodeAt(i)) {
  9191. case 0x0A: case 0x0D: case 0x20: ++i; break;
  9192. case 0x3C: return parse_xlml(data.slice(i),o);
  9193. default: break main;
  9194. }
  9195. return PRN.to_workbook(data, o);
  9196. }
  9197. function read_plaintext_raw(data, o) {
  9198. var str = "", bytes = firstbyte(data, o);
  9199. switch(o.type) {
  9200. case 'base64': str = Base64.decode(data); break;
  9201. case 'binary': str = data; break;
  9202. case 'buffer': str = data.toString('binary'); break;
  9203. case 'array': str = cc2str(data); break;
  9204. default: throw new Error("Unrecognized type " + o.type);
  9205. }
  9206. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
  9207. return read_plaintext(str, o);
  9208. }
  9209. function read_utf16(data, o) {
  9210. var d = data;
  9211. if(o.type == 'base64') d = Base64.decode(d);
  9212. d = cptable.utils.decode(1200, d.slice(2), 'str');
  9213. o.type = "binary";
  9214. return read_plaintext(d, o);
  9215. }
  9216. function bstrify(data) {
  9217. return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
  9218. }
  9219. function read_prn(data, d, o, str) {
  9220. if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
  9221. return PRN.to_workbook(d, o);
  9222. }
  9223. function readSync(data, opts) {
  9224. reset_cp();
  9225. var o = opts||{};
  9226. if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o = dup(o), o.type = "array", o));
  9227. var d = data, n = [0,0,0,0], str = false;
  9228. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  9229. _ssfopts = {};
  9230. if(o.dateNF) _ssfopts.dateNF = o.dateNF;
  9231. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  9232. if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); }
  9233. if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
  9234. if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
  9235. // $FlowIgnore
  9236. var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
  9237. // $FlowIgnore
  9238. if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
  9239. }
  9240. switch((n = firstbyte(d, o))[0]) {
  9241. case 0xD0: if(n[1] === 0xCF && n[2] === 0x11 && n[3] === 0xE0 && n[4] === 0xA1 && n[5] === 0xB1 && n[6] === 0x1A && n[7] === 0xE1) return read_cfb(CFB.read(d, o), o); break;
  9242. case 0x09: if(n[1] <= 0x08) return parse_xlscfb(d, o); break;
  9243. case 0x3C: return parse_xlml(d, o);
  9244. case 0x49:
  9245. if(n[1] === 0x49 && n[2] === 0x2a && n[3] === 0x00) throw new Error("TIFF Image File is not a spreadsheet");
  9246. if(n[1] === 0x44) return read_wb_ID(d, o);
  9247. break;
  9248. case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
  9249. case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
  9250. case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
  9251. case 0xFF:
  9252. if(n[1] === 0xFE) { return read_utf16(d, o); }
  9253. else if(n[1] === 0x00 && n[2] === 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
  9254. break;
  9255. case 0x00:
  9256. if(n[1] === 0x00) {
  9257. if(n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
  9258. if(n[2] === 0x00 && (n[3] === 0x08 || n[3] === 0x09)) return WK_.to_workbook(d, o);
  9259. }
  9260. break;
  9261. case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
  9262. case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return RTF.to_workbook(d, o); break;
  9263. case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
  9264. case 0x89: if(n[1] === 0x50 && n[2] === 0x4E && n[3] === 0x47) throw new Error("PNG Image File is not a spreadsheet"); break;
  9265. }
  9266. if(DBF.versions.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
  9267. return read_prn(data, d, o, str);
  9268. }
  9269. function readFileSync(filename, opts) {
  9270. var o = opts||{}; o.type = 'file';
  9271. return readSync(filename, o);
  9272. }
  9273. function write_cfb_ctr(cfb, o) {
  9274. switch(o.type) {
  9275. case "base64": case "binary": break;
  9276. case "buffer": case "array": o.type = ""; break;
  9277. case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
  9278. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  9279. default: throw new Error("Unrecognized type " + o.type);
  9280. }
  9281. return CFB.write(cfb, o);
  9282. }
  9283. function write_zip_type(wb, opts) {
  9284. var o = dup(opts||{});
  9285. var z = write_zip(wb, o);
  9286. var oopts = {};
  9287. if(o.compression) oopts.compression = 'DEFLATE';
  9288. if(o.password) oopts.type = has_buf ? "nodebuffer" : "string";
  9289. else switch(o.type) {
  9290. case "base64": oopts.type = "base64"; break;
  9291. case "binary": oopts.type = "string"; break;
  9292. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  9293. case "buffer":
  9294. case "file": oopts.type = has_buf ? "nodebuffer" : "string"; break;
  9295. default: throw new Error("Unrecognized type " + o.type);
  9296. }
  9297. var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: {"nodebuffer": "buffer", "string": "binary"}[oopts.type] || oopts.type}) : z.generate(oopts);
  9298. /*jshint -W083 */
  9299. if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
  9300. /*jshint +W083 */
  9301. if(o.type === "file") return write_dl(o.file, out);
  9302. return o.type == "string" ? utf8read(out) : out;
  9303. }
  9304. function write_cfb_type(wb, opts) {
  9305. var o = opts||{};
  9306. var cfb = write_xlscfb(wb, o);
  9307. return write_cfb_ctr(cfb, o);
  9308. }
  9309. function write_string_type(out, opts, bom) {
  9310. if(!bom) bom = "";
  9311. var o = bom + out;
  9312. switch(opts.type) {
  9313. case "base64": return Base64.encode(utf8write(o));
  9314. case "binary": return utf8write(o);
  9315. case "string": return out;
  9316. case "file": return write_dl(opts.file, o, 'utf8');
  9317. case "buffer": {
  9318. if(has_buf) return Buffer_from(o, 'utf8');
  9319. else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
  9320. }
  9321. }
  9322. throw new Error("Unrecognized type " + opts.type);
  9323. }
  9324. function write_stxt_type(out, opts) {
  9325. switch(opts.type) {
  9326. case "base64": return Base64.encode(out);
  9327. case "binary": return out;
  9328. case "string": return out; /* override in sheet_to_txt */
  9329. case "file": return write_dl(opts.file, out, 'binary');
  9330. case "buffer": {
  9331. if(has_buf) return Buffer_from(out, 'binary');
  9332. else return out.split("").map(function(c) { return c.charCodeAt(0); });
  9333. }
  9334. }
  9335. throw new Error("Unrecognized type " + opts.type);
  9336. }
  9337. /* TODO: test consistency */
  9338. function write_binary_type(out, opts) {
  9339. switch(opts.type) {
  9340. case "string":
  9341. case "base64":
  9342. case "binary":
  9343. var bstr = "";
  9344. // $FlowIgnore
  9345. for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
  9346. return opts.type == 'base64' ? Base64.encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
  9347. case "file": return write_dl(opts.file, out);
  9348. case "buffer": return out;
  9349. default: throw new Error("Unrecognized type " + opts.type);
  9350. }
  9351. }
  9352. function writeSync(wb, opts) {
  9353. reset_cp();
  9354. check_wb(wb);
  9355. var o = dup(opts||{});
  9356. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  9357. if(o.type == "array") { o.type = "binary"; var out = (writeSync(wb, o)); o.type = "array"; return s2ab(out); }
  9358. switch(o.bookType || 'xlsb') {
  9359. case 'xml':
  9360. case 'xlml': return write_string_type(write_xlml(wb, o), o);
  9361. case 'slk':
  9362. case 'sylk': return write_string_type(write_slk_str(wb, o), o);
  9363. case 'htm':
  9364. case 'html': return write_string_type(write_htm_str(wb, o), o);
  9365. case 'txt': return write_stxt_type(write_txt_str(wb, o), o);
  9366. case 'csv': return write_string_type(write_csv_str(wb, o), o, "\ufeff");
  9367. case 'dif': return write_string_type(write_dif_str(wb, o), o);
  9368. case 'dbf': return write_binary_type(write_dbf_buf(wb, o), o);
  9369. case 'prn': return write_string_type(write_prn_str(wb, o), o);
  9370. case 'rtf': return write_string_type(write_rtf_str(wb, o), o);
  9371. case 'eth': return write_string_type(write_eth_str(wb, o), o);
  9372. case 'fods': return write_string_type(write_ods(wb, o), o);
  9373. case 'wk1': return write_binary_type(write_wk1_buf(wb, o), o);
  9374. case 'wk3': return write_binary_type(WK_.book_to_wk3(wb, o), o);
  9375. case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
  9376. case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
  9377. case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
  9378. case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
  9379. case 'biff8':
  9380. case 'xla':
  9381. case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
  9382. case 'xlsx':
  9383. case 'xlsm':
  9384. case 'xlam':
  9385. case 'xlsb':
  9386. case 'ods': return write_zip_type(wb, o);
  9387. default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
  9388. }
  9389. }
  9390. function resolve_book_type(o) {
  9391. if(o.bookType) return;
  9392. var _BT = {
  9393. "xls": "biff8",
  9394. "htm": "html",
  9395. "slk": "sylk",
  9396. "socialcalc": "eth",
  9397. "Sh33tJS": "WTF"
  9398. };
  9399. var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
  9400. if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
  9401. o.bookType = _BT[o.bookType] || o.bookType;
  9402. }
  9403. function writeFileSync(wb, filename, opts) {
  9404. var o = opts||{}; o.type = 'file';
  9405. o.file = filename;
  9406. resolve_book_type(o);
  9407. return writeSync(wb, o);
  9408. }
  9409. function writeFileAsync(filename, wb, opts, cb) {
  9410. var o = opts||{}; o.type = 'file';
  9411. o.file = filename;
  9412. resolve_book_type(o);
  9413. o.type = 'buffer';
  9414. var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts);
  9415. return _fs.writeFile(filename, writeSync(wb, o), _cb);
  9416. }
  9417. function make_json_row(sheet, r, R, cols, header, hdr, dense, o) {
  9418. var rr = encode_row(R);
  9419. var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
  9420. var isempty = true;
  9421. var row = (header === 1) ? [] : {};
  9422. if(header !== 1) {
  9423. if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
  9424. else row.__rowNum__ = R;
  9425. }
  9426. if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
  9427. var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  9428. if(val === undefined || val.t === undefined) {
  9429. if(defval === undefined) continue;
  9430. if(hdr[C] != null) { row[hdr[C]] = defval; }
  9431. continue;
  9432. }
  9433. var v = val.v;
  9434. switch(val.t){
  9435. case 'z': if(v == null) break; continue;
  9436. case 'e': v = (v == 0 ? null : void 0); break;
  9437. case 's': case 'd': case 'b': case 'n': break;
  9438. default: throw new Error('unrecognized type ' + val.t);
  9439. }
  9440. if(hdr[C] != null) {
  9441. if(v == null) {
  9442. if(val.t == "e" && v === null) row[hdr[C]] = null;
  9443. else if(defval !== undefined) row[hdr[C]] = defval;
  9444. else if(raw && v === null) row[hdr[C]] = null;
  9445. else continue;
  9446. } else {
  9447. row[hdr[C]] = raw || (o.rawNumbers && val.t == "n") ? v : format_cell(val,v,o);
  9448. }
  9449. if(v != null) isempty = false;
  9450. }
  9451. }
  9452. return { row: row, isempty: isempty };
  9453. }
  9454. function sheet_to_json(sheet, opts) {
  9455. if(sheet == null || sheet["!ref"] == null) return [];
  9456. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  9457. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  9458. var o = opts || {};
  9459. var range = o.range != null ? o.range : sheet["!ref"];
  9460. if(o.header === 1) header = 1;
  9461. else if(o.header === "A") header = 2;
  9462. else if(Array.isArray(o.header)) header = 3;
  9463. else if(o.header == null) header = 0;
  9464. switch(typeof range) {
  9465. case 'string': r = safe_decode_range(range); break;
  9466. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  9467. default: r = range;
  9468. }
  9469. if(header > 0) offset = 0;
  9470. var rr = encode_row(r.s.r);
  9471. var cols = [];
  9472. var out = [];
  9473. var outi = 0, counter = 0;
  9474. var dense = Array.isArray(sheet);
  9475. var R = r.s.r, C = 0, CC = 0;
  9476. if(dense && !sheet[R]) sheet[R] = [];
  9477. for(C = r.s.c; C <= r.e.c; ++C) {
  9478. cols[C] = encode_col(C);
  9479. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  9480. switch(header) {
  9481. case 1: hdr[C] = C - r.s.c; break;
  9482. case 2: hdr[C] = cols[C]; break;
  9483. case 3: hdr[C] = o.header[C - r.s.c]; break;
  9484. default:
  9485. if(val == null) val = {w: "__EMPTY", t: "s"};
  9486. vv = v = format_cell(val, null, o);
  9487. counter = 0;
  9488. for(CC = 0; CC < hdr.length; ++CC) if(hdr[CC] == vv) vv = v + "_" + (++counter);
  9489. hdr[C] = vv;
  9490. }
  9491. }
  9492. for (R = r.s.r + offset; R <= r.e.r; ++R) {
  9493. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  9494. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
  9495. }
  9496. out.length = outi;
  9497. return out;
  9498. }
  9499. var qreg = /"/g;
  9500. function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
  9501. var isempty = true;
  9502. var row = [], txt = "", rr = encode_row(R);
  9503. for(var C = r.s.c; C <= r.e.c; ++C) {
  9504. if (!cols[C]) continue;
  9505. var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
  9506. if(val == null) txt = "";
  9507. else if(val.v != null) {
  9508. isempty = false;
  9509. txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
  9510. for(var i = 0, cc = 0; i !== txt.length; ++i) if((cc = txt.charCodeAt(i)) === fs || cc === rs || cc === 34 || o.forceQuotes) {txt = "\"" + txt.replace(qreg, '""') + "\""; break; }
  9511. if(txt == "ID") txt = '"ID"';
  9512. } else if(val.f != null && !val.F) {
  9513. isempty = false;
  9514. txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
  9515. } else txt = "";
  9516. /* NOTE: Excel CSV does not support array formulae */
  9517. row.push(txt);
  9518. }
  9519. if(o.blankrows === false && isempty) return null;
  9520. return row.join(FS);
  9521. }
  9522. function sheet_to_csv(sheet, opts) {
  9523. var out = [];
  9524. var o = opts == null ? {} : opts;
  9525. if(sheet == null || sheet["!ref"] == null) return "";
  9526. var r = safe_decode_range(sheet["!ref"]);
  9527. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  9528. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  9529. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  9530. var row = "", cols = [];
  9531. o.dense = Array.isArray(sheet);
  9532. var colinfo = o.skipHidden && sheet["!cols"] || [];
  9533. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  9534. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  9535. for(var R = r.s.r; R <= r.e.r; ++R) {
  9536. if ((rowinfo[R]||{}).hidden) continue;
  9537. row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
  9538. if(row == null) { continue; }
  9539. if(o.strip) row = row.replace(endregex,"");
  9540. out.push(row + RS);
  9541. }
  9542. delete o.dense;
  9543. return out.join("");
  9544. }
  9545. function sheet_to_txt(sheet, opts) {
  9546. if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
  9547. var s = sheet_to_csv(sheet, opts);
  9548. if(typeof cptable == 'undefined' || opts.type == 'string') return s;
  9549. var o = cptable.utils.encode(1200, s, 'str');
  9550. return String.fromCharCode(255) + String.fromCharCode(254) + o;
  9551. }
  9552. function sheet_to_formulae(sheet) {
  9553. var y = "", x, val="";
  9554. if(sheet == null || sheet["!ref"] == null) return [];
  9555. var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
  9556. var cmds = [];
  9557. var dense = Array.isArray(sheet);
  9558. for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
  9559. for(var R = r.s.r; R <= r.e.r; ++R) {
  9560. rr = encode_row(R);
  9561. for(C = r.s.c; C <= r.e.c; ++C) {
  9562. y = cols[C] + rr;
  9563. x = dense ? (sheet[R]||[])[C] : sheet[y];
  9564. val = "";
  9565. if(x === undefined) continue;
  9566. else if(x.F != null) {
  9567. y = x.F;
  9568. if(!x.f) continue;
  9569. val = x.f;
  9570. if(y.indexOf(":") == -1) y = y + ":" + y;
  9571. }
  9572. if(x.f != null) val = x.f;
  9573. else if(x.t == 'z') continue;
  9574. else if(x.t == 'n' && x.v != null) val = "" + x.v;
  9575. else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
  9576. else if(x.w !== undefined) val = "'" + x.w;
  9577. else if(x.v === undefined) continue;
  9578. else if(x.t == 's') val = "'" + x.v;
  9579. else val = ""+x.v;
  9580. cmds[cmds.length] = y + "=" + val;
  9581. }
  9582. }
  9583. return cmds;
  9584. }
  9585. function sheet_add_json(_ws, js, opts) {
  9586. var o = opts || {};
  9587. var offset = +!o.skipHeader;
  9588. var ws = _ws || ({});
  9589. var _R = 0, _C = 0;
  9590. if(ws && o.origin != null) {
  9591. if(typeof o.origin == 'number') _R = o.origin;
  9592. else {
  9593. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  9594. _R = _origin.r; _C = _origin.c;
  9595. }
  9596. }
  9597. var cell;
  9598. var range = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}});
  9599. if(ws['!ref']) {
  9600. var _range = safe_decode_range(ws['!ref']);
  9601. range.e.c = Math.max(range.e.c, _range.e.c);
  9602. range.e.r = Math.max(range.e.r, _range.e.r);
  9603. if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
  9604. } else {
  9605. if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
  9606. }
  9607. var hdr = o.header || [], C = 0;
  9608. js.forEach(function (JS, R) {
  9609. keys(JS).forEach(function(k) {
  9610. if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
  9611. var v = JS[k];
  9612. var t = 'z';
  9613. var z = "";
  9614. var ref = encode_cell({c:_C + C,r:_R + R + offset});
  9615. cell = utils.sheet_get_cell(ws, ref);
  9616. if(v && typeof v === 'object' && !(v instanceof Date)){
  9617. ws[ref] = v;
  9618. } else {
  9619. if(typeof v == 'number') t = 'n';
  9620. else if(typeof v == 'boolean') t = 'b';
  9621. else if(typeof v == 'string') t = 's';
  9622. else if(v instanceof Date) {
  9623. t = 'd';
  9624. if(!o.cellDates) { t = 'n'; v = datenum(v); }
  9625. z = (o.dateNF || SSF._table[14]);
  9626. }
  9627. else if(v === null && o.nullError) { t = 'e'; v = 0; }
  9628. if(!cell) ws[ref] = cell = ({t:t, v:v});
  9629. else {
  9630. cell.t = t; cell.v = v;
  9631. delete cell.w; delete cell.R;
  9632. if(z) cell.z = z;
  9633. }
  9634. if(z) cell.z = z;
  9635. }
  9636. });
  9637. });
  9638. range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
  9639. var __R = encode_row(_R);
  9640. if(offset) for(C = 0; C < hdr.length; ++C) ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
  9641. ws['!ref'] = encode_range(range);
  9642. return ws;
  9643. }
  9644. function json_to_sheet(js, opts) { return sheet_add_json(null, js, opts); }
  9645. var utils = {
  9646. encode_col: encode_col,
  9647. encode_row: encode_row,
  9648. encode_cell: encode_cell,
  9649. encode_range: encode_range,
  9650. decode_col: decode_col,
  9651. decode_row: decode_row,
  9652. split_cell: split_cell,
  9653. decode_cell: decode_cell,
  9654. decode_range: decode_range,
  9655. format_cell: format_cell,
  9656. get_formulae: sheet_to_formulae,
  9657. make_csv: sheet_to_csv,
  9658. make_json: sheet_to_json,
  9659. make_formulae: sheet_to_formulae,
  9660. sheet_add_aoa: sheet_add_aoa,
  9661. sheet_add_json: sheet_add_json,
  9662. sheet_add_dom: sheet_add_dom,
  9663. aoa_to_sheet: aoa_to_sheet,
  9664. json_to_sheet: json_to_sheet,
  9665. table_to_sheet: parse_dom_table,
  9666. table_to_book: table_to_book,
  9667. sheet_to_csv: sheet_to_csv,
  9668. sheet_to_txt: sheet_to_txt,
  9669. sheet_to_json: sheet_to_json,
  9670. sheet_to_html: HTML_.from_sheet,
  9671. sheet_to_formulae: sheet_to_formulae,
  9672. sheet_to_row_object_array: sheet_to_json
  9673. };
  9674. (function(utils) {
  9675. utils.consts = utils.consts || {};
  9676. function add_consts(R/*Array<any>*/) { R.forEach(function(a){ utils.consts[a[0]] = a[1]; }); }
  9677. function get_default(x, y, z) { return x[y] != null ? x[y] : (x[y] = z); }
  9678. /* get cell, creating a stub if necessary */
  9679. function ws_get_cell_stub(ws, R, C) {
  9680. /* A1 cell address */
  9681. if(typeof R == "string") {
  9682. /* dense */
  9683. if(Array.isArray(ws)) {
  9684. var RC = decode_cell(R);
  9685. if(!ws[RC.r]) ws[RC.r] = [];
  9686. return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
  9687. }
  9688. return ws[R] || (ws[R] = {t:'z'});
  9689. }
  9690. /* cell address object */
  9691. if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
  9692. /* R and C are 0-based indices */
  9693. return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
  9694. }
  9695. utils.sheet_get_cell = ws_get_cell_stub;
  9696. /* find sheet index for given name / validate index */
  9697. function wb_sheet_idx(wb, sh) {
  9698. if(typeof sh == "number") {
  9699. if(sh >= 0 && wb.SheetNames.length > sh) return sh;
  9700. throw new Error("Cannot find sheet # " + sh);
  9701. } else if(typeof sh == "string") {
  9702. var idx = wb.SheetNames.indexOf(sh);
  9703. if(idx > -1) return idx;
  9704. throw new Error("Cannot find sheet name |" + sh + "|");
  9705. } else throw new Error("Cannot find sheet |" + sh + "|");
  9706. }
  9707. /* simple blank workbook object */
  9708. utils.book_new = function() {
  9709. return { SheetNames: [], Sheets: {} };
  9710. };
  9711. /* add a worksheet to the end of a given workbook */
  9712. utils.book_append_sheet = function(wb, ws, name) {
  9713. if(!name) for(var i = 1; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
  9714. if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
  9715. check_ws_name(name);
  9716. if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  9717. wb.SheetNames.push(name);
  9718. wb.Sheets[name] = ws;
  9719. };
  9720. /* set sheet visibility (visible/hidden/very hidden) */
  9721. utils.book_set_sheet_visibility = function(wb, sh, vis) {
  9722. get_default(wb,"Workbook",{});
  9723. get_default(wb.Workbook,"Sheets",[]);
  9724. var idx = wb_sheet_idx(wb, sh);
  9725. // $FlowIgnore
  9726. get_default(wb.Workbook.Sheets,idx, {});
  9727. switch(vis) {
  9728. case 0: case 1: case 2: break;
  9729. default: throw new Error("Bad sheet visibility setting " + vis);
  9730. }
  9731. // $FlowIgnore
  9732. wb.Workbook.Sheets[idx].Hidden = vis;
  9733. };
  9734. add_consts([
  9735. ["SHEET_VISIBLE", 0],
  9736. ["SHEET_HIDDEN", 1],
  9737. ["SHEET_VERY_HIDDEN", 2]
  9738. ]);
  9739. /* set number format */
  9740. utils.cell_set_number_format = function(cell, fmt) {
  9741. cell.z = fmt;
  9742. return cell;
  9743. };
  9744. /* set cell hyperlink */
  9745. utils.cell_set_hyperlink = function(cell, target, tooltip) {
  9746. if(!target) {
  9747. delete cell.l;
  9748. } else {
  9749. cell.l = ({ Target: target });
  9750. if(tooltip) cell.l.Tooltip = tooltip;
  9751. }
  9752. return cell;
  9753. };
  9754. utils.cell_set_internal_link = function(cell, range, tooltip) { return utils.cell_set_hyperlink(cell, "#" + range, tooltip); };
  9755. /* add to cell comments */
  9756. utils.cell_add_comment = function(cell, text, author) {
  9757. if(!cell.c) cell.c = [];
  9758. cell.c.push({t:text, a:author||"SheetJS"});
  9759. };
  9760. /* set array formula and flush related cells */
  9761. utils.sheet_set_array_formula = function(ws, range, formula) {
  9762. var rng = typeof range != "string" ? range : safe_decode_range(range);
  9763. var rngstr = typeof range == "string" ? range : encode_range(range);
  9764. for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
  9765. var cell = ws_get_cell_stub(ws, R, C);
  9766. cell.t = 'n';
  9767. cell.F = rngstr;
  9768. delete cell.v;
  9769. if(R == rng.s.r && C == rng.s.c) cell.f = formula;
  9770. }
  9771. return ws;
  9772. };
  9773. return utils;
  9774. })(utils);
  9775. if(typeof parse_xlscfb !== "undefined") XLSX.parse_xlscfb = parse_xlscfb;
  9776. XLSX.parse_zip = parse_zip;
  9777. XLSX.read = readSync; //xlsread
  9778. XLSX.readFile = readFileSync; //readFile
  9779. XLSX.readFileSync = readFileSync;
  9780. XLSX.write = writeSync;
  9781. XLSX.writeFile = writeFileSync;
  9782. XLSX.writeFileSync = writeFileSync;
  9783. XLSX.writeFileAsync = writeFileAsync;
  9784. XLSX.utils = utils;
  9785. XLSX.SSF = SSF;
  9786. XLSX.excel_exprot=excel_exprot;
  9787. if(typeof CFB !== "undefined") XLSX.CFB = CFB;
  9788. const fs = wx.getFileSystemManager() ;//获取全局唯一的文件管理器
  9789. function excel_exprot (data, header, headerName, fileName) {
  9790. let wopts = {
  9791. bookType: 'xlsx',
  9792. bookSST: false,
  9793. type: 'binary',
  9794. }
  9795. let workBook = {
  9796. SheetNames: ['Sheet1'],
  9797. Sheets: {},
  9798. Props: {},
  9799. }
  9800. dell();
  9801. const newData = [headerName, ...data]
  9802. // 1.XLSX.utils.json_to_sheet(data)接受一个对象数组并返回一个基于对象关键字自动生成的“标题”的工作表
  9803. //默认的列顺序由使用Object.keys的字段的第一次出现确定
  9804. // 2.将数据放入对象workBook的Sheets中等待输出
  9805. //加了一句skipHeader:true,这样就会忽略原来的表头
  9806. workBook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(newData, { header: header, skipHeader: true })
  9807. // 3.XLSX.write()开始编写Excel表格
  9808. // 4.changeData()将数据处理成需要的输出的格式
  9809. // console.log(this.changeData(XLSX.write(workBook, wopts)))
  9810. let time = new Date().getTime()
  9811. const StrData = changeData(XLSX.write(workBook, wopts))
  9812. fs.writeFile({
  9813. filePath: wx.env.USER_DATA_PATH + `/${fileName+time}.xlsx`, // wx.env.USER_DATA_PATH 指定临时文件存入的路径,后面字符串自定义
  9814. data: StrData,
  9815. encoding: 'binary', //二进制流文件必须是 binary
  9816. success(res) {
  9817. uni.hideLoading()
  9818. wx.openDocument({
  9819. // 打开文档
  9820. filePath: wx.env.USER_DATA_PATH + `/${fileName+time}.xlsx`, //拿上面存入的文件路径
  9821. showMenu: true, // 显示右上角菜单
  9822. success: function(res) {
  9823. },
  9824. fail: function() {
  9825. uni.showToast({
  9826. title: `打开失败`,
  9827. icon: 'error',
  9828. duration: 2000,
  9829. })
  9830. },
  9831. })
  9832. },
  9833. })
  9834. }
  9835. function changeData(s) {
  9836. //如果存在ArrayBuffer对象(es6)最好采用该对象
  9837. if (typeof ArrayBuffer !== 'undefined') {
  9838. //1.创建一个字节长度为s.length的内存区域
  9839. let buf = new ArrayBuffer(s.length)
  9840. //2.创建一个指向buf的Unit8视图,开始于字节0,直到缓冲区的末尾
  9841. let view = new Uint8Array(buf)
  9842. //3.返回指定位置的字符的Unicode编码
  9843. for (let i = 0; i != s.length; ++i) {
  9844. view[i] = s.charCodeAt(i) & 0xff
  9845. }
  9846. return buf
  9847. } else {
  9848. let buf = new Array(s.length)
  9849. for (let i = 0; i != s.length; ++i) {
  9850. buf[i] = s.charCodeAt(i) & 0xff
  9851. }
  9852. return buf
  9853. }
  9854. }
  9855. //删除缓存文件
  9856. function dell(){
  9857. fs.readdir({
  9858. dirPath: wx.env.USER_DATA_PATH,
  9859. success(res) {
  9860. console.log("文件列表",res)
  9861. let indexVal = res.files.length;
  9862. res.files.forEach((el) => {
  9863. let name = (wx.env.USER_DATA_PATH+el).replace(/usr/g, "usr/");
  9864. fs.unlink({
  9865. filePath:name,
  9866. fail(e) {
  9867. console.log('文件删除失败:', e)
  9868. },
  9869. success(succ){
  9870. indexVal++;
  9871. if(indexVal==0){
  9872. }
  9873. console.log('文件删除成功:', succ);
  9874. }
  9875. })
  9876. })
  9877. }
  9878. })
  9879. }
  9880. }
  9881. /*global define */
  9882. if(typeof exports !== 'undefined') make_xlsx_lib(exports);
  9883. else if(typeof module !== 'undefined' && module.exports) make_xlsx_lib(module.exports);
  9884. else if(typeof define === 'function' && define.amd) define('xlsx', function() { if(!XLSX.version) make_xlsx_lib(XLSX); return XLSX; });
  9885. else make_xlsx_lib(XLSX);
  9886. /* NOTE: the following extra line is needed for "Lightning Locker Service" */
  9887. if(typeof window !== 'undefined' && !window.XLSX) try { window.XLSX = XLSX; } catch(e) {}
  9888. /*exported XLS, ODS */
  9889. var XLS = XLSX, ODS = XLSX;