67_wsxml.js 21.8 KB
Newer Older
S
SheetJS 已提交
1
function parse_ws_xml_dim(ws/*:Worksheet*/, s/*:string*/) {
S
SheetJS 已提交
2
	var d = safe_decode_range(s);
3
	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);
S
SheetJS 已提交
4
}
S
SheetJS 已提交
5
var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
S
SheetJS 已提交
6
var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
7
var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
8
var dimregex = /"(\w*:\w*)"/;
9
var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
S
SheetJS 已提交
10
var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
S
SheetJS 已提交
11
var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
12
var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
S
SheetJS 已提交
13
var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
S
SheetJS 已提交
14

15
/* 18.3 Worksheets */
S
SheetJS 已提交
16
function parse_ws_xml(data/*:?string*/, opts, idx/*:number*/, rels, wb/*:WBWBProps*/, themes, styles)/*:Worksheet*/ {
17
	if(!data) return data;
S
SheetJS 已提交
18
	if(!rels) rels = {'!id':{}};
19
	if(DENSE != null && opts.dense == null) opts.dense = DENSE;
S
SheetJS 已提交
20

21
	/* 18.3.1.99 worksheet CT_Worksheet */
S
SheetJS 已提交
22
	var s = opts.dense ? ([]/*:any*/) : ({}/*:any*/);
S
SheetJS 已提交
23 24 25
	var refguess/*:Range*/ = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} }/*:any*/);

	var data1 = "", data2 = "";
S
SheetJS 已提交
26
	var mtch/*:?any*/ = data.match(sheetdataregex);
S
SheetJS 已提交
27
	if(mtch) {
28 29
		data1 = data.slice(0, mtch.index);
		data2 = data.slice(mtch.index + mtch[0].length);
S
SheetJS 已提交
30
	} else data1 = data2 = data;
31

S
SheetJS 已提交
32 33 34 35
	/* 18.3.1.82 sheetPr CT_SheetPr */
	var sheetPr = data1.match(sheetprregex);
	if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);

S
SheetJS 已提交
36
	/* 18.3.1.35 dimension CT_SheetDimension */
S
SheetJS 已提交
37
	var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
S
SheetJS 已提交
38
	if(ridx > 0) {
39
		var ref = data1.slice(ridx,ridx+50).match(dimregex);
S
SheetJS 已提交
40
		if(ref) parse_ws_xml_dim(s, ref[1]);
S
SheetJS 已提交
41
	}
42

S
SheetJS 已提交
43 44 45 46
	/* 18.3.1.88 sheetViews CT_SheetViews */
	var svs = data1.match(svsregex);
	if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);

S
SheetJS 已提交
47
	/* 18.3.1.17 cols CT_Cols */
S
SheetJS 已提交
48
	var columns/*:Array<ColInfo>*/ = [];
S
SheetJS 已提交
49
	if(opts.cellStyles) {
S
SheetJS 已提交
50
		/* 18.3.1.13 col CT_Col */
S
SheetJS 已提交
51
		var cols = data1.match(colregex);
S
SheetJS 已提交
52
		if(cols) parse_ws_xml_cols(columns, cols);
S
SheetJS 已提交
53 54
	}

55
	/* 18.3.1.80 sheetData CT_SheetData ? */
S
SheetJS 已提交
56
	if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
S
SheetJS 已提交
57

S
SheetJS 已提交
58 59 60 61 62
	/* 18.3.1.2  autoFilter CT_AutoFilter */
	var afilter = data2.match(afregex);
	if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);

	/* 18.3.1.55 mergeCells CT_MergeCells */
S
SheetJS 已提交
63 64 65
	var merges/*:Array<Range>*/ = [];
	var _merge = data2.match(mergecregex);
	if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
66
		merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
S
SheetJS 已提交
67

S
SheetJS 已提交
68
	/* 18.3.1.48 hyperlinks CT_Hyperlinks */
S
SheetJS 已提交
69
	var hlink = data2.match(hlinkregex);
S
SheetJS 已提交
70
	if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
S
SheetJS 已提交
71

