Add ability to save cell styles to .xlsx

This commit is contained in:
Pieter Sheth-Voss 2015-02-28 01:42:41 -05:00
parent 61b17e6d9d
commit 0227496616
16 changed files with 1184 additions and 69 deletions

@ -0,0 +1,5 @@
<component name="DependencyValidationManager">
<state>
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</state>
</component>

@ -153,6 +153,11 @@ var STYLES_XML_ROOT = writextag('styleSheet', null, {
RELS.STY = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
function write_sty_xml(wb, opts) {
if (typeof style_builder != 'undefined' && typeof 'require' != 'undefined') {
return style_builder.toXml();
}
var o = [XML_HEADER, STYLES_XML_ROOT], w;
if((w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');

File diff suppressed because one or more lines are too long

@ -9,17 +9,28 @@ function get_sst_id(sst, str) {
}
function get_cell_style(styles, cell, opts) {
var z = opts.revssf[cell.z != null ? cell.z : "General"];
for(var i = 0, len = styles.length; i != len; ++i) if(styles[i].numFmtId === z) return i;
styles[len] = {
numFmtId:z,
fontId:0,
fillId:0,
borderId:0,
xfId:0,
applyNumberFormat:1
};
return len;
if (typeof style_builder != 'undefined') {
if (cell.s && (cell.s == +cell.s)) { return cell.s} // if its already an integer index, let it be
if (!cell.s) cell.s = {}
if (cell.z) cell.s.numFmtId = cell.z;
cell.s = style_builder.addStyle(cell.s);
return cell.s;
}
else {
var z = opts.revssf[cell.z != null ? cell.z : "General"];
for(var i = 0, len = styles.length; i != len; ++i) if(styles[i].numFmtId === z) return i;
styles[len] = {
numFmtId:z,
fontId:0,
fillId:0,
borderId:0,
xfId:0,
applyNumberFormat:1
};
return len;
}
}
function safe_format(p, fmtid, fillid, opts) {

@ -72,7 +72,7 @@ function write_zip(wb, opts) {
/* TODO: something more intelligent with themes */
f = "xl/theme/theme1.xml";
zip.file(f, write_theme());
zip.file(f, write_theme(opts));
ct.themes.push(f);
add_rels(opts.wbrels, ++rId, "theme/theme1.xml", RELS.THEME);

@ -12,6 +12,14 @@ function writeSync(wb, opts) {
function writeFileSync(wb, filename, opts) {
var o = opts||{}; o.type = 'file';
if (typeof module != 'undefined' && typeof 'require' != 'undefined') {
style_builder = new StyleBuilder(opts);
}
else if (typeof $ != 'undefined' || typeof 'jQuery' != 'undefined') {
style_builder = new StyleBuilder(opts);
}
o.file = filename;
switch(o.file.substr(-5).toLowerCase()) {
case '.xlsm': o.bookType = 'xlsm'; break;

@ -196,3 +196,342 @@ var utils = {
sheet_to_formulae: sheet_to_formulae,
sheet_to_row_object_array: sheet_to_row_object_array
};
if ((typeof 'module' != 'undefined' && typeof require != 'undefined') || (typeof $ != 'undefined')) {
var StyleBuilder = function (options) {
if(typeof module !== "undefined" && typeof require !== 'undefined' ) {
var cheerio = require('cheerio');
createElement = function(str) { return cheerio(cheerio(str, null, null, {xmlMode: true})); };
}
else if (typeof jQuery !== 'undefined' || typeof $ !== 'undefined') {
createElement = function(str) { return $(str); }
}
else {
createElement = function() { }
}
var customNumFmtId = 164;
var table_fmt = {
0: 'General',
1: '0',
2: '0.00',
3: '#,##0',
4: '#,##0.00',
9: '0%',
10: '0.00%',
11: '0.00E+00',
12: '# ?/?',
13: '# ??/??',
14: 'm/d/yy',
15: 'd-mmm-yy',
16: 'd-mmm',
17: 'mmm-yy',
18: 'h:mm AM/PM',
19: 'h:mm:ss AM/PM',
20: 'h:mm',
21: 'h:mm:ss',
22: 'm/d/yy h:mm',
37: '#,##0 ;(#,##0)',
38: '#,##0 ;[Red](#,##0)',
39: '#,##0.00;(#,##0.00)',
40: '#,##0.00;[Red](#,##0.00)',
45: 'mm:ss',
46: '[h]:mm:ss',
47: 'mmss.0',
48: '##0.0E+0',
49: '@',
56: '"上午/下午 "hh"時"mm"分"ss"秒 "',
65535: 'General'
};
var fmt_table = {};
for (var idx in table_fmt) {
fmt_table[table_fmt[idx]] = idx;
}
var baseXmlprefix = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
var baseXml =
'<styleSheet xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"\
xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" mc:Ignorable="x14ac">\
<numFmts count="1">\
<numFmt numFmtId="164" formatCode="0.00%"/>\
</numFmts>\
<fonts count="0" x14ac:knownFonts="1"></fonts>\
<fills count="0"></fills>\
<borders count="0"></borders>\
<cellStyleXfs count="1">\
<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>\
</cellStyleXfs>\
<cellXfs count="0"></cellXfs>\
<cellStyles count="1">\
<cellStyle name="Normal" xfId="0" builtinId="0"/>\
</cellStyles>\
<dxfs count="0"/>\
<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>\
</styleSheet>';
_hashIndex = {};
_listIndex = [];
return {
initialize: function (options) {
if (typeof cheerio !== 'undefined') {
this.$styles = cheerio.load(baseXml, {xmlMode: true});
this.$styles.find = function(q) { return this(q)}
}
else {
this.$styles = $(baseXml);
}
// need to specify styles at index 0 and 1.
// the second style MUST be gray125 for some reason
var defaultStyle = options.defaultCellStyle;
if (!defaultStyle) defaultStyle = {
font: {name: 'Calibri', sz: '11'},
fill: { fgColor: { patternType: "none"}},
border: {},
numFmt: null
};
if (!defaultStyle.border) { defaultStyle.border = {}}
var gray125Style = JSON.parse(JSON.stringify(defaultStyle));
gray125Style.fill = { fgColor: { patternType: "gray125"}}
this.addStyles([defaultStyle, gray125Style]);
return this;
},
// create a style entry and returns an integer index that can be used in the cell .s property
// these format of this object follows the emerging Common Spreadsheet Format
addStyle: function (attributes) {
var attributes = this._duckTypeStyle(attributes);
var hashKey = JSON.stringify(attributes);
var index = _hashIndex[hashKey];
if (index == undefined) {
index = this._addXf(attributes || {});
_hashIndex[hashKey] = index;
}
else {
index = _hashIndex[hashKey];
}
return index;
},
// create style entries and returns array of integer indexes that can be used in cell .s property
addStyles: function (styles) {
var self = this;
return styles.map(function (style) {
return self.addStyle(style);
})
},
_duckTypeStyle: function(attributes) {
if (typeof attributes == 'object' && (attributes.patternFill || attributes.fgColor)) {
return {fill: attributes }; // this must be read via XLSX.parseFile(...)
}
else if (attributes.font || attributes.numFmt || attributes.border || attributes.fill) {
return attributes;
}
else {
return this._getStyleCSS(attributes)
}
},
_getStyleCSS: function(css) {
return css; //TODO
},
// Create an <xf> record for the style as well as corresponding <font>, <fill>, <border>, <numfmts>
// Right now this is simple and creates a <font>, <fill>, <border>, <numfmts> for every <xf>
// We could perhaps get fancier and avoid duplicating auxiliary entries as Excel presumably intended, but bother.
_addXf: function (attributes) {
var fontId = this._addFont(attributes.font);
var fillId = this._addFill(attributes.fill);
var borderId = this._addBorder(attributes.border);
var numFmtId = this._addNumFmt(attributes.numFmt);
var $xf = createElement('<xf></xf>')
.attr("numFmtId", numFmtId)
.attr("fontId", fontId)
.attr("fillId", fillId)
.attr("borderId", 0)
.attr("xfId", "0");
if (fontId > 0) {
$xf.attr('applyFont', "1");
}
if (fillId > 0) {
$xf.attr('applyFill', "1");
}
if (borderId > 0) {
$xf.attr('applyBorder', "1");
}
if (numFmtId > 0) {
$xf.attr('applyNumberFormat', "1");
}
var $cellXfs = this.$styles.find('cellXfs');
$cellXfs.append($xf);
var count = +$cellXfs.attr('count') + 1;
$cellXfs.attr('count', count);
return count - 1;
},
_addFont: function (attributes) {
if (!attributes) {
return 0;
}
var $font = createElement('<font/>', null, null, {xmlMode: true});
$font.append(createElement('<sz/>').attr('val', attributes.sz))
.append(createElement('<color/>').attr('theme', '1'))
.append(createElement('<name/>').attr('val', attributes.name))
// .append(createElement('<family/>').attr('val', '2'))
// .append(createElement('<scheme/>').attr('val', 'minor'));
if (attributes.bold) $font.append('<b/>');
if (attributes.underline) $font.append('<u/>');
if (attributes.italic) $font.append('<i/>');
if (attributes.color) {
if (attributes.color.theme) {
$font.append(createElement('<color/>').attr('theme', attributes.color.theme));
} else if (attributes.color.rgb) {
$font.append(createElement('<color/>').attr('rgb', attributes.color.rgb));
}
}
var $fonts = this.$styles.find('fonts');
$fonts.append($font);
var count = $fonts.children().length;
$fonts.attr('count', count);
return count - 1;
},
_addNumFmt: function (numFmt) {
if (!numFmt) {
return 0;
}
if (typeof numFmt == 'string') {
var numFmtIdx = fmt_table[numFmt];
if (numFmtIdx >= 0) {
return numFmtIdx; // we found a match against built in formats
}
}
if (numFmt == +numFmt) {
return numFmt; // we're matching an integer against some known code
}
var $numFmt = createElement('<numFmt/>', null, null, {xmlMode: true})
.attr("numFmtId", ++customNumFmtId )
.attr("formatCode", numFmt);
var $numFmts = this.$styles.find('numFmts');
$numFmts.append($numFmt);
var count = $numFmts.children().length;
$numFmts.attr('count', count);
return customNumFmtId;
},
_addFill: function (attributes) {
if (!attributes) {
return 0;
}
var $patternFill = createElement('<patternFill></patternFill>', null, null, {xmlMode: true})
.attr('patternType', attributes.patternType || 'solid');
if (attributes.fgColor) {
//Excel doesn't like it when we set both rgb and theme+tint, but xlsx.parseFile() sets both
//var $fgColor = createElement('<fgColor/>', null, null, {xmlMode: true}).attr(attributes.fgColor)
if (attributes.fgColor.rgb) {
if (attributes.fgColor.rgb.length == 6) {
attributes.fgColor.rgb = "FF" + attributes.fgColor.rgb /// add alpha to an RGB as Excel expects aRGB
}
var $fgColor = createElement('<fgColor/>', null, null, {xmlMode: true}).
attr('rgb', attributes.fgColor.rgb);
$patternFill.append($fgColor);
}
else if (attributes.fgColor.theme) {
var $fgColor = createElement('<fgColor/>', null, null, {xmlMode: true});
$fgColor.attr('theme', attributes.fgColor.theme);
if (attributes.fgColor.tint) {
$fgColor.attr('tint', attributes.fgColor.tint);
}
$patternFill.append($fgColor);
}
if (!attributes.bgColor) {
attributes.bgColor = { "indexed": "64"}
}
}
if (attributes.bgColor) {
var $bgColor = createElement('<bgColor/>', null, null, {xmlMode: true}).attr(attributes.bgColor);
$patternFill.append($bgColor);
}
var $fill = createElement('<fill></fill>')
.append($patternFill);
this.$styles.find('fills').append($fill);
var $fills = this.$styles.find('fills')
$fills.append($fill);
var count = $fills.children().length;
$fills.attr('count', count);
return count - 1;
},
_addBorder: function (attributes) {
if (!attributes) {
return 0;
}
var $border = createElement('<border></border>')
.append('<left></left>')
.append('<right></right>')
.append('<top></top>')
.append('<bottom></bottom>')
.append('<diagonal></diagonal>');
var $borders = this.$styles.find('borders');
$borders.append($border);
var count = $borders.children().length;
$borders.attr('count', count);
return count;
},
toXml: function () {
if (this.$styles.find('numFmts').children().length == 0) {
this.$styles.find('numFmts').remove();
}
if (this.$styles.xml) { return this.$styles.xml(); }
else { return baseXmlprefix + this.$styles.html(); }
}
}.initialize(options||{});
}
}

28
dist/cpexcel.js vendored

@ -1,6 +1,6 @@
/* cpexcel.js (C) 2013-2014 SheetJS -- http://sheetjs.com */
/*jshint -W100 */
var cptable = {version:"1.3.6"};
var cptable = {version:"1.3.7"};
cptable[874] = (function(){ var d = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~<7F><E282AC><EFBFBD><EFBFBD><EFBFBD><E280A6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>“”•<E28093><E28094><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู<E0B8B9><E0B8BA><EFBFBD><EFBFBD>฿เแโใไๅๆ็่้๊๋์ํ๎๏๑๒๓๔๕๖๗๘๙๚๛<E0B99A><E0B99B><EFBFBD><EFBFBD>", D = [], e = {}; for(var i=0;i!=d.length;++i) { if(d.charCodeAt(i) !== 0xFFFD) e[d[i]] = i; D[i] = d.charAt(i); } return {"enc": e, "dec": D }; })();
cptable[932] = (function(){ var d = [], e = {}, D = [], j;
D[0] = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~<><7F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚<EFBE9E><EFBE9F><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>".split("");
@ -832,7 +832,9 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
var sfcc = function sfcc(x) { return String.fromCharCode(x); };
var cca = function cca(x){ return x.charCodeAt(0); };
if(typeof Buffer !== 'undefined') {
var has_buf = (typeof Buffer !== 'undefined');
if(has_buf) {
var mdl = 1024, mdb = new Buffer(mdl);
var make_EE = function make_EE(E){
var EE = new Buffer(65536);
@ -867,6 +869,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
}
out.length = j;
out = out.slice(0,j);
} else {
out = Buffer(len);
for(i = 0; i < len; ++i) out[i] = EE[data[i].charCodeAt(0)];
@ -925,6 +928,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
out[k++] = EE[j+1] || EE[j]; if(EE[j+1] > 0) out[k++] = EE[j];
}
out.length = k;
out = out.slice(0,k);
} else if(Buffer.isBuffer(data)) {
for(i = k = 0; i < len; ++i) {
D = data[i];
@ -939,6 +943,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
}
out.length = k;
out = out.slice(0,k);
} else {
for(i = k = 0; i < len; i++) {
j = data[i].charCodeAt(0)*2;
@ -1037,7 +1042,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
var encache = function encache() {
if(typeof Buffer !== 'undefined') {
if(has_buf) {
if(cpdcache[sbcs_cache[0]]) return;
var i, s;
for(i = 0; i < sbcs_cache.length; ++i) {
@ -1063,7 +1068,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
};
var cp_decache = function cp_decache(cp) { cpdcache[cp] = cpecache[cp] = undefined; };
var decache = function decache() {
if(typeof Buffer !== 'undefined') {
if(has_buf) {
if(!cpdcache[sbcs_cache[0]]) return;
sbcs_cache.forEach(cp_decache);
dbcs_cache.forEach(cp_decache);
@ -1086,9 +1091,9 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
var encode = function encode(cp, data, ofmt) {
if(cp === last_cp) { return last_enc(data, ofmt); }
if(cpecache[cp] !== undefined) { last_enc = cpecache[last_cp=cp]; return last_enc(data, ofmt); }
if(typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) data = data.toString('utf8');
if(has_buf && Buffer.isBuffer(data)) data = data.toString('utf8');
var len = data.length;
var out = typeof Buffer !== 'undefined' ? new Buffer(4*len) : [], w, i, j = 0, c, tt, ww;
var out = has_buf ? new Buffer(4*len) : [], w, i, j = 0, c, tt, ww;
var C = cpt[cp], E, M;
if(C && (E=C.enc)) for(i = 0; i < len; ++i, ++j) {
w = E[data[i]];
@ -1100,7 +1105,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
else if((M=magic[cp])) switch(M) {
case "utf8":
if(typeof Buffer !== 'undefined' && typeof data === "string") { out = new Buffer(data, M); j = out.length; break; }
if(has_buf && typeof data === "string") { out = new Buffer(data, M); j = out.length; break; }
for(i = 0; i < len; ++i, ++j) {
w = data[i].charCodeAt(0);
if(w <= 0x007F) out[j] = w;
@ -1122,7 +1127,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
break;
case "ascii":
if(typeof Buffer !== 'undefined' && typeof data === "string") { out = new Buffer(data, M); j = out.length; break; }
if(has_buf && typeof data === "string") { out = new Buffer(data, M); j = out.length; break; }
for(i = 0; i < len; ++i, ++j) {
w = data[i].charCodeAt(0);
if(w <= 0x007F) out[j] = w;
@ -1130,7 +1135,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
break;
case "utf16le":
if(typeof Buffer !== 'undefined' && typeof data === "string") { out = new Buffer(data, M); j = out.length; break; }
if(has_buf && typeof data === "string") { out = new Buffer(data, M); j = out.length; break; }
for(i = 0; i < len; ++i) {
w = data[i].charCodeAt(0);
out[j++] = w&255;
@ -1182,6 +1187,7 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
else throw new Error("Unrecognized CP: " + cp);
out.length = j;
out = out.slice(0,j);
if(typeof Buffer === 'undefined') return (ofmt == 'str') ? out.map(sfcc).join("") : out;
if(ofmt === undefined || ofmt === 'buf') return out;
if(ofmt !== 'arr') return out.toString('binary');
@ -1222,13 +1228,13 @@ if (typeof module !== 'undefined' && module.exports) module.exports = cptable;
}
break;
case "ascii":
if(typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) return data.toString(M);
if(has_buf && Buffer.isBuffer(data)) return data.toString(M);
for(i = 0; i < len; i++) out[i] = String.fromCharCode(data[i]);
k = len; break;
case "utf16le":
i = 0;
if(len >= 2 && data[0] == 0xFF) if(data[1] == 0xFE) i = 2;
if(typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) return data.toString(M);
if(has_buf && Buffer.isBuffer(data)) return data.toString(M);
j = 2;
for(; i < len; i+=j) {
out[k++] = String.fromCharCode((data[i+1]<<8) + data[i]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

13
dist/xlsx.full.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

402
dist/xlsx.js vendored

File diff suppressed because one or more lines are too long

6
dist/xlsx.min.js vendored

File diff suppressed because one or more lines are too long

2
dist/xlsx.min.map vendored

File diff suppressed because one or more lines are too long

394
xlsx.js

File diff suppressed because one or more lines are too long