sheetjs-clone/dist/ods.min.js
SheetJS 86d6a093f0 version bump 0.8.2: ODS and cleanup
- README and example cleanup
- basic XLSB and ODS write support
- flow typecheck for ODS file
  Note: xlsx.js flow fails: https://github.com/facebook/flow/issues/380
- exposed jszip compression (fixes #220, closes #284)

README issues:

|  id  | author         | comment                                      |
|-----:|:---------------|:---------------------------------------------|
| #202 | @sao93859      | closes #202                                  |
| #211 | @alexanderchan | closes #211 corrected examples               |
| #327 | @cskaandorp    | changed saveAs example to match write tests  |
| #424 | @dskrvk        | added note about s2roa h/t @LeonardoPatignio |
| #496 | @jimmywarting  | closes #496 adapted rABS examples with rAAS  |

ODS file format issues:

|  id  | author         | comment                                      |
|-----:|:---------------|:---------------------------------------------|
| #148 | @user4815162342| closes #148 h/t @ziacik                      |
| #166 | @paulproteus   | closes #166 rudimentary ODS write support    |
| #177 | @ziacik        | closes #177                                  |
| #179 | @ziacik        | closes #179 use JSON when available          |
| #317 | @ziacik        | closes #317                                  |
| #328 | @think01       | closes #328                                  |
| #383 | @mdamt         | closes #383 duplicate cells should be copied |
| #430 | @RB-Lab        | closes #430                                  |
| #546 | @lgodard       | closes #546 thanks to other changes          |
2017-02-03 15:50:45 -05:00

3 lines
16 KiB
JavaScript

/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
var ODS={};(function make_ods(ODS){var get_utils=function(){if(typeof XLSX!=="undefined")return XLSX.utils;if(typeof module!=="undefined"&&typeof require!=="undefined")try{return require("../"+"xlsx").utils}catch(e){try{return require("./"+"xlsx").utils}catch(ee){return require("xl"+"sx").utils}}throw new Error("Cannot find XLSX utils")};var has_buf=typeof Buffer!=="undefined";function cc2str(arr){var o="";for(var i=0;i!=arr.length;++i)o+=String.fromCharCode(arr[i]);return o}function dup(o){if(typeof JSON!="undefined")return JSON.parse(JSON.stringify(o));if(typeof o!="object"||!o)return o;var out={};for(var k in o)if(o.hasOwnProperty(k))out[k]=dup(o[k]);return out}function getdata(data){if(!data)return null;if(data.data)return data.data;if(data.asNodeBuffer&&has_buf)return data.asNodeBuffer().toString("binary");if(data.asBinary)return data.asBinary();if(data._data&&data._data.getContent)return cc2str(Array.prototype.slice.call(data._data.getContent(),0));return null}function safegetzipfile(zip,file){var f=file;if(zip.files[f])return zip.files[f];f=file.toLowerCase();if(zip.files[f])return zip.files[f];f=f.replace(/\//g,"\\");if(zip.files[f])return zip.files[f];return null}function getzipfile(zip,file){var o=safegetzipfile(zip,file);if(o==null)throw new Error("Cannot find file "+file+" in zip");return o}function getzipdata(zip,file,safe){if(!safe)return getdata(getzipfile(zip,file));if(!file)return null;try{return getzipdata(zip,file)}catch(e){return null}}var _fs,jszip;if(typeof JSZip!=="undefined")jszip=JSZip;if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){if(has_buf&&typeof jszip==="undefined")jszip=require("js"+"zip");if(typeof jszip==="undefined")jszip=require("./js"+"zip").JSZip;_fs=require("f"+"s")}}var attregexg=/\b[\w:-]+=["'][^"]*['"]/g;var tagregex=/<[^>]*>/g;var nsregex=/<\w*:/,nsregex2=/<(\/?)\w+:/;function parsexmltag(tag,skip_root){var z=[];var eq=0,c=0;for(;eq!==tag.length;++eq)if((c=tag.charCodeAt(eq))===32||c===10||c===13)break;if(!skip_root)z[0]=tag.substr(0,eq);if(eq===tag.length)return z;var m=tag.match(attregexg),j=0,v="",i=0,q="",cc="";if(m)for(i=0;i!=m.length;++i){cc=m[i];for(c=0;c!=cc.length;++c)if(cc.charCodeAt(c)===61)break;q=cc.substr(0,c);v=cc.substring(c+2,cc.length-1);for(j=0;j!=q.length;++j)if(q.charCodeAt(j)===58)break;if(j===q.length)z[q]=v;else z[(j===5&&q.substr(0,5)==="xmlns"?"xmlns":"")+q.substr(j+1)]=v}return z}function strip_ns(x){return x.replace(nsregex2,"<$1")}var encodings={"&quot;":'"',"&apos;":"'","&gt;":">","&lt;":"<","&amp;":"&"};var rencoding={'"':"&quot;","'":"&apos;",">":"&gt;","<":"&lt;","&":"&amp;"};var rencstr="&<>'\"".split("");var encregex=/&[a-z]*;/g,coderegex=/_x([\da-fA-F]+)_/g;function unescapexml(text){var s=text+"";return s.replace(encregex,function($$){return encodings[$$]}).replace(coderegex,function(m,c){return String.fromCharCode(parseInt(c,16))})}var decregex=/[&<>'"]/g,charegex=/[\u0000-\u0008\u000b-\u001f]/g;function escapexml(text){var s=text+"";return s.replace(decregex,function(y){return rencoding[y]}).replace(charegex,function(s){return"_x"+("000"+s.charCodeAt(0).toString(16)).substr(-4)+"_"})}function parsexmlbool(value){switch(value){case"1":case"true":case"TRUE":return true;default:return false}}function datenum(v){var epoch=Date.parse(v);return(epoch+22091616e5)/(24*60*60*1e3)}function parse_isodur(s){var sec=0,mt=0,time=false;var m=s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);if(!m)throw new Error("|"+s+"| is not an ISO8601 Duration");for(var i=1;i!=m.length;++i){if(!m[i])continue;mt=1;if(i>3)time=true;switch(m[i].substr(m[i].length-1)){case"Y":throw new Error("Unsupported ISO Duration Field: "+m[i].substr(m[i].length-1));case"D":mt*=24;case"H":mt*=60;case"M":if(!time)throw new Error("Unsupported ISO Duration Field: M");else mt*=60;case"S":break}sec+=mt*parseInt(m[i],10)}return sec}var XML_HEADER='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';function xlml_normalize(d){if(has_buf&&Buffer.isBuffer(d))return d.toString("utf8");if(typeof d==="string")return d;throw"badf"}var xlmlregex=/<(\/?)([a-z0-9]*:|)([\w-]+)[^>]*>/gm;var CT_ODS="application/vnd.oasis.opendocument.spreadsheet";function parse_manifest(d,opts){var str=xlml_normalize(d);var Rn;var FEtag;while(Rn=xlmlregex.exec(str))switch(Rn[3]){case"manifest":break;case"file-entry":FEtag=parsexmltag(Rn[0],false);if(FEtag.path=="/"&&FEtag.type!==CT_ODS)throw new Error("This OpenDocument is not a spreadsheet");break;case"encryption-data":case"algorithm":case"start-key-generation":case"key-derivation":throw new Error("Unsupported ODS Encryption");default:if(opts&&opts.WTF)throw Rn}}function write_manifest(manifest,opts){var o=[XML_HEADER];o.push('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">\n');o.push(' <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>\n');for(var i=0;i<manifest.length;++i)o.push(' <manifest:file-entry manifest:full-path="'+manifest[i][0]+'" manifest:media-type="'+manifest[i][1]+'"/>\n');o.push("</manifest:manifest>");return o.join("")}function write_rdf_type(file,res,tag){return[' <rdf:Description rdf:about="'+file+'">\n',' <rdf:type rdf:resource="http://docs.oasis-open.org/ns/office/1.2/meta/'+(tag||"odf")+"#"+res+'"/>\n'," </rdf:Description>\n"].join("")}function write_rdf_has(base,file){return[' <rdf:Description rdf:about="'+base+'">\n',' <ns0:hasPart xmlns:ns0="http://docs.oasis-open.org/ns/office/1.2/meta/pkg#" rdf:resource="'+file+'"/>\n'," </rdf:Description>\n"].join("")}function write_rdf(rdf,opts){var o=[XML_HEADER];o.push('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n');for(var i=0;i!=rdf.length;++i){o.push(write_rdf_type(rdf[i][0],rdf[i][1]));o.push(write_rdf_has("",rdf[i][0]))}o.push(write_rdf_type("","Document","pkg"));o.push("</rdf:RDF>");return o.join("")}var parse_text_p=function(text,tag){return unescapexml(utf8read(text.replace(/<text:s\/>/g," ").replace(/<[^>]*>/g,"")))};var utf8read=function utf8reada(orig){var out="",i=0,c=0,d=0,e=0,f=0,w=0;while(i<orig.length){c=orig.charCodeAt(i++);if(c<128){out+=String.fromCharCode(c);continue}d=orig.charCodeAt(i++);if(c>191&&c<224){out+=String.fromCharCode((c&31)<<6|d&63);continue}e=orig.charCodeAt(i++);if(c<240){out+=String.fromCharCode((c&15)<<12|(d&63)<<6|e&63);continue}f=orig.charCodeAt(i++);w=((c&7)<<18|(d&63)<<12|(e&63)<<6|f&63)-65536;out+=String.fromCharCode(55296+(w>>>10&1023));out+=String.fromCharCode(56320+(w&1023))}return out};var parse_content_xml=function(){var number_formats={day:["d","dd"],month:["m","mm"],year:["y","yy"],hours:["h","hh"],minutes:["m","mm"],seconds:["s","ss"],"am-pm":["A/P","AM/PM"],"day-of-week":["ddd","dddd"]};return function pcx(d,opts){var str=xlml_normalize(d);var state=[],tmp;var tag;var NFtag={name:""},NF="",pidx=0;var sheetag;var Sheets={},SheetNames=[],ws={};var Rn,q;var ctag={value:""};var textp="",textpidx=0,textptag;var R=-1,C=-1,range={s:{r:1e6,c:1e7},e:{r:0,c:0}};var number_format_map={};var merges=[],mrange={},mR=0,mC=0;var rept=1;xlmlregex.lastIndex=0;while(Rn=xlmlregex.exec(str))switch(Rn[3]){case"table":if(Rn[1]==="/"){if(range.e.c>=range.s.c&&range.e.r>=range.s.r)ws["!ref"]=get_utils().encode_range(range);if(merges.length)ws["!merges"]=merges;sheetag.name=utf8read(sheetag.name);SheetNames.push(sheetag.name);Sheets[sheetag.name]=ws}else if(Rn[0].charAt(Rn[0].length-2)!=="/"){sheetag=parsexmltag(Rn[0],false);R=C=-1;range.s.r=range.s.c=1e7;range.e.r=range.e.c=0;ws={};merges=[]}break;case"table-row":if(Rn[1]==="/")break;++R;C=-1;break;case"covered-table-cell":++C;break;case"table-cell":if(Rn[0].charAt(Rn[0].length-2)==="/"){ctag=parsexmltag(Rn[0],false);if(ctag["number-columns-repeated"])C+=parseInt(ctag["number-columns-repeated"],10);else++C}else if(Rn[1]!=="/"){++C;rept=1;if(C>range.e.c)range.e.c=C;if(R>range.e.r)range.e.r=R;if(C<range.s.c)range.s.c=C;if(R<range.s.r)range.s.r=R;ctag=parsexmltag(Rn[0],false);q={t:ctag["value-type"],v:null};if(ctag["number-columns-spanned"]||ctag["number-rows-spanned"]){mR=parseInt(ctag["number-rows-spanned"],10)||0;mC=parseInt(ctag["number-columns-spanned"],10)||0;mrange={s:{r:R,c:C},e:{r:R+mR-1,c:C+mC-1}};merges.push(mrange)}if(ctag["number-columns-repeated"])rept=parseInt(ctag["number-columns-repeated"],10);switch(q.t){case"boolean":q.t="b";q.v=parsexmlbool(ctag["boolean-value"]);break;case"float":q.t="n";q.v=parseFloat(ctag.value);break;case"percentage":q.t="n";q.v=parseFloat(ctag.value);break;case"currency":q.t="n";q.v=parseFloat(ctag.value);break;case"date":q.t="n";q.v=datenum(ctag["date-value"]);q.z="m/d/yy";break;case"time":q.t="n";q.v=parse_isodur(ctag["time-value"])/86400;break;default:if(q.t==="string"||!q.t){q.t="s";if(ctag["string-value"]!=null)textp=ctag["string-value"]}else throw new Error("Unsupported value type "+q.t)}}else{if(q.t==="s")q.v=textp||"";if(textp)q.w=textp;if(!(opts.sheetRows&&opts.sheetRows<R)){ws[get_utils().encode_cell({r:R,c:C})]=q;while(--rept>0)ws[get_utils().encode_cell({r:R,c:++C})]=dup(q);if(range.e.c<=C)range.e.c=C}q={};textp=""}break;case"document-content":case"spreadsheet":case"scripts":case"font-face-decls":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp}else if(Rn[0].charAt(Rn[0].length-2)!=="/")state.push([Rn[3],true]);break;case"shapes":case"frame":case"text-box":case"image":case"data-pilot-tables":case"list-style":case"form":case"dde-links":case"annotation":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp}else if(Rn[0].charAt(Rn[0].length-2)!=="/")state.push([Rn[3],false]);break;case"number-style":case"percentage-style":case"date-style":case"time-style":if(Rn[1]==="/"){number_format_map[NFtag.name]=NF;if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp}else if(Rn[0].charAt(Rn[0].length-2)!=="/"){NF="";NFtag=parsexmltag(Rn[0],false);state.push([Rn[3],true])}break;case"script":break;case"automatic-styles":break;case"style":break;case"map":break;case"font-face":break;case"paragraph-properties":break;case"table-properties":break;case"table-column-properties":break;case"table-row-properties":break;case"table-cell-properties":break;case"number":switch(state[state.length-1][0]){case"time-style":case"date-style":tag=parsexmltag(Rn[0],false);NF+=number_formats[Rn[3]][tag.style==="long"?1:0];break}break;case"fraction":break;case"day":case"month":case"year":case"era":case"day-of-week":case"week-of-year":case"quarter":case"hours":case"minutes":case"seconds":case"am-pm":switch(state[state.length-1][0]){case"time-style":case"date-style":tag=parsexmltag(Rn[0],false);NF+=number_formats[Rn[3]][tag.style==="long"?1:0];break}break;case"boolean-style":break;case"boolean":break;case"text-style":break;case"text":if(Rn[0].substr(-2)==="/>")break;else if(Rn[1]==="/")switch(state[state.length-1][0]){case"number-style":case"date-style":case"time-style":NF+=str.slice(pidx,Rn.index);break}else pidx=Rn.index+Rn[0].length;break;case"text-content":break;case"text-properties":break;case"body":break;case"forms":break;case"table-column":break;case"null-date":break;case"graphic-properties":break;case"calculation-settings":break;case"named-expressions":break;case"named-range":break;case"named-expression":break;case"sort":break;case"sort-by":break;case"sort-groups":break;case"span":break;case"line-break":break;case"p":if(Rn[1]==="/")textp=parse_text_p(str.slice(textpidx,Rn.index),textptag);else{textptag=parsexmltag(Rn[0],false);textpidx=Rn.index+Rn[0].length}break;case"s":break;case"date":break;case"object":break;case"title":break;case"desc":break;case"table-source":break;case"iteration":break;case"content-validations":break;case"content-validation":break;case"error-message":break;case"database-ranges":break;case"database-range":break;case"filter":break;case"filter-and":break;case"filter-or":break;case"filter-condition":break;case"list-level-style-bullet":break;case"list-level-style-number":break;case"list-level-properties":break;case"sender-firstname":case"sender-lastname":case"sender-initials":case"sender-title":case"sender-position":case"sender-email":case"sender-phone-private":case"sender-fax":case"sender-company":case"sender-phone-work":case"sender-street":case"sender-city":case"sender-postal-code":case"sender-country":case"sender-state-or-province":case"author-name":case"author-initials":case"chapter":case"file-name":case"template-name":case"sheet-name":break;case"data-pilot-table":case"source-cell-range":case"source-service":case"data-pilot-field":case"data-pilot-level":case"data-pilot-subtotals":case"data-pilot-subtotal":case"data-pilot-members":case"data-pilot-member":case"data-pilot-display-info":case"data-pilot-sort-info":case"data-pilot-layout-info":case"data-pilot-field-reference":case"data-pilot-groups":case"data-pilot-group":case"data-pilot-group-member":break;case"rect":break;case"dde-connection-decls":case"dde-connection-decl":case"dde-link":case"dde-source":break;case"properties":break;case"property":break;case"a":break;case"table-protection":break;case"data-pilot-grand-total":break;default:if(Rn[2]==="dc:")break;if(Rn[2]==="draw:")break;if(Rn[2]==="calcext:")break;if(opts.WTF)throw Rn}var out={Sheets:Sheets,SheetNames:SheetNames};return out}}();var write_content_xml=function(){var null_cell_xml=" <table:table-cell />\n";var write_ws=function(ws,wb,i,opts){var o=[];o.push(' <table:table table:name="'+escapexml(wb.SheetNames[i])+'">\n');var R=0,C=0,range=get_utils().decode_range(ws["!ref"]);for(R=0;R<range.s.r;++R)o.push(" <table:table-row></table:table-row>\n");for(;R<=range.e.r;++R){o.push(" <table:table-row>\n");for(C=0;C<range.s.c;++C)o.push(null_cell_xml);for(;C<=range.e.c;++C){var ref=get_utils().encode_cell({r:R,c:C}),cell=ws[ref];if(cell)switch(cell.t){case"b":o.push(' <table:table-cell office:value-type="boolean" office:boolean-value="'+(cell.v?"true":"false")+'"><text:p>'+(cell.v?"TRUE":"FALSE")+"</text:p></table:table-cell>\n");break;case"n":o.push(' <table:table-cell office:value-type="float" office:value="'+cell.v+'"><text:p>'+(cell.w||cell.v)+"</text:p></table:table-cell>\n");break;case"s":case"str":o.push(' <table:table-cell office:value-type="string"><text:p>'+escapexml(cell.v)+"</text:p></table:table-cell>\n");break;default:o.push(null_cell_xml)}else o.push(null_cell_xml)}o.push(" </table:table-row>\n")}o.push(" </table:table>\n");return o.join("")};return function wcx(wb,opts){var o=[XML_HEADER];o.push('<office:document-content office:version="1.2" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">\n');o.push(" <office:body>\n");o.push(" <office:spreadsheet>\n");for(var i=0;i!=wb.SheetNames.length;++i)o.push(write_ws(wb.Sheets[wb.SheetNames[i]],wb,i,opts));o.push(" </office:spreadsheet>\n");o.push(" </office:body>\n");o.push("</office:document-content>");return o.join("")}}();function parse_ods(zip,opts){opts=opts||{};var manifest=parse_manifest(getzipdata(zip,"META-INF/manifest.xml"),opts);return parse_content_xml(getzipdata(zip,"content.xml"),opts)}function write_ods(wb,opts){var zip=new jszip;var f="";var manifest=[];var rdf=[];f="mimetype";zip.file(f,"application/vnd.oasis.opendocument.spreadsheet");f="content.xml";zip.file(f,write_content_xml(wb,opts));manifest.push([f,"text/xml"]);rdf.push([f,"ContentFile"]);f="manifest.rdf";zip.file(f,write_rdf(rdf,opts));manifest.push([f,"application/rdf+xml"]);f="META-INF/manifest.xml";zip.file(f,write_manifest(manifest,opts));return zip}ODS.parse_ods=parse_ods;ODS.write_ods=write_ods})(typeof exports!=="undefined"?exports:ODS);