S
SheetJS 已提交
72 73 74 75
	/* 18.3.1.62 pageMargins CT_PageMargins */
	var margins = data2.match(marginregex);
	if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));

S
SheetJS 已提交
76
	if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
S
SheetJS 已提交
77 78
	if(opts.sheetRows > 0 && s["!ref"]) {
		var tmpref = safe_decode_range(s["!ref"]);
79
		if(opts.sheetRows <= +tmpref.e.r) {
80 81 82 83 84 85 86 87 88
			tmpref.e.r = opts.sheetRows - 1;
			if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
			if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
			if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
			if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
			s["!fullref"] = s["!ref"];
			s["!ref"] = encode_range(tmpref);
		}
	}
S
SheetJS 已提交
89
	if(columns.length > 0) s["!cols"] = columns;
S
SheetJS 已提交
90
	if(merges.length > 0) s["!merges"] = merges;
91 92 93
	return s;
}

S
SheetJS 已提交
94
function write_ws_xml_merges(merges/*:Array<Range>*/)/*:string*/ {
95
	if(merges.length === 0) return "";
S
SheetJS 已提交
96 97 98 99
	var o = '<mergeCells count="' + merges.length + '">';
	for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
	return o + '</mergeCells>';
}
S
SheetJS 已提交
100

S
SheetJS 已提交
101 102 103 104 105 106
/* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
function parse_ws_xml_sheetpr(sheetPr/*:string*/, s, wb/*:WBWBProps*/, idx/*:number*/) {
	var data = parsexmltag(sheetPr);
	if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
	if(data.codeName) wb.Sheets[idx].CodeName = data.codeName;
}
107 108 109 110 111 112 113 114 115 116
function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
	var needed = false;
	var props = {}, payload = null;
	if(opts.bookType !== 'xlsx' && wb.vbaraw) {
		var cname = wb.SheetNames[idx];
		try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
		needed = true;
		props.codeName = escapexml(cname);
	}

R
Robin Hu 已提交
117 118 119 120 121 122 123
	if(ws && ws["!outline"]) {
		var outlineprops = {summaryBelow:1, summaryRight:1};
		if(ws["!outline"].above) outlineprops.summaryBelow = 0;
		if(ws["!outline"].left) outlineprops.summaryRight = 0;
		payload = (payload||"") + writextag('outlinePr', null, outlineprops);
	}

124 125 126
	if(!needed && !payload) return;
	o[o.length] = (writextag('sheetPr', payload, props));
}
S
SheetJS 已提交
127 128

/* 18.3.1.85 sheetProtection CT_SheetProtection */
S
SheetJS 已提交
129 130 131 132 133 134 135
var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
var sheetprot_deftrue = [
	"formatColumns", "formatRows", "formatCells",
	"insertColumns", "insertRows", "insertHyperlinks",
	"deleteColumns", "deleteRows",
	"sort", "autoFilter", "pivotTables"
];
M
Mior 已提交
136
function write_ws_xml_protection(sp)/*:string*/ {
S
SheetJS 已提交
137
	// algorithmName, hashValue, saltValue, spinCount
M
Mior 已提交
138
	var o = ({sheet:1}/*:any*/);
S
SheetJS 已提交
139 140
	sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
	sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
M
Mior 已提交
141 142 143 144 145
	/* TODO: algorithm */
	if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
	return writextag('sheetProtection', null, o);
}

S
SheetJS 已提交
146
function parse_ws_xml_hlinks(s, data/*:Array<string>*/, rels) {
S
SheetJS 已提交
147
	var dense = Array.isArray(s);
S
SheetJS 已提交
148
	for(var i = 0; i != data.length; ++i) {
J
James Yang 已提交
149
		var val = parsexmltag(utf8read(data[i]), true);
S
SheetJS 已提交
150
		if(!val.ref) return;
S
SheetJS 已提交
151
		var rel = ((rels || {})['!id']||[])[val.id];
S
SheetJS 已提交
152 153 154
		if(rel) {
			val.Target = rel.Target;
			if(val.location) val.Target += "#"+val.location;
H
harbhub 已提交
155
		} else {
S
SheetJS 已提交
156 157
			val.Target = "#" + val.location;
			rel = {Target: val.Target, TargetMode: 'Internal'};
S
SheetJS 已提交
158
		}
S
SheetJS 已提交
159
		val.Rel = rel;
S
SheetJS 已提交
160
		if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
S
SheetJS 已提交
161
		var rng = safe_decode_range(val.ref);
S
SheetJS 已提交
162 163
		for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
			var addr = encode_cell({c:C,r:R});
S
SheetJS 已提交
164 165 166 167 168 169 170 171
			if(dense) {
				if(!s[R]) s[R] = [];
				if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
				s[R][C].l = val;
			} else {
				if(!s[addr]) s[addr] = {t:"z",v:undefined};
				s[addr].l = val;
			}
S
SheetJS 已提交
172
		}
S
SheetJS 已提交
173 174
	}
}
S
SheetJS 已提交
175

S
SheetJS 已提交
176 177 178 179 180 181 182
function parse_ws_xml_margins(margin) {
	var o = {};
	["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
		if(margin[k]) o[k] = parseFloat(margin[k]);
	});
	return o;
}
S
SheetJS 已提交
183
function write_ws_xml_margins(margin)/*:string*/ {
S
Siguza 已提交
184 185 186
	default_margins(margin);
	return writextag('pageMargins', null, margin);
}
S
SheetJS 已提交
187

S
SheetJS 已提交
188
function parse_ws_xml_cols(columns, cols) {
S
SheetJS 已提交
189 190 191
	var seencol = false;
	for(var coli = 0; coli != cols.length; ++coli) {
		var coll = parsexmltag(cols[coli], true);
S
SheetJS 已提交
192
		if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
S
SheetJS 已提交
193
		var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
S
SheetJS 已提交
194 195 196 197
		delete coll.min; delete coll.max; coll.width = +coll.width;
		if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
		process_col(coll);
		while(colm <= colM) columns[colm++] = dup(coll);
S
SheetJS 已提交
198
	}
S
SheetJS 已提交
199
}
S
SheetJS 已提交
200
function write_ws_xml_cols(ws, cols)/*:string*/ {
S
SheetJS 已提交
201
	var o = ["<cols>"], col;
S
SheetJS 已提交
202 203
	for(var i = 0; i != cols.length; ++i) {
		if(!(col = cols[i])) continue;
S
SheetJS 已提交
204
		o[o.length] = (writextag('col', null, col_obj_w(i, col)));
S
SheetJS 已提交
205
	}
S
SheetJS 已提交
206
	o[o.length] = "</cols>";
S
SheetJS 已提交
207
	return o.join("");
S
SheetJS 已提交
208
}
209

S
SheetJS 已提交
210
function parse_ws_xml_autofilter(data/*:string*/) {
S
SheetJS 已提交
211 212 213
	var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
	return o;
}
S
SheetJS 已提交
214 215
function write_ws_xml_autofilter(data, ws, wb, idx)/*:string*/ {
	var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
S
SheetJS 已提交
216
	if(!wb.Workbook) wb.Workbook = ({Sheets:[]}/*:any*/);
S
SheetJS 已提交
217 218 219 220 221 222 223 224 225 226 227 228
	if(!wb.Workbook.Names) wb.Workbook.Names = [];
	var names/*: Array<any> */ = wb.Workbook.Names;
	var range = decode_range(ref);
	if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
	for(var i = 0; i < names.length; ++i) {
		var name = names[i];
		if(name.Name != '_xlnm._FilterDatabase') continue;
		if(name.Sheet != idx) continue;
		name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
	}
	if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref  });
	return writextag("autoFilter", null, {ref:ref});
S
SheetJS 已提交
229 230
}

S
SheetJS 已提交
231 232
/* 18.3.1.88 sheetViews CT_SheetViews */
/* 18.3.1.87 sheetView CT_SheetView */
S
SheetJS 已提交
233
var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
S
SheetJS 已提交
234
function parse_ws_xml_sheetviews(data, wb/*:WBWBProps*/) {
S
SheetJS 已提交
235 236
	if(!wb.Views) wb.Views = [{}];
	(data.match(sviewregex)||[]).forEach(function(r/*:string*/, i/*:number*/) {
S
SheetJS 已提交
237
		var tag = parsexmltag(r);
S
SheetJS 已提交
238 239 240 241
		// $FlowIgnore
		if(!wb.Views[i]) wb.Views[i] = {};
		// $FlowIgnore
		if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
S
SheetJS 已提交
242 243
	});
}
S
SheetJS 已提交
244
function write_ws_xml_sheetviews(ws, opts, idx, wb)/*:string*/ {
S
SheetJS 已提交
245
	var sview = ({workbookViewId:"0"}/*:any*/);
246
	// $FlowIgnore
S
SheetJS 已提交
247
	if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
248
	return writextag("sheetViews", writextag("sheetView", null, sview), {});
S
SheetJS 已提交
249 250
}

S
SheetJS 已提交
251
function write_ws_xml_cell(cell/*:Cell*/, ref, ws, opts/*::, idx, wb*/)/*:string*/ {
252
	if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z') return "";
S
SheetJS 已提交
253
	var vv = "";
S
SheetJS 已提交
254
	var oldt = cell.t, oldv = cell.v;
S
SheetJS 已提交
255
	if(cell.t !== "z") switch(cell.t) {
S
SheetJS 已提交
256
		case 'b': vv = cell.v ? "1" : "0"; break;
S
SheetJS 已提交
257 258 259
		case 'n': vv = ''+cell.v; break;
		case 'e': vv = BErr[cell.v]; break;
		case 'd':
S
SheetJS 已提交
260
			if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
S
SheetJS 已提交
261
			else {
262
				cell = dup(cell);
S
SheetJS 已提交
263
				cell.t = 'n';
S
SheetJS 已提交
264
				vv = ''+(cell.v = datenum(parseDate(cell.v)));
S
SheetJS 已提交
265
			}
S
SheetJS 已提交
266
			if(typeof cell.z === 'undefined') cell.z = SSF._table[14];
S
SheetJS 已提交
267
			break;
S
SheetJS 已提交
268 269
		default: vv = cell.v; break;
	}
S
SheetJS 已提交
270
	var v = writetag('v', escapexml(vv)), o = ({r:ref}/*:any*/);
271
	/* TODO: cell style */
S
SheetJS 已提交
272 273
	var os = get_cell_style(opts.cellXfs, cell, opts);
	if(os !== 0) o.s = os;
274
	switch(cell.t) {
275
		case 'n': break;
S
SheetJS 已提交
276
		case 'd': o.t = "d"; break;
277 278
		case 'b': o.t = "b"; break;
		case 'e': o.t = "e"; break;
279
		case 'z': break;
S
SheetJS 已提交
280
		default: if(cell.v == null) { delete cell.t; break; }
281
			if(opts && opts.bookSST) {
S
SheetJS 已提交
282
				v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
S
SheetJS 已提交
283
				o.t = "s"; break;
S
SheetJS 已提交
284
			}
S
SheetJS 已提交
285
			o.t = "str"; break;
286
	}
S
SheetJS 已提交
287
	if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
288
	if(typeof cell.f == "string" && cell.f) {
289
		var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
S
SheetJS 已提交
290 291
		v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
	}
S
SheetJS 已提交
292
	if(cell.l) ws['!links'].push([ref, cell.l]);
S
SheetJS 已提交
293
	if(cell.c) ws['!comments'].push([ref, cell.c]);
S
SheetJS 已提交
294 295 296
	return writextag('c', v, o);
}

S
SheetJS 已提交
297
var parse_ws_xml_data = (function() {
D
Daniel Yonkov 已提交
298
	var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
S
SheetJS 已提交
299
	var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
S
SheetJS 已提交
300
	var refregex = /ref=["']([^"']*)["']/;
S
SheetJS 已提交
301 302
	var match_v = matchtag("v"), match_f = matchtag("f");

S
SheetJS 已提交
303 304
return function parse_ws_xml_data(sdata/*:string*/, s, opts, guess/*:Range*/, themes, styles) {
	var ri = 0, x = "", cells/*:Array<string>*/ = [], cref/*:?Array<string>*/ = [], idx=0, i=0, cc=0, d="", p/*:any*/;
S
SheetJS 已提交
305
	var tag, tagr = 0, tagc = 0;
S
SheetJS 已提交
306
	var sstr, ftag;
307 308
	var fmtid = 0, fillid = 0;
	var do_format = Array.isArray(styles.CellXf), cf;
S
SheetJS 已提交
309
	var arrayf/*:Array<[Range, string]>*/ = [];
S
SheetJS 已提交
310
	var sharedf = [];
S
SheetJS 已提交
311
	var dense = Array.isArray(s);
S
SheetJS 已提交
312
	var rows/*:Array<RowInfo>*/ = [], rowobj = {}, rowrite = false;
S
SheetJS 已提交
313
	var sheetStubs = !!opts.sheetStubs;
314
	for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
S
SheetJS 已提交
315
		x = marr[mt].trim();
316 317
		var xlen = x.length;
		if(xlen === 0) continue;
318

S
SheetJS 已提交
319
		/* 18.3.1.73 row CT_Row */
320
		for(ri = 0; ri < xlen; ++ri) if(x.charCodeAt(ri) === 62) break; ++ri;
321
		tag = parsexmltag(x.slice(0,ri), true);
S
SheetJS 已提交
322
		tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
323 324 325
		if(opts.sheetRows && opts.sheetRows < tagr) continue;
		if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
		if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
S
SheetJS 已提交
326

S
SheetJS 已提交
327 328 329 330
		if(opts && opts.cellStyles) {
			rowobj = {}; rowrite = false;
			if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
			if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
331
			if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
S
SheetJS 已提交
332 333 334
			if(rowrite) rows[tagr-1] = rowobj;
		}

S
SheetJS 已提交
335
		/* 18.3.1.4 c CT_Cell */
336
		cells = x.slice(ri).split(cellregex);
S
SheetJS 已提交
337 338
		for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
		cells = cells.slice(rslice);
339
		for(ri = 0; ri != cells.length; ++ri) {
S
SheetJS 已提交
340 341 342
			x = cells[ri].trim();
			if(x.length === 0) continue;
			cref = x.match(rregex); idx = ri; i=0; cc=0;
343
			x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
S
SheetJS 已提交
344
			if(cref != null && cref.length === 2) {
S
SheetJS 已提交
345 346 347 348 349 350
				idx = 0; d=cref[1];
				for(i=0; i != d.length; ++i) {
					if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
					idx = 26*idx + cc;
				}
				--idx;
S
SheetJS 已提交
351 352
				tagc = idx;
			} else ++tagc;
S
SheetJS 已提交
353
			for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
354
			tag = parsexmltag(x.slice(0,i), true);
S
SheetJS 已提交
355
			if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
356
			d = x.slice(i);
S
SheetJS 已提交
357
			p = ({t:""}/*:any*/);
S
SheetJS 已提交
358

S
SheetJS 已提交
359 360 361
			if((cref=d.match(match_v))!= null && /*::cref != null && */cref[1] !== '') p.v=unescapexml(cref[1]);
			if(opts.cellFormula) {
				if((cref=d.match(match_f))!= null && /*::cref != null && */cref[1] !== '') {
S
SheetJS 已提交
362
					/* TODO: match against XLSXFutureFunctions */
S
SheetJS 已提交
363
					p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
S
SheetJS 已提交
364
					if(!opts.xlfn) p.f = _xlfn(p.f);
S
SheetJS 已提交
365 366 367 368 369 370
					if(/*::cref != null && cref[0] != null && */cref[0].indexOf('t="array"') > -1) {
						p.F = (d.match(refregex)||[])[1];
						if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
					} else if(/*::cref != null && cref[0] != null && */cref[0].indexOf('t="shared"') > -1) {
						// TODO: parse formula
						ftag = parsexmltag(cref[0]);
S
SheetJS 已提交
371 372 373
						var ___f = unescapexml(utf8read(cref[1]));
						if(!opts.xlfn) ___f = _xlfn(___f);
						sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
S
SheetJS 已提交
374 375 376
					}
				} else if((cref=d.match(/<f[^>]*\/>/))) {
					ftag = parsexmltag(cref[0]);
377
					if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
S
SheetJS 已提交
378 379 380 381 382 383 384 385
				}
				/* TODO: factor out contains logic */
				var _tag = decode_cell(tag.r);
				for(i = 0; i < arrayf.length; ++i)
					if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
						if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
							p.F = arrayf[i][1];
			}
S
SheetJS 已提交
386

S
SheetJS 已提交
387
			if(tag.t == null && p.v === undefined) {
S
SheetJS 已提交
388 389
				if(p.f || p.F) {
					p.v = 0; p.t = "n";
S
SheetJS 已提交
390
				} else if(!sheetStubs) continue;
S
SheetJS 已提交
391
				else p.t = "z";
S
SheetJS 已提交
392 393
			}
			else p.t = tag.t || "n";
S
SheetJS 已提交
394 395
			if(guess.s.c > tagc) guess.s.c = tagc;
			if(guess.e.c < tagc) guess.e.c = tagc;
S
SheetJS 已提交
396 397
			/* 18.18.11 t ST_CellType */
			switch(p.t) {
S
SheetJS 已提交
398
				case 'n':
S
SheetJS 已提交
399
					if(p.v == "" || p.v == null) {
S
SheetJS 已提交
400
						if(!sheetStubs) continue;
S
SheetJS 已提交
401 402
						p.t = 'z';
					} else p.v = parseFloat(p.v);
S
SheetJS 已提交
403
					break;
S
SheetJS 已提交
404
				case 's':
405
					if(typeof p.v == 'undefined') {
S
SheetJS 已提交
406
						if(!sheetStubs) continue;
S
SheetJS 已提交
407
						p.t = 'z';
408 409 410 411 412
					} else {
						sstr = strs[parseInt(p.v, 10)];
						p.v = sstr.t;
						p.r = sstr.r;
						if(opts.cellHTML) p.h = sstr.h;
413
					}
S
SheetJS 已提交
414
					break;
S
SheetJS 已提交
415 416 417
				case 'str':
					p.t = "s";
					p.v = (p.v!=null) ? utf8read(p.v) : '';
418
					if(opts.cellHTML) p.h = escapehtml(p.v);
S
SheetJS 已提交
419
					break;
S
SheetJS 已提交
420 421
				case 'inlineStr':
					cref = d.match(isregex);
S
SheetJS 已提交
422
					p.t = 's';
S
SheetJS 已提交
423 424 425 426
					if(cref != null && (sstr = parse_si(cref[1]))) {
						p.v = sstr.t;
						if(opts.cellHTML) p.h = sstr.h;
					} else p.v = "";
S
SheetJS 已提交
427
					break;
S
SheetJS 已提交
428 429
				case 'b': p.v = parsexmlbool(p.v); break;
				case 'd':
S
SheetJS 已提交
430 431
					if(opts.cellDates) p.v = parseDate(p.v, 1);
					else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
S
SheetJS 已提交
432
					break;
S
SheetJS 已提交
433
				/* error string in .w, number in .v */
S
SheetJS 已提交
434
				case 'e':
S
SheetJS 已提交
435
					if(!opts || opts.cellText !== false) p.w = p.v;
S
SheetJS 已提交
436
					p.v = RBErr[p.v]; break;
S
SheetJS 已提交
437 438 439
			}
			/* formatting */
			fmtid = fillid = 0;
S
SheetJS 已提交
440
			cf = null;
S
SheetJS 已提交
441 442 443 444
			if(do_format && tag.s !== undefined) {
				cf = styles.CellXf[tag.s];
				if(cf != null) {
					if(cf.numFmtId != null) fmtid = cf.numFmtId;
S
SheetJS 已提交
445 446 447
					if(opts.cellStyles) {
						if(cf.fillId != null) fillid = cf.fillId;
					}
S
SheetJS 已提交
448 449
				}
			}
S
SheetJS 已提交
450
			safe_format(p, fmtid, fillid, opts, themes, styles);
S
SheetJS 已提交
451
			if(opts.cellDates && do_format && p.t == 'n' && SSF.is_date(SSF._table[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
S
SheetJS 已提交
452 453 454 455 456
			if(dense) {
				var _r = decode_cell(tag.r);
				if(!s[_r.r]) s[_r.r] = [];
				s[_r.r][_r.c] = p;
			} else s[tag.r] = p;
S
SheetJS 已提交
457 458
		}
	}
S
SheetJS 已提交
459
	if(rows.length > 0) s['!rows'] = rows;
S
SheetJS 已提交
460 461
}; })();

S
SheetJS 已提交
462
function write_ws_xml_data(ws/*:Worksheet*/, opts, idx/*:number*/, wb/*:Workbook*//*::, rels*/)/*:string*/ {
S
SheetJS 已提交
463
	var o/*:Array<string>*/ = [], r/*:Array<string>*/ = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols/*:Array<string>*/ = [], R=0, C=0, rows = ws['!rows'];
S
SheetJS 已提交
464
	var dense = Array.isArray(ws);
465
	var params = ({r:rr}/*:any*/), row/*:RowInfo*/, height = -1;
466 467
	for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
	for(R = range.s.r; R <= range.e.r; ++R) {
468
		r = [];
S
SheetJS 已提交
469
		rr = encode_row(R);
470
		for(C = range.s.c; C <= range.e.c; ++C) {
S
SheetJS 已提交
471
			ref = cols[C] + rr;
S
SheetJS 已提交
472 473 474
			var _cell = dense ? (ws[R]||[])[C]: ws[ref];
			if(_cell === undefined) continue;
			if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
475
		}
476
		if(r.length > 0 || (rows && rows[R])) {
477
			params = ({r:rr}/*:any*/);
P
Paul Ishenin 已提交
478
			if(rows && rows[R]) {
479
				row = rows[R];
P
Paul Ishenin 已提交
480
				if(row.hidden) params.hidden = 1;
481
				height = -1;
482 483 484 485
				if(row.hpx) height = px2pt(row.hpx);
				else if(row.hpt) height = row.hpt;
				if(height > -1) { params.ht = height; params.customHeight = 1; }
				if(row.level) { params.outlineLevel = row.level; }
P
Paul Ishenin 已提交
486 487 488
			}
			o[o.length] = (writextag('row', r.join(""), params));
		}
489
	}
490 491
	if(rows) for(; R < rows.length; ++R) {
		if(rows && rows[R]) {
S
SheetJS 已提交
492 493
			params = ({r:R+1}/*:any*/);
			row = rows[R];
494
			if(row.hidden) params.hidden = 1;
S
SheetJS 已提交
495
			height = -1;
496 497 498 499 500 501 502
			if (row.hpx) height = px2pt(row.hpx);
			else if (row.hpt) height = row.hpt;
			if (height > -1) { params.ht = height; params.customHeight = 1; }
			if (row.level) { params.outlineLevel = row.level; }
			o[o.length] = (writextag('row', "", params));
		}
	}
503
	return o.join("");
S
SheetJS 已提交
504
}
505

S
SheetJS 已提交
506 507 508 509
var WS_XML_ROOT = writextag('worksheet', null, {
	'xmlns': XMLNS.main[0],
	'xmlns:r': XMLNS.r
});
S
SheetJS 已提交
510

S
SheetJS 已提交
511
function write_ws_xml(idx/*:number*/, opts, wb/*:Workbook*/, rels)/*:string*/ {
S
SheetJS 已提交
512
	var o = [XML_HEADER, WS_XML_ROOT];
513 514
	var s = wb.SheetNames[idx], sidx = 0, rdata = "";
	var ws = wb.Sheets[s];
S
SheetJS 已提交
515
	if(ws == null) ws = {};
516 517 518 519 520 521 522 523
	var ref = ws['!ref'] || 'A1';
	var range = safe_decode_range(ref);
	if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
		if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
		range.e.c = Math.min(range.e.c, 0x3FFF);
		range.e.r = Math.min(range.e.c, 0xFFFFF);
		ref = encode_range(range);
	}
S
SheetJS 已提交
524
	if(!rels) rels = {};
S
SheetJS 已提交
525
	ws['!comments'] = [];
526
	var _drawing = [];
S
SheetJS 已提交
527

528
	write_ws_xml_sheetpr(ws, wb, idx, opts, o);
S
SheetJS 已提交
529

530 531
	o[o.length] = (writextag('dimension', null, {'ref': ref}));

S
SheetJS 已提交
532
	o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
S
SheetJS 已提交
533

534
	/* TODO: store in WB, process styles */
535 536 537 538 539
	if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
		defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
		baseColWidth:opts.sheetFormat.baseColWidth||'10',
		outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
	}));
540

S
SheetJS 已提交
541 542
	if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));

543
	o[sidx = o.length] = '<sheetData/>';
S
SheetJS 已提交
544
	ws['!links'] = [];
S
SheetJS 已提交
545
	if(ws['!ref'] != null) {
S
SheetJS 已提交
546
		rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
547 548
		if(rdata.length > 0) o[o.length] = (rdata);
	}
S
SheetJS 已提交
549
	if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
550

S
SheetJS 已提交
551 552
	/* sheetCalcPr */

M
Mior 已提交
553 554
	if(ws['!protect'] != null) o[o.length] = write_ws_xml_protection(ws['!protect']);

S
SheetJS 已提交
555 556 557
	/* protectedRanges */
	/* scenarios */

S
SheetJS 已提交
558
	if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
S
SheetJS 已提交
559 560 561 562 563

	/* sortState */
	/* dataConsolidate */
	/* customSheetViews */

S
SheetJS 已提交
564
	if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
S
SheetJS 已提交
565

S
SheetJS 已提交
566 567 568 569
	/* phoneticPr */
	/* conditionalFormatting */
	/* dataValidations */

S
SheetJS 已提交
570
	var relc = -1, rel, rId = -1;
S
SheetJS 已提交
571
	if(/*::(*/ws['!links']/*::||[])*/.length > 0) {
S
SheetJS 已提交
572
		o[o.length] = "<hyperlinks>";
S
SheetJS 已提交
573
		/*::(*/ws['!links']/*::||[])*/.forEach(function(l) {
S
SheetJS 已提交
574
			if(!l[1].Target) return;
S
SheetJS 已提交
575 576 577 578 579
			rel = ({"ref":l[0]}/*:any*/);
			if(l[1].Target.charAt(0) != "#") {
				rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
				rel["r:id"] = "rId"+rId;
			}
580
			if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
S
SheetJS 已提交
581 582 583 584 585
			if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
			o[o.length] = writextag("hyperlink",null,rel);
		});
		o[o.length] = "</hyperlinks>";
	}
S
SheetJS 已提交
586
	delete ws['!links'];
S
SheetJS 已提交
587

S
SheetJS 已提交
588 589
	/* printOptions */

590
	if(ws['!margins'] != null) o[o.length] =  write_ws_xml_margins(ws['!margins']);
S
SheetJS 已提交
591

592 593
	/* pageSetup */
	/* headerFooter */
S
SheetJS 已提交
594 595 596 597
	/* rowBreaks */
	/* colBreaks */
	/* customProperties */
	/* cellWatches */
S
SheetJS 已提交
598

S
SheetJS 已提交
599
	if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
S
SheetJS 已提交
600

S
SheetJS 已提交
601 602
	/* smartTags */

603
	if(_drawing.length > 0) {
S
SheetJS 已提交
604 605
		rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
		o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
606
		ws['!drawing'] = _drawing;
S
SheetJS 已提交
607
	}
S
SheetJS 已提交
608

S
SheetJS 已提交
609 610 611 612 613 614
	if(ws['!comments'].length > 0) {
		rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
		o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
		ws['!legacy'] = rId;
	}

615
	/* legacyDrawingHF */
S
SheetJS 已提交
616 617 618 619 620
	/* picture */
	/* oleObjects */
	/* controls */
	/* webPublishItems */
	/* tableParts */
621
	/* extLst */
S
SheetJS 已提交
622

623
	if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
624
	return o.join("");
S
SheetJS 已提交
625
}