xlsx.mini.js 336 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710
  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. function make_xlsx_lib(XLSX){
  7. XLSX.version = '0.16.9';
  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. 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(!isNaN(v)) return v;
  2641. if(!/\d/.test(s)) return v;
  2642. var wt = 1;
  2643. var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
  2644. if(!isNaN(v = Number(ss))) return v / wt;
  2645. ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
  2646. if(!isNaN(v = Number(ss))) return v / wt;
  2647. return v;
  2648. }
  2649. function fuzzydate(s) {
  2650. var o = new Date(s), n = new Date(NaN);
  2651. var y = o.getYear(), m = o.getMonth(), d = o.getDate();
  2652. if(isNaN(d)) return n;
  2653. if(y < 0 || y > 8099) return n;
  2654. if((m > 0 || d > 1) && y != 101) return o;
  2655. if(s.toLowerCase().match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) return o;
  2656. if(s.match(/[^-0-9:,\/\\]/)) return n;
  2657. return o;
  2658. }
  2659. var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  2660. function split_regex(str, re, def) {
  2661. if(safe_split_regex || typeof re == "string") return str.split(re);
  2662. var p = str.split(re), o = [p[0]];
  2663. for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
  2664. return o;
  2665. }
  2666. function getdatastr(data) {
  2667. if(!data) return null;
  2668. if(data.data) return debom(data.data);
  2669. if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
  2670. if(data.asBinary) return debom(data.asBinary());
  2671. if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
  2672. if(data.content && data.type) return debom(cc2str(data.content));
  2673. return null;
  2674. }
  2675. function getdatabin(data) {
  2676. if(!data) return null;
  2677. if(data.data) return char_codes(data.data);
  2678. if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  2679. if(data._data && data._data.getContent) {
  2680. var o = data._data.getContent();
  2681. if(typeof o == "string") return char_codes(o);
  2682. return Array.prototype.slice.call(o);
  2683. }
  2684. if(data.content && data.type) return data.content;
  2685. return null;
  2686. }
  2687. function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }
  2688. /* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
  2689. /* OASIS does not comment on filename case sensitivity */
  2690. function safegetzipfile(zip, file) {
  2691. var k = zip.FullPaths || keys(zip.files);
  2692. var f = file.toLowerCase(), g = f.replace(/\\/g,'\/');
  2693. for(var i=0; i<k.length; ++i) {
  2694. var n = k[i].replace(/^Root Entry[\/]/,"").toLowerCase();
  2695. if(f == n || g == n) return zip.FileIndex[i];
  2696. }
  2697. return null;
  2698. }
  2699. function getzipfile(zip, file) {
  2700. var o = safegetzipfile(zip, file);
  2701. if(o == null) throw new Error("Cannot find file " + file + " in zip");
  2702. return o;
  2703. }
  2704. function getzipdata(zip, file, safe) {
  2705. if(!safe) return getdata(getzipfile(zip, file));
  2706. if(!file) return null;
  2707. try { return getzipdata(zip, file); } catch(e) { return null; }
  2708. }
  2709. function getzipstr(zip, file, safe) {
  2710. if(!safe) return getdatastr(getzipfile(zip, file));
  2711. if(!file) return null;
  2712. try { return getzipstr(zip, file); } catch(e) { return null; }
  2713. }
  2714. function zipentries(zip) {
  2715. var k = zip.FullPaths || keys(zip.files), o = [];
  2716. for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i].replace(/^Root Entry[\/]/, ""));
  2717. return o.sort();
  2718. }
  2719. function zip_add_file(zip, path, content) {
  2720. if(zip.FullPaths) CFB.utils.cfb_add(zip, path, typeof content == "string" ? (has_buf ? Buffer_from(content) : s2a(utf8write(content))) : content);
  2721. else zip.file(path, content);
  2722. }
  2723. function zip_new() {
  2724. return CFB.utils.cfb_new();
  2725. }
  2726. function zip_read(d, o) {
  2727. var zip;
  2728. switch(o.type) {
  2729. case "base64": zip = CFB.read(d, { type: "base64" }); break;
  2730. case "binary": zip = CFB.read(d, { type: "binary" }); break;
  2731. case "buffer": case "array": zip = CFB.read(d, { type: "buffer" }); break;
  2732. default: throw new Error("Unrecognized type " + o.type);
  2733. }
  2734. return zip;
  2735. }
  2736. function resolve_path(path, base) {
  2737. if(path.charAt(0) == "/") return path.slice(1);
  2738. var result = base.split('/');
  2739. if(base.slice(-1) != "/") result.pop(); // folder path
  2740. var target = path.split('/');
  2741. while (target.length !== 0) {
  2742. var step = target.shift();
  2743. if (step === '..') result.pop();
  2744. else if (step !== '.') result.push(step);
  2745. }
  2746. return result.join('/');
  2747. }
  2748. var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
  2749. var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
  2750. var tagregex=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s?[\/\?]?>/mg;
  2751. if(!(XML_HEADER.match(tagregex))) tagregex = /<[^>]*>/g;
  2752. var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
  2753. function parsexmltag(tag, skip_root, skip_LC) {
  2754. var z = ({});
  2755. var eq = 0, c = 0;
  2756. for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
  2757. if(!skip_root) z[0] = tag.slice(0, eq);
  2758. if(eq === tag.length) return z;
  2759. var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
  2760. if(m) for(i = 0; i != m.length; ++i) {
  2761. cc = m[i];
  2762. for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
  2763. q = cc.slice(0,c).trim();
  2764. while(cc.charCodeAt(c+1) == 32) ++c;
  2765. quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
  2766. v = cc.slice(c+1+quot, cc.length-quot);
  2767. for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
  2768. if(j===q.length) {
  2769. if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
  2770. z[q] = v;
  2771. if(!skip_LC) z[q.toLowerCase()] = v;
  2772. }
  2773. else {
  2774. var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
  2775. if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
  2776. z[k] = v;
  2777. if(!skip_LC) z[k.toLowerCase()] = v;
  2778. }
  2779. }
  2780. return z;
  2781. }
  2782. function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
  2783. var encodings = {
  2784. '&quot;': '"',
  2785. '&apos;': "'",
  2786. '&gt;': '>',
  2787. '&lt;': '<',
  2788. '&amp;': '&'
  2789. };
  2790. var rencoding = evert(encodings);
  2791. //var rencstr = "&<>'\"".split("");
  2792. // TODO: CP remap (need to read file version to determine OS)
  2793. var unescapexml = (function() {
  2794. /* 22.4.2.4 bstr (Basic String) */
  2795. var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  2796. return function unescapexml(text) {
  2797. var s = text + '', i = s.indexOf("<![CDATA[");
  2798. 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));});
  2799. var j = s.indexOf("]]>");
  2800. return unescapexml(s.slice(0, i)) + s.slice(i+9,j) + unescapexml(s.slice(j+3));
  2801. };
  2802. })();
  2803. var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
  2804. function escapexml(text){
  2805. var s = text + '';
  2806. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
  2807. }
  2808. function escapexmltag(text){ return escapexml(text).replace(/ /g,"_x0020_"); }
  2809. var htmlcharegex = /[\u0000-\u001f]/g;
  2810. function escapehtml(text){
  2811. var s = text + '';
  2812. 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) + ";"; });
  2813. }
  2814. function escapexlml(text){
  2815. var s = text + '';
  2816. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
  2817. }
  2818. /* TODO: handle codepages */
  2819. var xlml_fixstr = (function() {
  2820. var entregex = /&#(\d+);/g;
  2821. function entrepl($$,$1) { return String.fromCharCode(parseInt($1,10)); }
  2822. return function xlml_fixstr(str) { return str.replace(entregex,entrepl); };
  2823. })();
  2824. var xlml_unfixstr = (function() {
  2825. return function xlml_unfixstr(str) { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); };
  2826. })();
  2827. function parsexmlbool(value) {
  2828. switch(value) {
  2829. case 1: case true: case '1': case 'true': case 'TRUE': return true;
  2830. /* case '0': case 'false': case 'FALSE':*/
  2831. default: return false;
  2832. }
  2833. }
  2834. var utf8read = function utf8reada(orig) {
  2835. var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
  2836. while (i < orig.length) {
  2837. c = orig.charCodeAt(i++);
  2838. if (c < 128) { out += String.fromCharCode(c); continue; }
  2839. d = orig.charCodeAt(i++);
  2840. if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
  2841. e = orig.charCodeAt(i++);
  2842. if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
  2843. f = orig.charCodeAt(i++);
  2844. w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
  2845. out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
  2846. out += String.fromCharCode(0xDC00 + (w&1023));
  2847. }
  2848. return out;
  2849. };
  2850. var utf8write = function(orig) {
  2851. var out = [], i = 0, c = 0, d = 0;
  2852. while(i < orig.length) {
  2853. c = orig.charCodeAt(i++);
  2854. switch(true) {
  2855. case c < 128: out.push(String.fromCharCode(c)); break;
  2856. case c < 2048:
  2857. out.push(String.fromCharCode(192 + (c >> 6)));
  2858. out.push(String.fromCharCode(128 + (c & 63)));
  2859. break;
  2860. case c >= 55296 && c < 57344:
  2861. c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
  2862. out.push(String.fromCharCode(240 + ((d >>18) & 7)));
  2863. out.push(String.fromCharCode(144 + ((d >>12) & 63)));
  2864. out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
  2865. out.push(String.fromCharCode(128 + (d & 63)));
  2866. break;
  2867. default:
  2868. out.push(String.fromCharCode(224 + (c >> 12)));
  2869. out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
  2870. out.push(String.fromCharCode(128 + (c & 63)));
  2871. }
  2872. }
  2873. return out.join("");
  2874. };
  2875. if(has_buf) {
  2876. var utf8readb = function utf8readb(data) {
  2877. var out = Buffer.alloc(2*data.length), w, i, j = 1, k = 0, ww=0, c;
  2878. for(i = 0; i < data.length; i+=j) {
  2879. j = 1;
  2880. if((c=data.charCodeAt(i)) < 128) w = c;
  2881. else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
  2882. else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
  2883. else { j = 4;
  2884. w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
  2885. w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
  2886. }
  2887. if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
  2888. out[k++] = w%256; out[k++] = w>>>8;
  2889. }
  2890. return out.slice(0,k).toString('ucs2');
  2891. };
  2892. var corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
  2893. if(utf8read(corpus) == utf8readb(corpus)) utf8read = utf8readb;
  2894. var utf8readc = function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); };
  2895. if(utf8read(corpus) == utf8readc(corpus)) utf8read = utf8readc;
  2896. utf8write = function(data) { return Buffer_from(data, 'utf8').toString("binary"); };
  2897. }
  2898. // matches <foo>...</foo> extracts content
  2899. var matchtag = (function() {
  2900. var mtcache = ({});
  2901. return function matchtag(f,g) {
  2902. var t = f+"|"+(g||"");
  2903. if(mtcache[t]) return mtcache[t];
  2904. return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||""))));
  2905. };
  2906. })();
  2907. var htmldecode = (function() {
  2908. var entities = [
  2909. ['nbsp', ' '], ['middot', '·'],
  2910. ['quot', '"'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['amp', '&']
  2911. ].map(function(x) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
  2912. return function htmldecode(str) {
  2913. var o = str
  2914. // Remove new lines and spaces from start of content
  2915. .replace(/^[\t\n\r ]+/, "")
  2916. // Remove new lines and spaces from end of content
  2917. .replace(/[\t\n\r ]+$/,"")
  2918. // Added line which removes any white space characters after and before html tags
  2919. .replace(/>\s+/g,">").replace(/\s+</g,"<")
  2920. // Replace remaining new lines and spaces with space
  2921. .replace(/[\t\n\r ]+/g, " ")
  2922. // Replace <br> tags with new lines
  2923. .replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
  2924. // Strip HTML elements
  2925. .replace(/<[^>]*>/g,"");
  2926. for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
  2927. return o;
  2928. };
  2929. })();
  2930. var vtregex = (function(){ var vt_cache = {};
  2931. return function vt_regex(bt) {
  2932. if(vt_cache[bt] !== undefined) return vt_cache[bt];
  2933. return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
  2934. };})();
  2935. var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
  2936. function parseVector(data, opts) {
  2937. var h = parsexmltag(data);
  2938. var matches = data.match(vtregex(h.baseType))||[];
  2939. var res = [];
  2940. if(matches.length != h.size) {
  2941. if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
  2942. return res;
  2943. }
  2944. matches.forEach(function(x) {
  2945. var v = x.replace(vtvregex,"").match(vtmregex);
  2946. if(v) res.push({v:utf8read(v[2]), t:v[1]});
  2947. });
  2948. return res;
  2949. }
  2950. var wtregex = /(^\s|\s$|\n)/;
  2951. function writetag(f,g) { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }
  2952. function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
  2953. function writextag(f,g,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
  2954. function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
  2955. function write_vt(s, xlsx) {
  2956. switch(typeof s) {
  2957. case 'string':
  2958. var o = writextag('vt:lpwstr', escapexml(s));
  2959. if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
  2960. return o;
  2961. case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
  2962. case 'boolean': return writextag('vt:bool',s?'true':'false');
  2963. }
  2964. if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
  2965. throw new Error("Unable to serialize " + s);
  2966. }
  2967. var XMLNS = ({
  2968. 'dc': 'http://purl.org/dc/elements/1.1/',
  2969. 'dcterms': 'http://purl.org/dc/terms/',
  2970. 'dcmitype': 'http://purl.org/dc/dcmitype/',
  2971. 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
  2972. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  2973. 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
  2974. 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
  2975. 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
  2976. 'xsd': 'http://www.w3.org/2001/XMLSchema'
  2977. });
  2978. XMLNS.main = [
  2979. 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  2980. 'http://purl.oclc.org/ooxml/spreadsheetml/main',
  2981. 'http://schemas.microsoft.com/office/excel/2006/main',
  2982. 'http://schemas.microsoft.com/office/excel/2006/2'
  2983. ];
  2984. var XLMLNS = ({
  2985. 'o': 'urn:schemas-microsoft-com:office:office',
  2986. 'x': 'urn:schemas-microsoft-com:office:excel',
  2987. 'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
  2988. 'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
  2989. 'mv': 'http://macVmlSchemaUri',
  2990. 'v': 'urn:schemas-microsoft-com:vml',
  2991. 'html': 'http://www.w3.org/TR/REC-html40'
  2992. });
  2993. function read_double_le(b, idx) {
  2994. var s = 1 - 2 * (b[idx + 7] >>> 7);
  2995. var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
  2996. var m = (b[idx+6]&0x0f);
  2997. for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
  2998. if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
  2999. if(e == 0) e = -1022;
  3000. else { e -= 1023; m += Math.pow(2,52); }
  3001. return s * Math.pow(2, e - 52) * m;
  3002. }
  3003. function write_double_le(b, v, idx) {
  3004. var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
  3005. var av = bs ? (-v) : v;
  3006. if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
  3007. else if(av == 0) e = m = 0;
  3008. else {
  3009. e = Math.floor(Math.log(av) / Math.LN2);
  3010. m = av * Math.pow(2, 52 - e);
  3011. if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
  3012. else { m -= Math.pow(2,52); e+=1023; }
  3013. }
  3014. for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
  3015. b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
  3016. b[idx + 7] = (e >> 4) | bs;
  3017. }
  3018. 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; };
  3019. var ___toBuffer = __toBuffer;
  3020. 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,''); };
  3021. var ___utf16le = __utf16le;
  3022. 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(""); };
  3023. var ___hexlify = __hexlify;
  3024. 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(""); };
  3025. var ___utf8 = __utf8;
  3026. var __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3027. var ___lpstr = __lpstr;
  3028. var __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3029. var ___cpstr = __cpstr;
  3030. var __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3031. var ___lpwstr = __lpwstr;
  3032. var __lpp4, ___lpp4;
  3033. __lpp4 = ___lpp4 = function lpp4_(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
  3034. var __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
  3035. var ___8lpp4 = __8lpp4;
  3036. var __double, ___double;
  3037. __double = ___double = function(b, idx) { return read_double_le(b, idx);};
  3038. var is_buf = function is_buf_a(a) { return Array.isArray(a); };
  3039. if(has_buf) {
  3040. __utf16le = function(b,s,e) { if(!Buffer.isBuffer(b)) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; };
  3041. __hexlify = function(b,s,l) { return Buffer.isBuffer(b) ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); };
  3042. __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) : "";};
  3043. __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) : "";};
  3044. __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);};
  3045. __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);};
  3046. __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);};
  3047. __utf8 = function utf8_b(b, s, e) { return (Buffer.isBuffer(b)) ? b.toString('utf8',s,e) : ___utf8(b,s,e); };
  3048. __toBuffer = function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0]) : ___toBuffer(bufs);};
  3049. bconcat = function(bufs) { return Buffer.isBuffer(bufs[0]) ? Buffer.concat(bufs) : [].concat.apply([], bufs); };
  3050. __double = function double_(b, i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
  3051. is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a); };
  3052. }
  3053. /* from js-xls */
  3054. if(typeof cptable !== 'undefined') {
  3055. __utf16le = function(b,s,e) { return cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
  3056. __utf8 = function(b,s,e) { return cptable.utils.decode(65001, b.slice(s,e)); };
  3057. __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)) : "";};
  3058. __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)) : "";};
  3059. __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)) : "";};
  3060. __lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
  3061. __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
  3062. }
  3063. var __readUInt8 = function(b, idx) { return b[idx]; };
  3064. var __readUInt16LE = function(b, idx) { return (b[idx+1]*(1<<8))+b[idx]; };
  3065. var __readInt16LE = function(b, idx) { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
  3066. var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
  3067. var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
  3068. var __readInt32BE = function(b, idx) { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };
  3069. function ReadShift(size, t) {
  3070. var o="", oI, oR, oo=[], w, vv, i, loc;
  3071. switch(t) {
  3072. case 'dbcs':
  3073. loc = this.l;
  3074. if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
  3075. else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
  3076. size *= 2;
  3077. break;
  3078. case 'utf8': o = __utf8(this, this.l, this.l + size); break;
  3079. case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;
  3080. case 'wstr':
  3081. if(typeof cptable !== 'undefined') o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
  3082. else return ReadShift.call(this, size, 'dbcs');
  3083. size = 2 * size; break;
  3084. /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
  3085. case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3086. case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3087. /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
  3088. case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
  3089. /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
  3090. case 'lpp4': size = 4 + __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
  3091. /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
  3092. case '8lpp4': size = 4 + __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;
  3093. case 'cstr': size = 0; o = "";
  3094. while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
  3095. o = oo.join(""); break;
  3096. case '_wstr': size = 0; o = "";
  3097. while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
  3098. size+=2; o = oo.join(""); break;
  3099. /* sbcs and dbcs support continue records in the SST way TODO codepages */
  3100. case 'dbcs-cont': o = ""; loc = this.l;
  3101. for(i = 0; i < size; ++i) {
  3102. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3103. w = __readUInt8(this, loc);
  3104. this.l = loc + 1;
  3105. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3106. return oo.join("") + vv;
  3107. }
  3108. oo.push(_getchar(__readUInt16LE(this, loc)));
  3109. loc+=2;
  3110. } o = oo.join(""); size *= 2; break;
  3111. case 'cpstr':
  3112. if(typeof cptable !== 'undefined') {
  3113. o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
  3114. break;
  3115. }
  3116. /* falls through */
  3117. case 'sbcs-cont': o = ""; loc = this.l;
  3118. for(i = 0; i != size; ++i) {
  3119. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3120. w = __readUInt8(this, loc);
  3121. this.l = loc + 1;
  3122. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3123. return oo.join("") + vv;
  3124. }
  3125. oo.push(_getchar(__readUInt8(this, loc)));
  3126. loc+=1;
  3127. } o = oo.join(""); break;
  3128. default:
  3129. switch(size) {
  3130. case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
  3131. case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
  3132. case 4: case -4:
  3133. if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
  3134. else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
  3135. case 8: case -8:
  3136. if(t === 'f') {
  3137. if(size == 8) oR = __double(this, this.l);
  3138. 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);
  3139. this.l += 8; return oR;
  3140. } else size = 8;
  3141. /* falls through */
  3142. case 16: o = __hexlify(this, this.l, size); break;
  3143. }}
  3144. this.l+=size; return o;
  3145. }
  3146. 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); };
  3147. 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); };
  3148. var __writeUInt16LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };
  3149. function WriteShift(t, val, f) {
  3150. var size = 0, i = 0;
  3151. if(f === 'dbcs') {
  3152. for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
  3153. size = 2 * val.length;
  3154. } else if(f === 'sbcs') {
  3155. if(typeof cptable !== 'undefined' && current_ansi == 874) {
  3156. /* TODO: use tables directly, don't encode */
  3157. for(i = 0; i != val.length; ++i) {
  3158. var cppayload = cptable.utils.encode(current_ansi, val.charAt(i));
  3159. this[this.l + i] = cppayload[0];
  3160. }
  3161. } else {
  3162. val = val.replace(/[^\x00-\x7F]/g, "_");
  3163. for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
  3164. }
  3165. size = val.length;
  3166. } else if(f === 'hex') {
  3167. for(; i < t; ++i) {
  3168. this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
  3169. } return this;
  3170. } else if(f === 'utf16le') {
  3171. var end = Math.min(this.l + t, this.length);
  3172. for(i = 0; i < Math.min(val.length, t); ++i) {
  3173. var cc = val.charCodeAt(i);
  3174. this[this.l++] = (cc & 0xff);
  3175. this[this.l++] = (cc >> 8);
  3176. }
  3177. while(this.l < end) this[this.l++] = 0;
  3178. return this;
  3179. } else switch(t) {
  3180. case 1: size = 1; this[this.l] = val&0xFF; break;
  3181. case 2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
  3182. 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;
  3183. case 4: size = 4; __writeUInt32LE(this, val, this.l); break;
  3184. case 8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
  3185. /* falls through */
  3186. case 16: break;
  3187. case -4: size = 4; __writeInt32LE(this, val, this.l); break;
  3188. }
  3189. this.l += size; return this;
  3190. }
  3191. function CheckField(hexstr, fld) {
  3192. var m = __hexlify(this,this.l,hexstr.length>>1);
  3193. if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
  3194. this.l += hexstr.length>>1;
  3195. }
  3196. function prep_blob(blob, pos) {
  3197. blob.l = pos;
  3198. blob.read_shift = ReadShift;
  3199. blob.chk = CheckField;
  3200. blob.write_shift = WriteShift;
  3201. }
  3202. function parsenoop(blob, length) { blob.l += length; }
  3203. function new_buf(sz) {
  3204. var o = new_raw_buf(sz);
  3205. prep_blob(o, 0);
  3206. return o;
  3207. }
  3208. /* [MS-XLSB] 2.1.4 Record */
  3209. function recordhopper(data, cb, opts) {
  3210. if(!data) return;
  3211. var tmpbyte, cntbyte, length;
  3212. prep_blob(data, data.l || 0);
  3213. var L = data.length, RT = 0, tgt = 0;
  3214. while(data.l < L) {
  3215. RT = data.read_shift(1);
  3216. if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
  3217. var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
  3218. tmpbyte = data.read_shift(1);
  3219. length = tmpbyte & 0x7F;
  3220. for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
  3221. tgt = data.l + length;
  3222. var d = (R.f||parsenoop)(data, length, opts);
  3223. data.l = tgt;
  3224. if(cb(d, R.n, RT)) return;
  3225. }
  3226. }
  3227. /* control buffer usage for fixed-length buffers */
  3228. function buf_array() {
  3229. var bufs = [], blksz = has_buf ? 256 : 2048;
  3230. var newblk = function ba_newblk(sz) {
  3231. var o = (new_buf(sz));
  3232. prep_blob(o, 0);
  3233. return o;
  3234. };
  3235. var curbuf = newblk(blksz);
  3236. var endbuf = function ba_endbuf() {
  3237. if(!curbuf) return;
  3238. if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
  3239. if(curbuf.length > 0) bufs.push(curbuf);
  3240. curbuf = null;
  3241. };
  3242. var next = function ba_next(sz) {
  3243. if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
  3244. endbuf();
  3245. return (curbuf = newblk(Math.max(sz+1, blksz)));
  3246. };
  3247. var end = function ba_end() {
  3248. endbuf();
  3249. return __toBuffer([bufs]);
  3250. };
  3251. var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };
  3252. return ({ next:next, push:push, end:end, _bufs:bufs });
  3253. }
  3254. function write_record(ba, type, payload, length) {
  3255. var t = +XLSBRE[type], l;
  3256. if(isNaN(t)) return; // TODO: throw something here?
  3257. if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
  3258. l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
  3259. if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
  3260. var o = ba.next(l);
  3261. if(t <= 0x7F) o.write_shift(1, t);
  3262. else {
  3263. o.write_shift(1, (t & 0x7F) + 0x80);
  3264. o.write_shift(1, (t >> 7));
  3265. }
  3266. for(var i = 0; i != 4; ++i) {
  3267. if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
  3268. else { o.write_shift(1, length); break; }
  3269. }
  3270. if(length > 0 && is_buf(payload)) ba.push(payload);
  3271. }
  3272. /* XLS ranges enforced */
  3273. function shift_cell_xls(cell, tgt, opts) {
  3274. var out = dup(cell);
  3275. if(tgt.s) {
  3276. if(out.cRel) out.c += tgt.s.c;
  3277. if(out.rRel) out.r += tgt.s.r;
  3278. } else {
  3279. if(out.cRel) out.c += tgt.c;
  3280. if(out.rRel) out.r += tgt.r;
  3281. }
  3282. if(!opts || opts.biff < 12) {
  3283. while(out.c >= 0x100) out.c -= 0x100;
  3284. while(out.r >= 0x10000) out.r -= 0x10000;
  3285. }
  3286. return out;
  3287. }
  3288. function shift_range_xls(cell, range, opts) {
  3289. var out = dup(cell);
  3290. out.s = shift_cell_xls(out.s, range.s, opts);
  3291. out.e = shift_cell_xls(out.e, range.s, opts);
  3292. return out;
  3293. }
  3294. function encode_cell_xls(c, biff) {
  3295. if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
  3296. if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
  3297. var s = encode_cell(c);
  3298. if(!c.cRel && c.cRel != null) s = fix_col(s);
  3299. if(!c.rRel && c.rRel != null) s = fix_row(s);
  3300. return s;
  3301. }
  3302. function encode_range_xls(r, opts) {
  3303. if(r.s.r == 0 && !r.s.rRel) {
  3304. if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
  3305. return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
  3306. }
  3307. }
  3308. if(r.s.c == 0 && !r.s.cRel) {
  3309. if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
  3310. return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
  3311. }
  3312. }
  3313. return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
  3314. }
  3315. function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
  3316. function encode_row(row) { return "" + (row + 1); }
  3317. function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
  3318. function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
  3319. 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; }
  3320. 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; }
  3321. function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
  3322. function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
  3323. function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
  3324. //function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
  3325. function decode_cell(cstr) {
  3326. var R = 0, C = 0;
  3327. for(var i = 0; i < cstr.length; ++i) {
  3328. var cc = cstr.charCodeAt(i);
  3329. if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
  3330. else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
  3331. }
  3332. return { c: C - 1, r:R - 1 };
  3333. }
  3334. //function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
  3335. function encode_cell(cell) {
  3336. var col = cell.c + 1;
  3337. var s="";
  3338. for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
  3339. return s + (cell.r + 1);
  3340. }
  3341. function decode_range(range) {
  3342. var idx = range.indexOf(":");
  3343. if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
  3344. return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
  3345. }
  3346. function encode_range(cs,ce) {
  3347. if(typeof ce === 'undefined' || typeof ce === 'number') {
  3348. return encode_range(cs.s, cs.e);
  3349. }
  3350. if(typeof cs !== 'string') cs = encode_cell((cs));
  3351. if(typeof ce !== 'string') ce = encode_cell((ce));
  3352. return cs == ce ? cs : cs + ":" + ce;
  3353. }
  3354. function safe_decode_range(range) {
  3355. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  3356. var idx = 0, i = 0, cc = 0;
  3357. var len = range.length;
  3358. for(idx = 0; i < len; ++i) {
  3359. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3360. idx = 26*idx + cc;
  3361. }
  3362. o.s.c = --idx;
  3363. for(idx = 0; i < len; ++i) {
  3364. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3365. idx = 10*idx + cc;
  3366. }
  3367. o.s.r = --idx;
  3368. if(i === len || range.charCodeAt(++i) === 58) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
  3369. for(idx = 0; i != len; ++i) {
  3370. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3371. idx = 26*idx + cc;
  3372. }
  3373. o.e.c = --idx;
  3374. for(idx = 0; i != len; ++i) {
  3375. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3376. idx = 10*idx + cc;
  3377. }
  3378. o.e.r = --idx;
  3379. return o;
  3380. }
  3381. function safe_format_cell(cell, v) {
  3382. var q = (cell.t == 'd' && v instanceof Date);
  3383. if(cell.z != null) try { return (cell.w = SSF.format(cell.z, q ? datenum(v) : v)); } catch(e) { }
  3384. try { return (cell.w = SSF.format((cell.XF||{}).numFmtId||(q ? 14 : 0), q ? datenum(v) : v)); } catch(e) { return ''+v; }
  3385. }
  3386. function format_cell(cell, v, o) {
  3387. if(cell == null || cell.t == null || cell.t == 'z') return "";
  3388. if(cell.w !== undefined) return cell.w;
  3389. if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
  3390. if(v == undefined) return safe_format_cell(cell, cell.v);
  3391. return safe_format_cell(cell, v);
  3392. }
  3393. function sheet_to_workbook(sheet, opts) {
  3394. var n = opts && opts.sheet ? opts.sheet : "Sheet1";
  3395. var sheets = {}; sheets[n] = sheet;
  3396. return { SheetNames: [n], Sheets: sheets };
  3397. }
  3398. function sheet_add_aoa(_ws, data, opts) {
  3399. var o = opts || {};
  3400. var dense = _ws ? Array.isArray(_ws) : o.dense;
  3401. if(DENSE != null && dense == null) dense = DENSE;
  3402. var ws = _ws || (dense ? ([]) : ({}));
  3403. var _R = 0, _C = 0;
  3404. if(ws && o.origin != null) {
  3405. if(typeof o.origin == 'number') _R = o.origin;
  3406. else {
  3407. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  3408. _R = _origin.r; _C = _origin.c;
  3409. }
  3410. if(!ws["!ref"]) ws["!ref"] = "A1:A1";
  3411. }
  3412. var range = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}});
  3413. if(ws['!ref']) {
  3414. var _range = safe_decode_range(ws['!ref']);
  3415. range.s.c = _range.s.c;
  3416. range.s.r = _range.s.r;
  3417. range.e.c = Math.max(range.e.c, _range.e.c);
  3418. range.e.r = Math.max(range.e.r, _range.e.r);
  3419. if(_R == -1) range.e.r = _R = _range.e.r + 1;
  3420. }
  3421. for(var R = 0; R != data.length; ++R) {
  3422. if(!data[R]) continue;
  3423. if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
  3424. for(var C = 0; C != data[R].length; ++C) {
  3425. if(typeof data[R][C] === 'undefined') continue;
  3426. var cell = ({v: data[R][C] });
  3427. var __R = _R + R, __C = _C + C;
  3428. if(range.s.r > __R) range.s.r = __R;
  3429. if(range.s.c > __C) range.s.c = __C;
  3430. if(range.e.r < __R) range.e.r = __R;
  3431. if(range.e.c < __C) range.e.c = __C;
  3432. if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
  3433. else {
  3434. if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
  3435. if(cell.v === null) { if(cell.f) cell.t = 'n'; else if(!o.sheetStubs) continue; else cell.t = 'z'; }
  3436. else if(typeof cell.v === 'number') cell.t = 'n';
  3437. else if(typeof cell.v === 'boolean') cell.t = 'b';
  3438. else if(cell.v instanceof Date) {
  3439. cell.z = o.dateNF || SSF._table[14];
  3440. if(o.cellDates) { cell.t = 'd'; cell.w = SSF.format(cell.z, datenum(cell.v)); }
  3441. else { cell.t = 'n'; cell.v = datenum(cell.v); cell.w = SSF.format(cell.z, cell.v); }
  3442. }
  3443. else cell.t = 's';
  3444. }
  3445. if(dense) {
  3446. if(!ws[__R]) ws[__R] = [];
  3447. if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
  3448. ws[__R][__C] = cell;
  3449. } else {
  3450. var cell_ref = encode_cell(({c:__C,r:__R}));
  3451. if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
  3452. ws[cell_ref] = cell;
  3453. }
  3454. }
  3455. }
  3456. if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
  3457. return ws;
  3458. }
  3459. function aoa_to_sheet(data, opts) { return sheet_add_aoa(null, data, opts); }
  3460. /* [MS-OLEPS] 2.2 PropertyType */
  3461. //var VT_EMPTY = 0x0000;
  3462. //var VT_NULL = 0x0001;
  3463. var VT_I2 = 0x0002;
  3464. var VT_I4 = 0x0003;
  3465. //var VT_R4 = 0x0004;
  3466. //var VT_R8 = 0x0005;
  3467. //var VT_CY = 0x0006;
  3468. //var VT_DATE = 0x0007;
  3469. //var VT_BSTR = 0x0008;
  3470. //var VT_ERROR = 0x000A;
  3471. var VT_BOOL = 0x000B;
  3472. var VT_VARIANT = 0x000C;
  3473. //var VT_DECIMAL = 0x000E;
  3474. //var VT_I1 = 0x0010;
  3475. //var VT_UI1 = 0x0011;
  3476. //var VT_UI2 = 0x0012;
  3477. var VT_UI4 = 0x0013;
  3478. //var VT_I8 = 0x0014;
  3479. //var VT_UI8 = 0x0015;
  3480. //var VT_INT = 0x0016;
  3481. //var VT_UINT = 0x0017;
  3482. var VT_LPSTR = 0x001E;
  3483. //var VT_LPWSTR = 0x001F;
  3484. var VT_FILETIME = 0x0040;
  3485. var VT_BLOB = 0x0041;
  3486. //var VT_STREAM = 0x0042;
  3487. //var VT_STORAGE = 0x0043;
  3488. //var VT_STREAMED_Object = 0x0044;
  3489. //var VT_STORED_Object = 0x0045;
  3490. //var VT_BLOB_Object = 0x0046;
  3491. var VT_CF = 0x0047;
  3492. //var VT_CLSID = 0x0048;
  3493. //var VT_VERSIONED_STREAM = 0x0049;
  3494. var VT_VECTOR = 0x1000;
  3495. //var VT_ARRAY = 0x2000;
  3496. var VT_STRING = 0x0050; // 2.3.3.1.11 VtString
  3497. var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString
  3498. var VT_CUSTOM = [VT_STRING, VT_USTR];
  3499. /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
  3500. var DocSummaryPIDDSI = {
  3501. 0x01: { n: 'CodePage', t: VT_I2 },
  3502. 0x02: { n: 'Category', t: VT_STRING },
  3503. 0x03: { n: 'PresentationFormat', t: VT_STRING },
  3504. 0x04: { n: 'ByteCount', t: VT_I4 },
  3505. 0x05: { n: 'LineCount', t: VT_I4 },
  3506. 0x06: { n: 'ParagraphCount', t: VT_I4 },
  3507. 0x07: { n: 'SlideCount', t: VT_I4 },
  3508. 0x08: { n: 'NoteCount', t: VT_I4 },
  3509. 0x09: { n: 'HiddenCount', t: VT_I4 },
  3510. 0x0a: { n: 'MultimediaClipCount', t: VT_I4 },
  3511. 0x0b: { n: 'ScaleCrop', t: VT_BOOL },
  3512. 0x0c: { n: 'HeadingPairs', t: VT_VECTOR | VT_VARIANT },
  3513. 0x0d: { n: 'TitlesOfParts', t: VT_VECTOR | VT_LPSTR },
  3514. 0x0e: { n: 'Manager', t: VT_STRING },
  3515. 0x0f: { n: 'Company', t: VT_STRING },
  3516. 0x10: { n: 'LinksUpToDate', t: VT_BOOL },
  3517. 0x11: { n: 'CharacterCount', t: VT_I4 },
  3518. 0x13: { n: 'SharedDoc', t: VT_BOOL },
  3519. 0x16: { n: 'HyperlinksChanged', t: VT_BOOL },
  3520. 0x17: { n: 'AppVersion', t: VT_I4, p: 'version' },
  3521. 0x18: { n: 'DigSig', t: VT_BLOB },
  3522. 0x1A: { n: 'ContentType', t: VT_STRING },
  3523. 0x1B: { n: 'ContentStatus', t: VT_STRING },
  3524. 0x1C: { n: 'Language', t: VT_STRING },
  3525. 0x1D: { n: 'Version', t: VT_STRING },
  3526. 0xFF: {}
  3527. };
  3528. /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
  3529. var SummaryPIDSI = {
  3530. 0x01: { n: 'CodePage', t: VT_I2 },
  3531. 0x02: { n: 'Title', t: VT_STRING },
  3532. 0x03: { n: 'Subject', t: VT_STRING },
  3533. 0x04: { n: 'Author', t: VT_STRING },
  3534. 0x05: { n: 'Keywords', t: VT_STRING },
  3535. 0x06: { n: 'Comments', t: VT_STRING },
  3536. 0x07: { n: 'Template', t: VT_STRING },
  3537. 0x08: { n: 'LastAuthor', t: VT_STRING },
  3538. 0x09: { n: 'RevNumber', t: VT_STRING },
  3539. 0x0A: { n: 'EditTime', t: VT_FILETIME },
  3540. 0x0B: { n: 'LastPrinted', t: VT_FILETIME },
  3541. 0x0C: { n: 'CreatedDate', t: VT_FILETIME },
  3542. 0x0D: { n: 'ModifiedDate', t: VT_FILETIME },
  3543. 0x0E: { n: 'PageCount', t: VT_I4 },
  3544. 0x0F: { n: 'WordCount', t: VT_I4 },
  3545. 0x10: { n: 'CharCount', t: VT_I4 },
  3546. 0x11: { n: 'Thumbnail', t: VT_CF },
  3547. 0x12: { n: 'Application', t: VT_STRING },
  3548. 0x13: { n: 'DocSecurity', t: VT_I4 },
  3549. 0xFF: {}
  3550. };
  3551. /* [MS-OLEPS] 2.18 */
  3552. var SpecialProperties = {
  3553. 0x80000000: { n: 'Locale', t: VT_UI4 },
  3554. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  3555. 0x72627262: {}
  3556. };
  3557. (function() {
  3558. for(var y in SpecialProperties) if(Object.prototype.hasOwnProperty.call(SpecialProperties, y))
  3559. DocSummaryPIDDSI[y] = SummaryPIDSI[y] = SpecialProperties[y];
  3560. })();
  3561. var DocSummaryRE = evert_key(DocSummaryPIDDSI, "n");
  3562. var SummaryRE = evert_key(SummaryPIDSI, "n");
  3563. /* [MS-XLS] 2.4.63 Country/Region codes */
  3564. var CountryEnum = {
  3565. 0x0001: "US", // United States
  3566. 0x0002: "CA", // Canada
  3567. 0x0003: "", // Latin America (except Brazil)
  3568. 0x0007: "RU", // Russia
  3569. 0x0014: "EG", // Egypt
  3570. 0x001E: "GR", // Greece
  3571. 0x001F: "NL", // Netherlands
  3572. 0x0020: "BE", // Belgium
  3573. 0x0021: "FR", // France
  3574. 0x0022: "ES", // Spain
  3575. 0x0024: "HU", // Hungary
  3576. 0x0027: "IT", // Italy
  3577. 0x0029: "CH", // Switzerland
  3578. 0x002B: "AT", // Austria
  3579. 0x002C: "GB", // United Kingdom
  3580. 0x002D: "DK", // Denmark
  3581. 0x002E: "SE", // Sweden
  3582. 0x002F: "NO", // Norway
  3583. 0x0030: "PL", // Poland
  3584. 0x0031: "DE", // Germany
  3585. 0x0034: "MX", // Mexico
  3586. 0x0037: "BR", // Brazil
  3587. 0x003d: "AU", // Australia
  3588. 0x0040: "NZ", // New Zealand
  3589. 0x0042: "TH", // Thailand
  3590. 0x0051: "JP", // Japan
  3591. 0x0052: "KR", // Korea
  3592. 0x0054: "VN", // Viet Nam
  3593. 0x0056: "CN", // China
  3594. 0x005A: "TR", // Turkey
  3595. 0x0069: "JS", // Ramastan
  3596. 0x00D5: "DZ", // Algeria
  3597. 0x00D8: "MA", // Morocco
  3598. 0x00DA: "LY", // Libya
  3599. 0x015F: "PT", // Portugal
  3600. 0x0162: "IS", // Iceland
  3601. 0x0166: "FI", // Finland
  3602. 0x01A4: "CZ", // Czech Republic
  3603. 0x0376: "TW", // Taiwan
  3604. 0x03C1: "LB", // Lebanon
  3605. 0x03C2: "JO", // Jordan
  3606. 0x03C3: "SY", // Syria
  3607. 0x03C4: "IQ", // Iraq
  3608. 0x03C5: "KW", // Kuwait
  3609. 0x03C6: "SA", // Saudi Arabia
  3610. 0x03CB: "AE", // United Arab Emirates
  3611. 0x03CC: "IL", // Israel
  3612. 0x03CE: "QA", // Qatar
  3613. 0x03D5: "IR", // Iran
  3614. 0xFFFF: "US" // United States
  3615. };
  3616. /* [MS-XLS] 2.5.127 */
  3617. var XLSFillPattern = [
  3618. null,
  3619. 'solid',
  3620. 'mediumGray',
  3621. 'darkGray',
  3622. 'lightGray',
  3623. 'darkHorizontal',
  3624. 'darkVertical',
  3625. 'darkDown',
  3626. 'darkUp',
  3627. 'darkGrid',
  3628. 'darkTrellis',
  3629. 'lightHorizontal',
  3630. 'lightVertical',
  3631. 'lightDown',
  3632. 'lightUp',
  3633. 'lightGrid',
  3634. 'lightTrellis',
  3635. 'gray125',
  3636. 'gray0625'
  3637. ];
  3638. function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }
  3639. /* [MS-XLS] 2.5.161 */
  3640. /* [MS-XLSB] 2.5.75 Icv */
  3641. var _XLSIcv = rgbify([
  3642. /* Color Constants */
  3643. 0x000000,
  3644. 0xFFFFFF,
  3645. 0xFF0000,
  3646. 0x00FF00,
  3647. 0x0000FF,
  3648. 0xFFFF00,
  3649. 0xFF00FF,
  3650. 0x00FFFF,
  3651. /* Overridable Defaults */
  3652. 0x000000,
  3653. 0xFFFFFF,
  3654. 0xFF0000,
  3655. 0x00FF00,
  3656. 0x0000FF,
  3657. 0xFFFF00,
  3658. 0xFF00FF,
  3659. 0x00FFFF,
  3660. 0x800000,
  3661. 0x008000,
  3662. 0x000080,
  3663. 0x808000,
  3664. 0x800080,
  3665. 0x008080,
  3666. 0xC0C0C0,
  3667. 0x808080,
  3668. 0x9999FF,
  3669. 0x993366,
  3670. 0xFFFFCC,
  3671. 0xCCFFFF,
  3672. 0x660066,
  3673. 0xFF8080,
  3674. 0x0066CC,
  3675. 0xCCCCFF,
  3676. 0x000080,
  3677. 0xFF00FF,
  3678. 0xFFFF00,
  3679. 0x00FFFF,
  3680. 0x800080,
  3681. 0x800000,
  3682. 0x008080,
  3683. 0x0000FF,
  3684. 0x00CCFF,
  3685. 0xCCFFFF,
  3686. 0xCCFFCC,
  3687. 0xFFFF99,
  3688. 0x99CCFF,
  3689. 0xFF99CC,
  3690. 0xCC99FF,
  3691. 0xFFCC99,
  3692. 0x3366FF,
  3693. 0x33CCCC,
  3694. 0x99CC00,
  3695. 0xFFCC00,
  3696. 0xFF9900,
  3697. 0xFF6600,
  3698. 0x666699,
  3699. 0x969696,
  3700. 0x003366,
  3701. 0x339966,
  3702. 0x003300,
  3703. 0x333300,
  3704. 0x993300,
  3705. 0x993366,
  3706. 0x333399,
  3707. 0x333333,
  3708. /* Other entries to appease BIFF8/12 */
  3709. 0xFFFFFF, /* 0x40 icvForeground ?? */
  3710. 0x000000, /* 0x41 icvBackground ?? */
  3711. 0x000000, /* 0x42 icvFrame ?? */
  3712. 0x000000, /* 0x43 icv3D ?? */
  3713. 0x000000, /* 0x44 icv3DText ?? */
  3714. 0x000000, /* 0x45 icv3DHilite ?? */
  3715. 0x000000, /* 0x46 icv3DShadow ?? */
  3716. 0x000000, /* 0x47 icvHilite ?? */
  3717. 0x000000, /* 0x48 icvCtlText ?? */
  3718. 0x000000, /* 0x49 icvCtlScrl ?? */
  3719. 0x000000, /* 0x4A icvCtlInv ?? */
  3720. 0x000000, /* 0x4B icvCtlBody ?? */
  3721. 0x000000, /* 0x4C icvCtlFrame ?? */
  3722. 0x000000, /* 0x4D icvCtlFore ?? */
  3723. 0x000000, /* 0x4E icvCtlBack ?? */
  3724. 0x000000, /* 0x4F icvCtlNeutral */
  3725. 0x000000, /* 0x50 icvInfoBk ?? */
  3726. 0x000000 /* 0x51 icvInfoText ?? */
  3727. ]);
  3728. var XLSIcv = dup(_XLSIcv);
  3729. /* [MS-XLSB] 2.5.97.2 */
  3730. var BErr = {
  3731. 0x00: "#NULL!",
  3732. 0x07: "#DIV/0!",
  3733. 0x0F: "#VALUE!",
  3734. 0x17: "#REF!",
  3735. 0x1D: "#NAME?",
  3736. 0x24: "#NUM!",
  3737. 0x2A: "#N/A",
  3738. 0x2B: "#GETTING_DATA",
  3739. 0xFF: "#WTF?"
  3740. };
  3741. var RBErr = evert_num(BErr);
  3742. /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
  3743. /* 12.3 Part Summary <SpreadsheetML> */
  3744. /* 14.2 Part Summary <DrawingML> */
  3745. /* [MS-XLSX] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
  3746. var ct2type/*{[string]:string}*/ = ({
  3747. /* Workbook */
  3748. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  3749. /* Worksheet */
  3750. "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
  3751. /* Macrosheet */
  3752. "application/vnd.ms-excel.intlmacrosheet": "TODO",
  3753. "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
  3754. /* File Properties */
  3755. "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  3756. "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  3757. "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  3758. /* Custom Data Properties */
  3759. "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  3760. "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  3761. /* PivotTable */
  3762. "application/vnd.ms-excel.pivotTable": "TODO",
  3763. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  3764. /* Chart Objects */
  3765. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  3766. /* Chart Colors */
  3767. "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  3768. /* Chart Style */
  3769. "application/vnd.ms-office.chartstyle+xml": "TODO",
  3770. /* Chart Advanced */
  3771. "application/vnd.ms-office.chartex+xml": "TODO",
  3772. /* Calculation Chain */
  3773. "application/vnd.ms-excel.calcChain": "calcchains",
  3774. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  3775. /* Printer Settings */
  3776. "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  3777. /* ActiveX */
  3778. "application/vnd.ms-office.activeX": "TODO",
  3779. "application/vnd.ms-office.activeX+xml": "TODO",
  3780. /* Custom Toolbars */
  3781. "application/vnd.ms-excel.attachedToolbars": "TODO",
  3782. /* External Data Connections */
  3783. "application/vnd.ms-excel.connections": "TODO",
  3784. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  3785. /* External Links */
  3786. "application/vnd.ms-excel.externalLink": "links",
  3787. "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  3788. /* Metadata */
  3789. "application/vnd.ms-excel.sheetMetadata": "TODO",
  3790. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "TODO",
  3791. /* PivotCache */
  3792. "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  3793. "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  3794. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  3795. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  3796. /* Query Table */
  3797. "application/vnd.ms-excel.queryTable": "TODO",
  3798. "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  3799. /* Shared Workbook */
  3800. "application/vnd.ms-excel.userNames": "TODO",
  3801. "application/vnd.ms-excel.revisionHeaders": "TODO",
  3802. "application/vnd.ms-excel.revisionLog": "TODO",
  3803. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  3804. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  3805. "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  3806. /* Single Cell Table */
  3807. "application/vnd.ms-excel.tableSingleCells": "TODO",
  3808. "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  3809. /* Slicer */
  3810. "application/vnd.ms-excel.slicer": "TODO",
  3811. "application/vnd.ms-excel.slicerCache": "TODO",
  3812. "application/vnd.ms-excel.slicer+xml": "TODO",
  3813. "application/vnd.ms-excel.slicerCache+xml": "TODO",
  3814. /* Sort Map */
  3815. "application/vnd.ms-excel.wsSortMap": "TODO",
  3816. /* Table */
  3817. "application/vnd.ms-excel.table": "TODO",
  3818. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  3819. /* Themes */
  3820. "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  3821. /* Theme Override */
  3822. "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  3823. /* Timeline */
  3824. "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
  3825. "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
  3826. /* VBA */
  3827. "application/vnd.ms-office.vbaProject": "vba",
  3828. "application/vnd.ms-office.vbaProjectSignature": "vba",
  3829. /* Volatile Dependencies */
  3830. "application/vnd.ms-office.volatileDependencies": "TODO",
  3831. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  3832. /* Control Properties */
  3833. "application/vnd.ms-excel.controlproperties+xml": "TODO",
  3834. /* Data Model */
  3835. "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  3836. /* Survey */
  3837. "application/vnd.ms-excel.Survey+xml": "TODO",
  3838. /* Drawing */
  3839. "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  3840. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  3841. "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  3842. "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  3843. "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  3844. "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  3845. /* VML */
  3846. "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  3847. "application/vnd.openxmlformats-package.relationships+xml": "rels",
  3848. "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  3849. /* Image */
  3850. "image/png": "TODO",
  3851. "sheet": "js"
  3852. });
  3853. var CT_LIST = (function(){
  3854. var o = {
  3855. workbooks: {
  3856. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  3857. xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
  3858. xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
  3859. xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
  3860. xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
  3861. },
  3862. strs: { /* Shared Strings */
  3863. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
  3864. xlsb: "application/vnd.ms-excel.sharedStrings"
  3865. },
  3866. comments: { /* Comments */
  3867. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  3868. xlsb: "application/vnd.ms-excel.comments"
  3869. },
  3870. sheets: { /* Worksheet */
  3871. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  3872. xlsb: "application/vnd.ms-excel.worksheet"
  3873. },
  3874. charts: { /* Chartsheet */
  3875. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
  3876. xlsb: "application/vnd.ms-excel.chartsheet"
  3877. },
  3878. dialogs: { /* Dialogsheet */
  3879. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
  3880. xlsb: "application/vnd.ms-excel.dialogsheet"
  3881. },
  3882. macros: { /* Macrosheet (Excel 4.0 Macros) */
  3883. xlsx: "application/vnd.ms-excel.macrosheet+xml",
  3884. xlsb: "application/vnd.ms-excel.macrosheet"
  3885. },
  3886. styles: { /* Styles */
  3887. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
  3888. xlsb: "application/vnd.ms-excel.styles"
  3889. }
  3890. };
  3891. keys(o).forEach(function(k) { ["xlsm", "xlam"].forEach(function(v) { if(!o[k][v]) o[k][v] = o[k].xlsx; }); });
  3892. keys(o).forEach(function(k){ keys(o[k]).forEach(function(v) { ct2type[o[k][v]] = k; }); });
  3893. return o;
  3894. })();
  3895. var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);
  3896. XMLNS.CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
  3897. function new_ct() {
  3898. return ({
  3899. workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
  3900. rels:[], strs:[], comments:[], links:[],
  3901. coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
  3902. calcchains:[], vba: [], drawings: [],
  3903. TODO:[], xmlns: "" });
  3904. }
  3905. function parse_ct(data) {
  3906. var ct = new_ct();
  3907. if(!data || !data.match) return ct;
  3908. var ctext = {};
  3909. (data.match(tagregex)||[]).forEach(function(x) {
  3910. var y = parsexmltag(x);
  3911. switch(y[0].replace(nsregex,"<")) {
  3912. case '<?xml': break;
  3913. case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
  3914. case '<Default': ctext[y.Extension] = y.ContentType; break;
  3915. case '<Override':
  3916. if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
  3917. break;
  3918. }
  3919. });
  3920. if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  3921. ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  3922. ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  3923. ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  3924. ct.defaults = ctext;
  3925. delete ct.calcchains;
  3926. return ct;
  3927. }
  3928. var CTYPE_XML_ROOT = writextag('Types', null, {
  3929. 'xmlns': XMLNS.CT,
  3930. 'xmlns:xsd': XMLNS.xsd,
  3931. 'xmlns:xsi': XMLNS.xsi
  3932. });
  3933. var CTYPE_DEFAULTS = [
  3934. ['xml', 'application/xml'],
  3935. ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
  3936. ['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
  3937. ['data', 'application/vnd.openxmlformats-officedocument.model+data'],
  3938. /* from test files */
  3939. ['bmp', 'image/bmp'],
  3940. ['png', 'image/png'],
  3941. ['gif', 'image/gif'],
  3942. ['emf', 'image/x-emf'],
  3943. ['wmf', 'image/x-wmf'],
  3944. ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
  3945. ['tif', 'image/tiff'], ['tiff', 'image/tiff'],
  3946. ['pdf', 'application/pdf'],
  3947. ['rels', type2ct.rels[0]]
  3948. ].map(function(x) {
  3949. return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
  3950. });
  3951. function write_ct(ct, opts) {
  3952. var o = [], v;
  3953. o[o.length] = (XML_HEADER);
  3954. o[o.length] = (CTYPE_XML_ROOT);
  3955. o = o.concat(CTYPE_DEFAULTS);
  3956. /* only write first instance */
  3957. var f1 = function(w) {
  3958. if(ct[w] && ct[w].length > 0) {
  3959. v = ct[w][0];
  3960. o[o.length] = (writextag('Override', null, {
  3961. 'PartName': (v[0] == '/' ? "":"/") + v,
  3962. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  3963. }));
  3964. }
  3965. };
  3966. /* book type-specific */
  3967. var f2 = function(w) {
  3968. (ct[w]||[]).forEach(function(v) {
  3969. o[o.length] = (writextag('Override', null, {
  3970. 'PartName': (v[0] == '/' ? "":"/") + v,
  3971. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  3972. }));
  3973. });
  3974. };
  3975. /* standard type */
  3976. var f3 = function(t) {
  3977. (ct[t]||[]).forEach(function(v) {
  3978. o[o.length] = (writextag('Override', null, {
  3979. 'PartName': (v[0] == '/' ? "":"/") + v,
  3980. 'ContentType': type2ct[t][0]
  3981. }));
  3982. });
  3983. };
  3984. f1('workbooks');
  3985. f2('sheets');
  3986. f2('charts');
  3987. f3('themes');
  3988. ['strs', 'styles'].forEach(f1);
  3989. ['coreprops', 'extprops', 'custprops'].forEach(f3);
  3990. f3('vba');
  3991. f3('comments');
  3992. f3('drawings');
  3993. if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
  3994. return o.join("");
  3995. }
  3996. /* 9.3 Relationships */
  3997. var RELS = ({
  3998. WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  3999. SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4000. HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  4001. VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  4002. XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  4003. XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  4004. XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  4005. CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  4006. CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  4007. VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
  4008. });
  4009. /* 9.3.3 Representing Relationships */
  4010. function get_rels_path(file) {
  4011. var n = file.lastIndexOf("/");
  4012. return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
  4013. }
  4014. function parse_rels(data, currentFilePath) {
  4015. var rels = {"!id":{}};
  4016. if (!data) return rels;
  4017. if (currentFilePath.charAt(0) !== '/') {
  4018. currentFilePath = '/'+currentFilePath;
  4019. }
  4020. var hash = {};
  4021. (data.match(tagregex)||[]).forEach(function(x) {
  4022. var y = parsexmltag(x);
  4023. /* 9.3.2.2 OPC_Relationships */
  4024. if (y[0] === '<Relationship') {
  4025. var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; rel.TargetMode = y.TargetMode;
  4026. var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
  4027. rels[canonictarget] = rel;
  4028. hash[y.Id] = rel;
  4029. }
  4030. });
  4031. rels["!id"] = hash;
  4032. return rels;
  4033. }
  4034. XMLNS.RELS = 'http://schemas.openxmlformats.org/package/2006/relationships';
  4035. var RELS_ROOT = writextag('Relationships', null, {
  4036. //'xmlns:ns0': XMLNS.RELS,
  4037. 'xmlns': XMLNS.RELS
  4038. });
  4039. /* TODO */
  4040. function write_rels(rels) {
  4041. var o = [XML_HEADER, RELS_ROOT];
  4042. keys(rels['!id']).forEach(function(rid) {
  4043. o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
  4044. });
  4045. if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
  4046. return o.join("");
  4047. }
  4048. var RELS_EXTERN = [RELS.HLINK, RELS.XPATH, RELS.XMISS];
  4049. function add_rels(rels, rId, f, type, relobj, targetmode) {
  4050. if(!relobj) relobj = {};
  4051. if(!rels['!id']) rels['!id'] = {};
  4052. if(rId < 0) for(rId = 1; rels['!id']['rId' + rId]; ++rId){/* empty */}
  4053. relobj.Id = 'rId' + rId;
  4054. relobj.Type = type;
  4055. relobj.Target = f;
  4056. if(targetmode) relobj.TargetMode = targetmode;
  4057. else if(RELS_EXTERN.indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
  4058. if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
  4059. rels['!id'][relobj.Id] = relobj;
  4060. rels[('/' + relobj.Target).replace("//","/")] = relobj;
  4061. return rId;
  4062. }
  4063. /* ECMA-376 Part II 11.1 Core Properties Part */
  4064. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  4065. var CORE_PROPS = [
  4066. ["cp:category", "Category"],
  4067. ["cp:contentStatus", "ContentStatus"],
  4068. ["cp:keywords", "Keywords"],
  4069. ["cp:lastModifiedBy", "LastAuthor"],
  4070. ["cp:lastPrinted", "LastPrinted"],
  4071. ["cp:revision", "RevNumber"],
  4072. ["cp:version", "Version"],
  4073. ["dc:creator", "Author"],
  4074. ["dc:description", "Comments"],
  4075. ["dc:identifier", "Identifier"],
  4076. ["dc:language", "Language"],
  4077. ["dc:subject", "Subject"],
  4078. ["dc:title", "Title"],
  4079. ["dcterms:created", "CreatedDate", 'date'],
  4080. ["dcterms:modified", "ModifiedDate", 'date']
  4081. ];
  4082. XMLNS.CORE_PROPS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
  4083. RELS.CORE_PROPS = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';
  4084. var CORE_PROPS_REGEX = (function() {
  4085. var r = new Array(CORE_PROPS.length);
  4086. for(var i = 0; i < CORE_PROPS.length; ++i) {
  4087. var f = CORE_PROPS[i];
  4088. var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
  4089. r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
  4090. }
  4091. return r;
  4092. })();
  4093. function parse_core_props(data) {
  4094. var p = {};
  4095. data = utf8read(data);
  4096. for(var i = 0; i < CORE_PROPS.length; ++i) {
  4097. var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
  4098. if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
  4099. if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
  4100. }
  4101. return p;
  4102. }
  4103. var CORE_PROPS_XML_ROOT = writextag('cp:coreProperties', null, {
  4104. //'xmlns': XMLNS.CORE_PROPS,
  4105. 'xmlns:cp': XMLNS.CORE_PROPS,
  4106. 'xmlns:dc': XMLNS.dc,
  4107. 'xmlns:dcterms': XMLNS.dcterms,
  4108. 'xmlns:dcmitype': XMLNS.dcmitype,
  4109. 'xmlns:xsi': XMLNS.xsi
  4110. });
  4111. function cp_doit(f, g, h, o, p) {
  4112. if(p[f] != null || g == null || g === "") return;
  4113. p[f] = g;
  4114. g = escapexml(g);
  4115. o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
  4116. }
  4117. function write_core_props(cp, _opts) {
  4118. var opts = _opts || {};
  4119. var o = [XML_HEADER, CORE_PROPS_XML_ROOT], p = {};
  4120. if(!cp && !opts.Props) return o.join("");
  4121. if(cp) {
  4122. 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);
  4123. 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);
  4124. }
  4125. for(var i = 0; i != CORE_PROPS.length; ++i) {
  4126. var f = CORE_PROPS[i];
  4127. var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
  4128. if(v === true) v = "1";
  4129. else if(v === false) v = "0";
  4130. else if(typeof v == "number") v = String(v);
  4131. if(v != null) cp_doit(f[0], v, null, o, p);
  4132. }
  4133. if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
  4134. return o.join("");
  4135. }
  4136. /* 15.2.12.3 Extended File Properties Part */
  4137. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  4138. var EXT_PROPS = [
  4139. ["Application", "Application", "string"],
  4140. ["AppVersion", "AppVersion", "string"],
  4141. ["Company", "Company", "string"],
  4142. ["DocSecurity", "DocSecurity", "string"],
  4143. ["Manager", "Manager", "string"],
  4144. ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  4145. ["SharedDoc", "SharedDoc", "bool"],
  4146. ["LinksUpToDate", "LinksUpToDate", "bool"],
  4147. ["ScaleCrop", "ScaleCrop", "bool"],
  4148. ["HeadingPairs", "HeadingPairs", "raw"],
  4149. ["TitlesOfParts", "TitlesOfParts", "raw"]
  4150. ];
  4151. XMLNS.EXT_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
  4152. RELS.EXT_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';
  4153. var PseudoPropsPairs = [
  4154. "Worksheets", "SheetNames",
  4155. "NamedRanges", "DefinedNames",
  4156. "Chartsheets", "ChartNames"
  4157. ];
  4158. function load_props_pairs(HP, TOP, props, opts) {
  4159. var v = [];
  4160. if(typeof HP == "string") v = parseVector(HP, opts);
  4161. else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
  4162. var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
  4163. var idx = 0, len = 0;
  4164. if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
  4165. len = +(v[i+1].v);
  4166. switch(v[i].v) {
  4167. case "Worksheets":
  4168. case "工作表":
  4169. case "Листы":
  4170. case "أوراق العمل":
  4171. case "ワークシート":
  4172. case "גליונות עבודה":
  4173. case "Arbeitsblätter":
  4174. case "Çalışma Sayfaları":
  4175. case "Feuilles de calcul":
  4176. case "Fogli di lavoro":
  4177. case "Folhas de cálculo":
  4178. case "Planilhas":
  4179. case "Regneark":
  4180. case "Hojas de cálculo":
  4181. case "Werkbladen":
  4182. props.Worksheets = len;
  4183. props.SheetNames = parts.slice(idx, idx + len);
  4184. break;
  4185. case "Named Ranges":
  4186. case "Rangos con nombre":
  4187. case "名前付き一覧":
  4188. case "Benannte Bereiche":
  4189. case "Navngivne områder":
  4190. props.NamedRanges = len;
  4191. props.DefinedNames = parts.slice(idx, idx + len);
  4192. break;
  4193. case "Charts":
  4194. case "Diagramme":
  4195. props.Chartsheets = len;
  4196. props.ChartNames = parts.slice(idx, idx + len);
  4197. break;
  4198. }
  4199. idx += len;
  4200. }
  4201. }
  4202. function parse_ext_props(data, p, opts) {
  4203. var q = {}; if(!p) p = {};
  4204. data = utf8read(data);
  4205. EXT_PROPS.forEach(function(f) {
  4206. var xml = (data.match(matchtag(f[0]))||[])[1];
  4207. switch(f[2]) {
  4208. case "string": if(xml) p[f[1]] = unescapexml(xml); break;
  4209. case "bool": p[f[1]] = xml === "true"; break;
  4210. case "raw":
  4211. var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
  4212. if(cur && cur.length > 0) q[f[1]] = cur[1];
  4213. break;
  4214. }
  4215. });
  4216. if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);
  4217. return p;
  4218. }
  4219. var EXT_PROPS_XML_ROOT = writextag('Properties', null, {
  4220. 'xmlns': XMLNS.EXT_PROPS,
  4221. 'xmlns:vt': XMLNS.vt
  4222. });
  4223. function write_ext_props(cp) {
  4224. var o = [], W = writextag;
  4225. if(!cp) cp = {};
  4226. cp.Application = "SheetJS";
  4227. o[o.length] = (XML_HEADER);
  4228. o[o.length] = (EXT_PROPS_XML_ROOT);
  4229. EXT_PROPS.forEach(function(f) {
  4230. if(cp[f[1]] === undefined) return;
  4231. var v;
  4232. switch(f[2]) {
  4233. case 'string': v = escapexml(String(cp[f[1]])); break;
  4234. case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
  4235. }
  4236. if(v !== undefined) o[o.length] = (W(f[0], v));
  4237. });
  4238. /* TODO: HeadingPairs, TitlesOfParts */
  4239. 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"})));
  4240. 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"})));
  4241. if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
  4242. return o.join("");
  4243. }
  4244. /* 15.2.12.2 Custom File Properties Part */
  4245. XMLNS.CUST_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
  4246. RELS.CUST_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';
  4247. var custregex = /<[^>]+>[^<]*/g;
  4248. function parse_cust_props(data, opts) {
  4249. var p = {}, name = "";
  4250. var m = data.match(custregex);
  4251. if(m) for(var i = 0; i != m.length; ++i) {
  4252. var x = m[i], y = parsexmltag(x);
  4253. switch(y[0]) {
  4254. case '<?xml': break;
  4255. case '<Properties': break;
  4256. case '<property': name = unescapexml(y.name); break;
  4257. case '</property>': name = null; break;
  4258. default: if (x.indexOf('<vt:') === 0) {
  4259. var toks = x.split('>');
  4260. var type = toks[0].slice(4), text = toks[1];
  4261. /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
  4262. switch(type) {
  4263. case 'lpstr': case 'bstr': case 'lpwstr':
  4264. p[name] = unescapexml(text);
  4265. break;
  4266. case 'bool':
  4267. p[name] = parsexmlbool(text);
  4268. break;
  4269. case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
  4270. p[name] = parseInt(text, 10);
  4271. break;
  4272. case 'r4': case 'r8': case 'decimal':
  4273. p[name] = parseFloat(text);
  4274. break;
  4275. case 'filetime': case 'date':
  4276. p[name] = parseDate(text);
  4277. break;
  4278. case 'cy': case 'error':
  4279. p[name] = unescapexml(text);
  4280. break;
  4281. default:
  4282. if(type.slice(-1) == '/') break;
  4283. if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
  4284. }
  4285. } else if(x.slice(0,2) === "</") {/* empty */
  4286. } else if(opts.WTF) throw new Error(x);
  4287. }
  4288. }
  4289. return p;
  4290. }
  4291. var CUST_PROPS_XML_ROOT = writextag('Properties', null, {
  4292. 'xmlns': XMLNS.CUST_PROPS,
  4293. 'xmlns:vt': XMLNS.vt
  4294. });
  4295. function write_cust_props(cp) {
  4296. var o = [XML_HEADER, CUST_PROPS_XML_ROOT];
  4297. if(!cp) return o.join("");
  4298. var pid = 1;
  4299. keys(cp).forEach(function custprop(k) { ++pid;
  4300. o[o.length] = (writextag('property', write_vt(cp[k], true), {
  4301. 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
  4302. 'pid': pid,
  4303. 'name': escapexml(k)
  4304. }));
  4305. });
  4306. if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
  4307. return o.join("");
  4308. }
  4309. /* from js-harb (C) 2014-present SheetJS */
  4310. var DBF = (function() {
  4311. var dbf_codepage_map = {
  4312. /* Code Pages Supported by Visual FoxPro */
  4313. 0x01: 437, 0x02: 850,
  4314. 0x03: 1252, 0x04: 10000,
  4315. 0x64: 852, 0x65: 866,
  4316. 0x66: 865, 0x67: 861,
  4317. 0x68: 895, 0x69: 620,
  4318. 0x6A: 737, 0x6B: 857,
  4319. 0x78: 950, 0x79: 949,
  4320. 0x7A: 936, 0x7B: 932,
  4321. 0x7C: 874, 0x7D: 1255,
  4322. 0x7E: 1256, 0x96: 10007,
  4323. 0x97: 10029, 0x98: 10006,
  4324. 0xC8: 1250, 0xC9: 1251,
  4325. 0xCA: 1254, 0xCB: 1253,
  4326. /* shapefile DBF extension */
  4327. 0x00: 20127, 0x08: 865,
  4328. 0x09: 437, 0x0A: 850,
  4329. 0x0B: 437, 0x0D: 437,
  4330. 0x0E: 850, 0x0F: 437,
  4331. 0x10: 850, 0x11: 437,
  4332. 0x12: 850, 0x13: 932,
  4333. 0x14: 850, 0x15: 437,
  4334. 0x16: 850, 0x17: 865,
  4335. 0x18: 437, 0x19: 437,
  4336. 0x1A: 850, 0x1B: 437,
  4337. 0x1C: 863, 0x1D: 850,
  4338. 0x1F: 852, 0x22: 852,
  4339. 0x23: 852, 0x24: 860,
  4340. 0x25: 850, 0x26: 866,
  4341. 0x37: 850, 0x40: 852,
  4342. 0x4D: 936, 0x4E: 949,
  4343. 0x4F: 950, 0x50: 874,
  4344. 0x57: 1252, 0x58: 1252,
  4345. 0x59: 1252,
  4346. 0xFF: 16969
  4347. };
  4348. var dbf_reverse_map = evert({
  4349. 0x01: 437, 0x02: 850,
  4350. 0x03: 1252, 0x04: 10000,
  4351. 0x64: 852, 0x65: 866,
  4352. 0x66: 865, 0x67: 861,
  4353. 0x68: 895, 0x69: 620,
  4354. 0x6A: 737, 0x6B: 857,
  4355. 0x78: 950, 0x79: 949,
  4356. 0x7A: 936, 0x7B: 932,
  4357. 0x7C: 874, 0x7D: 1255,
  4358. 0x7E: 1256, 0x96: 10007,
  4359. 0x97: 10029, 0x98: 10006,
  4360. 0xC8: 1250, 0xC9: 1251,
  4361. 0xCA: 1254, 0xCB: 1253,
  4362. 0x00: 20127
  4363. });
  4364. var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
  4365. /* TODO: find an actual specification */
  4366. function dbf_to_aoa(buf, opts) {
  4367. var out = [];
  4368. /* TODO: browser based */
  4369. var d = (new_raw_buf(1));
  4370. switch(opts.type) {
  4371. case 'base64': d = s2a(Base64.decode(buf)); break;
  4372. case 'binary': d = s2a(buf); break;
  4373. case 'buffer':
  4374. case 'array': d = buf; break;
  4375. }
  4376. prep_blob(d, 0);
  4377. /* header */
  4378. var ft = d.read_shift(1);
  4379. var memo = false;
  4380. var vfp = false, l7 = false;
  4381. switch(ft) {
  4382. case 0x02: case 0x03: break;
  4383. case 0x30: vfp = true; memo = true; break;
  4384. case 0x31: vfp = true; break;
  4385. case 0x83: memo = true; break;
  4386. case 0x8B: memo = true; break;
  4387. case 0x8C: memo = true; l7 = true; break;
  4388. case 0xF5: memo = true; break;
  4389. default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
  4390. }
  4391. var /*filedate = new Date(),*/ nrow = 0, fpos = 0;
  4392. if(ft == 0x02) nrow = d.read_shift(2);
  4393. /*filedate = new Date(d.read_shift(1) + 1900, d.read_shift(1) - 1, d.read_shift(1));*/d.l += 3;
  4394. if(ft != 0x02) nrow = d.read_shift(4);
  4395. if(ft != 0x02) fpos = d.read_shift(2);
  4396. var rlen = d.read_shift(2);
  4397. var /*flags = 0,*/ current_cp = 1252;
  4398. if(ft != 0x02) {
  4399. d.l+=16;
  4400. /*flags = */d.read_shift(1);
  4401. //if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));
  4402. /* codepage present in FoxPro */
  4403. if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
  4404. d.l+=1;
  4405. d.l+=2;
  4406. }
  4407. if(l7) d.l += 36;
  4408. var fields = [], field = ({});
  4409. var hend = fpos - 10 - (vfp ? 264 : 0), ww = l7 ? 32 : 11;
  4410. while(ft == 0x02 ? d.l < d.length && d[d.l] != 0x0d: d.l < hend) {
  4411. field = ({});
  4412. field.name = cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)).replace(/[\u0000\r\n].*$/g,"");
  4413. d.l += ww;
  4414. field.type = String.fromCharCode(d.read_shift(1));
  4415. if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
  4416. field.len = d.read_shift(1);
  4417. if(ft == 0x02) field.offset = d.read_shift(2);
  4418. field.dec = d.read_shift(1);
  4419. if(field.name.length) fields.push(field);
  4420. if(ft != 0x02) d.l += l7 ? 13 : 14;
  4421. switch(field.type) {
  4422. case 'B': // VFP Double
  4423. if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  4424. break;
  4425. case 'G': // General
  4426. case 'P': // Picture
  4427. if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  4428. break;
  4429. case 'C': // character
  4430. case 'D': // date
  4431. case 'F': // floating point
  4432. case 'I': // long
  4433. case 'L': // boolean
  4434. case 'M': // memo
  4435. case 'N': // number
  4436. case 'O': // double
  4437. case 'T': // datetime
  4438. case 'Y': // currency
  4439. case '0': // VFP _NullFlags
  4440. case '@': // timestamp
  4441. case '+': // autoincrement
  4442. break;
  4443. default: throw new Error('Unknown Field Type: ' + field.type);
  4444. }
  4445. }
  4446. if(d[d.l] !== 0x0D) d.l = fpos-1;
  4447. else if(ft == 0x02) d.l = 0x209;
  4448. if(ft != 0x02) {
  4449. if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
  4450. d.l = fpos;
  4451. }
  4452. /* data */
  4453. var R = 0, C = 0;
  4454. out[0] = [];
  4455. for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
  4456. while(nrow-- > 0) {
  4457. if(d[d.l] === 0x2A) { d.l+=rlen; continue; }
  4458. ++d.l;
  4459. out[++R] = []; C = 0;
  4460. for(C = 0; C != fields.length; ++C) {
  4461. var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
  4462. prep_blob(dd, 0);
  4463. var s = cptable.utils.decode(current_cp, dd);
  4464. switch(fields[C].type) {
  4465. case 'C':
  4466. out[R][C] = cptable.utils.decode(current_cp, dd);
  4467. out[R][C] = out[R][C].trim();
  4468. break;
  4469. case 'D':
  4470. if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
  4471. else out[R][C] = s;
  4472. break;
  4473. case 'F': out[R][C] = parseFloat(s.trim()); break;
  4474. case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
  4475. case 'L': switch(s.toUpperCase()) {
  4476. case 'Y': case 'T': out[R][C] = true; break;
  4477. case 'N': case 'F': out[R][C] = false; break;
  4478. case ' ': case '?': out[R][C] = false; break; /* NOTE: technically uninitialized */
  4479. default: throw new Error("DBF Unrecognized L:|" + s + "|");
  4480. } break;
  4481. case 'M': /* TODO: handle memo files */
  4482. if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
  4483. out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
  4484. break;
  4485. case 'N': out[R][C] = +s.replace(/\u0000/g,"").trim(); break;
  4486. case '@': out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400); break;
  4487. case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
  4488. case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4; break;
  4489. case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
  4490. case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
  4491. /* falls through */
  4492. case 'G': case 'P': dd.l += fields[C].len; break;
  4493. case '0':
  4494. if(fields[C].name === '_NullFlags') break;
  4495. /* falls through */
  4496. default: throw new Error("DBF Unsupported data type " + fields[C].type);
  4497. }
  4498. }
  4499. }
  4500. 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));
  4501. if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
  4502. return out;
  4503. }
  4504. function dbf_to_sheet(buf, opts) {
  4505. var o = opts || {};
  4506. if(!o.dateNF) o.dateNF = "yyyymmdd";
  4507. return aoa_to_sheet(dbf_to_aoa(buf, o), o);
  4508. }
  4509. function dbf_to_workbook(buf, opts) {
  4510. try { return sheet_to_workbook(dbf_to_sheet(buf, opts), opts); }
  4511. catch(e) { if(opts && opts.WTF) throw e; }
  4512. return ({SheetNames:[],Sheets:{}});
  4513. }
  4514. var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
  4515. function sheet_to_dbf(ws, opts) {
  4516. var o = opts || {};
  4517. if(+o.codepage >= 0) set_cp(+o.codepage);
  4518. if(o.type == "string") throw new Error("Cannot write DBF to JS string");
  4519. var ba = buf_array();
  4520. var aoa = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
  4521. var headers = aoa[0], data = aoa.slice(1);
  4522. var i = 0, j = 0, hcnt = 0, rlen = 1;
  4523. for(i = 0; i < headers.length; ++i) {
  4524. if(i == null) continue;
  4525. ++hcnt;
  4526. if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
  4527. if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
  4528. if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
  4529. if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
  4530. }
  4531. var range = safe_decode_range(ws['!ref']);
  4532. var coltypes = [];
  4533. for(i = 0; i <= range.e.c - range.s.c; ++i) {
  4534. var col = [];
  4535. for(j=0; j < data.length; ++j) {
  4536. if(data[j][i] != null) col.push(data[j][i]);
  4537. }
  4538. if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
  4539. var guess = '', _guess = '';
  4540. for(j = 0; j < col.length; ++j) {
  4541. switch(typeof col[j]) {
  4542. /* TODO: check if L2 compat is desired */
  4543. case 'number': _guess = 'B'; break;
  4544. case 'string': _guess = 'C'; break;
  4545. case 'boolean': _guess = 'L'; break;
  4546. case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
  4547. default: _guess = 'C';
  4548. }
  4549. guess = guess && guess != _guess ? 'C' : _guess;
  4550. if(guess == 'C') break;
  4551. }
  4552. rlen += _RLEN[guess] || 0;
  4553. coltypes[i] = guess;
  4554. }
  4555. var h = ba.next(32);
  4556. h.write_shift(4, 0x13021130);
  4557. h.write_shift(4, data.length);
  4558. h.write_shift(2, 296 + 32 * hcnt);
  4559. h.write_shift(2, rlen);
  4560. for(i=0; i < 4; ++i) h.write_shift(4, 0);
  4561. h.write_shift(4, 0x00000000 | ((+dbf_reverse_map[current_ansi] || 0x03)<<8));
  4562. for(i = 0, j = 0; i < headers.length; ++i) {
  4563. if(headers[i] == null) continue;
  4564. var hf = ba.next(32);
  4565. var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
  4566. hf.write_shift(1, _f, "sbcs");
  4567. hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
  4568. hf.write_shift(4, j);
  4569. hf.write_shift(1, _RLEN[coltypes[i]] || 0);
  4570. hf.write_shift(1, 0);
  4571. hf.write_shift(1, 0x02);
  4572. hf.write_shift(4, 0);
  4573. hf.write_shift(1, 0);
  4574. hf.write_shift(4, 0);
  4575. hf.write_shift(4, 0);
  4576. j += _RLEN[coltypes[i]] || 0;
  4577. }
  4578. var hb = ba.next(264);
  4579. hb.write_shift(4, 0x0000000D);
  4580. for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
  4581. for(i=0; i < data.length; ++i) {
  4582. var rout = ba.next(rlen);
  4583. rout.write_shift(1, 0);
  4584. for(j=0; j<headers.length; ++j) {
  4585. if(headers[j] == null) continue;
  4586. switch(coltypes[j]) {
  4587. case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
  4588. case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
  4589. case 'D':
  4590. if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
  4591. else {
  4592. rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
  4593. rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
  4594. rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
  4595. } break;
  4596. case 'C':
  4597. var _s = String(data[i][j]||"");
  4598. rout.write_shift(1, _s, "sbcs");
  4599. for(hcnt=0; hcnt < 250-_s.length; ++hcnt) rout.write_shift(1, 0x20); break;
  4600. }
  4601. }
  4602. // data
  4603. }
  4604. ba.next(1).write_shift(1, 0x1A);
  4605. return ba.end();
  4606. }
  4607. return {
  4608. versions: DBF_SUPPORTED_VERSIONS,
  4609. to_workbook: dbf_to_workbook,
  4610. to_sheet: dbf_to_sheet,
  4611. from_sheet: sheet_to_dbf
  4612. };
  4613. })();
  4614. var SYLK = (function() {
  4615. /* TODO: stress test sequences */
  4616. var sylk_escapes = ({
  4617. AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
  4618. AE:'È', BE:'É', CE:'Ê', HE:'Ë',
  4619. AI:'Ì', BI:'Í', CI:'Î', HI:'Ï',
  4620. AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
  4621. AU:'Ù', BU:'Ú', CU:'Û', HU:'Ü',
  4622. Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
  4623. Ae:'è', Be:'é', Ce:'ê', He:'ë',
  4624. Ai:'ì', Bi:'í', Ci:'î', Hi:'ï',
  4625. Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
  4626. Au:'ù', Bu:'ú', Cu:'û', Hu:'ü',
  4627. KC:'Ç', Kc:'ç', q:'æ', z:'œ', a:'Æ', j:'Œ',
  4628. DN:209, Dn:241, Hy:255,
  4629. S:169, c:170, R:174, B:180,
  4630. 0:176, 1:177, 2:178,
  4631. 3:179, 5:181, 6:182,
  4632. 7:183, Q:185, k:186, b:208, i:216, l:222, s:240, y:248,
  4633. "!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
  4634. "+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
  4635. });
  4636. var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
  4637. var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
  4638. var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
  4639. sylk_escapes["|"] = 254;
  4640. /* TODO: find an actual specification */
  4641. function sylk_to_aoa(d, opts) {
  4642. switch(opts.type) {
  4643. case 'base64': return sylk_to_aoa_str(Base64.decode(d), opts);
  4644. case 'binary': return sylk_to_aoa_str(d, opts);
  4645. case 'buffer': return sylk_to_aoa_str(d.toString('binary'), opts);
  4646. case 'array': return sylk_to_aoa_str(cc2str(d), opts);
  4647. }
  4648. throw new Error("Unrecognized type " + opts.type);
  4649. }
  4650. function sylk_to_aoa_str(str, opts) {
  4651. var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr = [];
  4652. var formats = [];
  4653. var next_cell_format = null;
  4654. var sht = {}, rowinfo = [], colinfo = [], cw = [];
  4655. var Mval = 0, j;
  4656. if(+opts.codepage >= 0) set_cp(+opts.codepage);
  4657. for (; ri !== records.length; ++ri) {
  4658. Mval = 0;
  4659. var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
  4660. var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
  4661. var RT=record[0], val;
  4662. if(rstr.length > 0) switch(RT) {
  4663. case 'ID': break; /* header */
  4664. case 'E': break; /* EOF */
  4665. case 'B': break; /* dimensions */
  4666. case 'O': break; /* options? */
  4667. case 'P':
  4668. if(record[1].charAt(0) == 'P')
  4669. formats.push(rstr.slice(3).replace(/;;/g, ";"));
  4670. break;
  4671. case 'C':
  4672. var C_seen_K = false, C_seen_X = false;
  4673. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  4674. case 'X': C = parseInt(record[rj].slice(1))-1; C_seen_X = true; break;
  4675. case 'Y':
  4676. R = parseInt(record[rj].slice(1))-1; if(!C_seen_X) C = 0;
  4677. for(j = arr.length; j <= R; ++j) arr[j] = [];
  4678. break;
  4679. case 'K':
  4680. val = record[rj].slice(1);
  4681. if(val.charAt(0) === '"') val = val.slice(1,val.length - 1);
  4682. else if(val === 'TRUE') val = true;
  4683. else if(val === 'FALSE') val = false;
  4684. else if(!isNaN(fuzzynum(val))) {
  4685. val = fuzzynum(val);
  4686. if(next_cell_format !== null && SSF.is_date(next_cell_format)) val = numdate(val);
  4687. } else if(!isNaN(fuzzydate(val).getDate())) {
  4688. val = parseDate(val);
  4689. }
  4690. if(typeof cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = cptable.utils.decode(opts.codepage, val);
  4691. C_seen_K = true;
  4692. break;
  4693. case 'E':
  4694. var formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
  4695. arr[R][C] = [arr[R][C], formula];
  4696. break;
  4697. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  4698. }
  4699. if(C_seen_K) { arr[R][C] = val; next_cell_format = null; }
  4700. break;
  4701. case 'F':
  4702. var F_seen = 0;
  4703. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  4704. case 'X': C = parseInt(record[rj].slice(1))-1; ++F_seen; break;
  4705. case 'Y':
  4706. R = parseInt(record[rj].slice(1))-1; /*C = 0;*/
  4707. for(j = arr.length; j <= R; ++j) arr[j] = [];
  4708. break;
  4709. case 'M': Mval = parseInt(record[rj].slice(1)) / 20; break;
  4710. case 'F': break; /* ??? */
  4711. case 'G': break; /* hide grid */
  4712. case 'P':
  4713. next_cell_format = formats[parseInt(record[rj].slice(1))];
  4714. break;
  4715. case 'S': break; /* cell style */
  4716. case 'D': break; /* column */
  4717. case 'N': break; /* font */
  4718. case 'W':
  4719. cw = record[rj].slice(1).split(" ");
  4720. for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
  4721. Mval = parseInt(cw[2], 10);
  4722. colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval}; process_col(colinfo[j-1]);
  4723. } break;
  4724. case 'C': /* default column format */
  4725. C = parseInt(record[rj].slice(1))-1;
  4726. if(!colinfo[C]) colinfo[C] = {};
  4727. break;
  4728. case 'R': /* row properties */
  4729. R = parseInt(record[rj].slice(1))-1;
  4730. if(!rowinfo[R]) rowinfo[R] = {};
  4731. if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
  4732. else if(Mval === 0) rowinfo[R].hidden = true;
  4733. break;
  4734. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  4735. }
  4736. if(F_seen < 1) next_cell_format = null; break;
  4737. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  4738. }
  4739. }
  4740. if(rowinfo.length > 0) sht['!rows'] = rowinfo;
  4741. if(colinfo.length > 0) sht['!cols'] = colinfo;
  4742. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  4743. return [arr, sht];
  4744. }
  4745. function sylk_to_sheet(d, opts) {
  4746. var aoasht = sylk_to_aoa(d, opts);
  4747. var aoa = aoasht[0], ws = aoasht[1];
  4748. var o = aoa_to_sheet(aoa, opts);
  4749. keys(ws).forEach(function(k) { o[k] = ws[k]; });
  4750. return o;
  4751. }
  4752. function sylk_to_workbook(d, opts) { return sheet_to_workbook(sylk_to_sheet(d, opts), opts); }
  4753. function write_ws_cell_sylk(cell, ws, R, C) {
  4754. var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
  4755. switch(cell.t) {
  4756. case 'n':
  4757. o += (cell.v||0);
  4758. if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
  4759. case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
  4760. case 'e': o += cell.w || cell.v; break;
  4761. case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
  4762. case 's': o += '"' + cell.v.replace(/"/g,"") + '"'; break;
  4763. }
  4764. return o;
  4765. }
  4766. function write_ws_cols_sylk(out, cols) {
  4767. cols.forEach(function(col, i) {
  4768. var rec = "F;W" + (i+1) + " " + (i+1) + " ";
  4769. if(col.hidden) rec += "0";
  4770. else {
  4771. if(typeof col.width == 'number') col.wpx = width2px(col.width);
  4772. if(typeof col.wpx == 'number') col.wch = px2char(col.wpx);
  4773. if(typeof col.wch == 'number') rec += Math.round(col.wch);
  4774. }
  4775. if(rec.charAt(rec.length - 1) != " ") out.push(rec);
  4776. });
  4777. }
  4778. function write_ws_rows_sylk(out, rows) {
  4779. rows.forEach(function(row, i) {
  4780. var rec = "F;";
  4781. if(row.hidden) rec += "M0;";
  4782. else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
  4783. else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
  4784. if(rec.length > 2) out.push(rec + "R" + (i+1));
  4785. });
  4786. }
  4787. function sheet_to_sylk(ws, opts) {
  4788. var preamble = ["ID;PWXL;N;E"], o = [];
  4789. var r = safe_decode_range(ws['!ref']), cell;
  4790. var dense = Array.isArray(ws);
  4791. var RS = "\r\n";
  4792. preamble.push("P;PGeneral");
  4793. preamble.push("F;P0;DG0G8;M255");
  4794. if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
  4795. if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);
  4796. 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(" "));
  4797. for(var R = r.s.r; R <= r.e.r; ++R) {
  4798. for(var C = r.s.c; C <= r.e.c; ++C) {
  4799. var coord = encode_cell({r:R,c:C});
  4800. cell = dense ? (ws[R]||[])[C]: ws[coord];
  4801. if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
  4802. o.push(write_ws_cell_sylk(cell, ws, R, C, opts));
  4803. }
  4804. }
  4805. return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
  4806. }
  4807. return {
  4808. to_workbook: sylk_to_workbook,
  4809. to_sheet: sylk_to_sheet,
  4810. from_sheet: sheet_to_sylk
  4811. };
  4812. })();
  4813. var DIF = (function() {
  4814. function dif_to_aoa(d, opts) {
  4815. switch(opts.type) {
  4816. case 'base64': return dif_to_aoa_str(Base64.decode(d), opts);
  4817. case 'binary': return dif_to_aoa_str(d, opts);
  4818. case 'buffer': return dif_to_aoa_str(d.toString('binary'), opts);
  4819. case 'array': return dif_to_aoa_str(cc2str(d), opts);
  4820. }
  4821. throw new Error("Unrecognized type " + opts.type);
  4822. }
  4823. function dif_to_aoa_str(str, opts) {
  4824. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  4825. for (; ri !== records.length; ++ri) {
  4826. if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
  4827. if (R < 0) continue;
  4828. var metadata = records[ri].trim().split(",");
  4829. var type = metadata[0], value = metadata[1];
  4830. ++ri;
  4831. var data = records[ri].trim();
  4832. switch (+type) {
  4833. case -1:
  4834. if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
  4835. else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
  4836. break;
  4837. case 0:
  4838. if(data === 'TRUE') arr[R][C] = true;
  4839. else if(data === 'FALSE') arr[R][C] = false;
  4840. else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
  4841. else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
  4842. else arr[R][C] = value;
  4843. ++C; break;
  4844. case 1:
  4845. data = data.slice(1,data.length-1);
  4846. arr[R][C++] = data !== '' ? data : null;
  4847. break;
  4848. }
  4849. if (data === 'EOD') break;
  4850. }
  4851. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  4852. return arr;
  4853. }
  4854. function dif_to_sheet(str, opts) { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
  4855. function dif_to_workbook(str, opts) { return sheet_to_workbook(dif_to_sheet(str, opts), opts); }
  4856. var sheet_to_dif = (function() {
  4857. var push_field = function pf(o, topic, v, n, s) {
  4858. o.push(topic);
  4859. o.push(v + "," + n);
  4860. o.push('"' + s.replace(/"/g,'""') + '"');
  4861. };
  4862. var push_value = function po(o, type, v, s) {
  4863. o.push(type + "," + v);
  4864. o.push(type == 1 ? '"' + s.replace(/"/g,'""') + '"' : s);
  4865. };
  4866. return function sheet_to_dif(ws) {
  4867. var o = [];
  4868. var r = safe_decode_range(ws['!ref']), cell;
  4869. var dense = Array.isArray(ws);
  4870. push_field(o, "TABLE", 0, 1, "sheetjs");
  4871. push_field(o, "VECTORS", 0, r.e.r - r.s.r + 1,"");
  4872. push_field(o, "TUPLES", 0, r.e.c - r.s.c + 1,"");
  4873. push_field(o, "DATA", 0, 0,"");
  4874. for(var R = r.s.r; R <= r.e.r; ++R) {
  4875. push_value(o, -1, 0, "BOT");
  4876. for(var C = r.s.c; C <= r.e.c; ++C) {
  4877. var coord = encode_cell({r:R,c:C});
  4878. cell = dense ? (ws[R]||[])[C] : ws[coord];
  4879. if(!cell) { push_value(o, 1, 0, ""); continue;}
  4880. switch(cell.t) {
  4881. case 'n':
  4882. var val = DIF_XL ? cell.w : cell.v;
  4883. if(!val && cell.v != null) val = cell.v;
  4884. if(val == null) {
  4885. if(DIF_XL && cell.f && !cell.F) push_value(o, 1, 0, "=" + cell.f);
  4886. else push_value(o, 1, 0, "");
  4887. }
  4888. else push_value(o, 0, val, "V");
  4889. break;
  4890. case 'b':
  4891. push_value(o, 0, cell.v ? 1 : 0, cell.v ? "TRUE" : "FALSE");
  4892. break;
  4893. case 's':
  4894. push_value(o, 1, 0, (!DIF_XL || isNaN(cell.v)) ? cell.v : '="' + cell.v + '"');
  4895. break;
  4896. case 'd':
  4897. if(!cell.w) cell.w = SSF.format(cell.z || SSF._table[14], datenum(parseDate(cell.v)));
  4898. if(DIF_XL) push_value(o, 0, cell.w, "V");
  4899. else push_value(o, 1, 0, cell.w);
  4900. break;
  4901. default: push_value(o, 1, 0, "");
  4902. }
  4903. }
  4904. }
  4905. push_value(o, -1, 0, "EOD");
  4906. var RS = "\r\n";
  4907. var oo = o.join(RS);
  4908. //while((oo.length & 0x7F) != 0) oo += "\0";
  4909. return oo;
  4910. };
  4911. })();
  4912. return {
  4913. to_workbook: dif_to_workbook,
  4914. to_sheet: dif_to_sheet,
  4915. from_sheet: sheet_to_dif
  4916. };
  4917. })();
  4918. var ETH = (function() {
  4919. function decode(s) { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
  4920. function encode(s) { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }
  4921. function eth_to_aoa(str, opts) {
  4922. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  4923. for (; ri !== records.length; ++ri) {
  4924. var record = records[ri].trim().split(":");
  4925. if(record[0] !== 'cell') continue;
  4926. var addr = decode_cell(record[1]);
  4927. if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
  4928. R = addr.r; C = addr.c;
  4929. switch(record[2]) {
  4930. case 't': arr[R][C] = decode(record[3]); break;
  4931. case 'v': arr[R][C] = +record[3]; break;
  4932. case 'vtf': var _f = record[record.length - 1];
  4933. /* falls through */
  4934. case 'vtc':
  4935. switch(record[3]) {
  4936. case 'nl': arr[R][C] = +record[4] ? true : false; break;
  4937. default: arr[R][C] = +record[4]; break;
  4938. }
  4939. if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
  4940. }
  4941. }
  4942. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  4943. return arr;
  4944. }
  4945. function eth_to_sheet(d, opts) { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
  4946. function eth_to_workbook(d, opts) { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }
  4947. var header = [
  4948. "socialcalc:version:1.5",
  4949. "MIME-Version: 1.0",
  4950. "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  4951. ].join("\n");
  4952. var sep = [
  4953. "--SocialCalcSpreadsheetControlSave",
  4954. "Content-type: text/plain; charset=UTF-8"
  4955. ].join("\n") + "\n";
  4956. /* TODO: the other parts */
  4957. var meta = [
  4958. "# SocialCalc Spreadsheet Control Save",
  4959. "part:sheet"
  4960. ].join("\n");
  4961. var end = "--SocialCalcSpreadsheetControlSave--";
  4962. function sheet_to_eth_data(ws) {
  4963. if(!ws || !ws['!ref']) return "";
  4964. var o = [], oo = [], cell, coord = "";
  4965. var r = decode_range(ws['!ref']);
  4966. var dense = Array.isArray(ws);
  4967. for(var R = r.s.r; R <= r.e.r; ++R) {
  4968. for(var C = r.s.c; C <= r.e.c; ++C) {
  4969. coord = encode_cell({r:R,c:C});
  4970. cell = dense ? (ws[R]||[])[C] : ws[coord];
  4971. if(!cell || cell.v == null || cell.t === 'z') continue;
  4972. oo = ["cell", coord, 't'];
  4973. switch(cell.t) {
  4974. case 's': case 'str': oo.push(encode(cell.v)); break;
  4975. case 'n':
  4976. if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
  4977. else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
  4978. break;
  4979. case 'b':
  4980. oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
  4981. oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
  4982. break;
  4983. case 'd':
  4984. var t = datenum(parseDate(cell.v));
  4985. oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
  4986. oo[5] = cell.w || SSF.format(cell.z || SSF._table[14], t);
  4987. break;
  4988. case 'e': continue;
  4989. }
  4990. o.push(oo.join(":"));
  4991. }
  4992. }
  4993. o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
  4994. o.push("valueformat:1:text-wiki");
  4995. //o.push("copiedfrom:" + ws['!ref']); // clipboard only
  4996. return o.join("\n");
  4997. }
  4998. function sheet_to_eth(ws) {
  4999. return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
  5000. // return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
  5001. }
  5002. return {
  5003. to_workbook: eth_to_workbook,
  5004. to_sheet: eth_to_sheet,
  5005. from_sheet: sheet_to_eth
  5006. };
  5007. })();
  5008. var PRN = (function() {
  5009. function set_text_arr(data, arr, R, C, o) {
  5010. if(o.raw) arr[R][C] = data;
  5011. else if(data === 'TRUE') arr[R][C] = true;
  5012. else if(data === 'FALSE') arr[R][C] = false;
  5013. else if(data === ""){/* empty */}
  5014. else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
  5015. else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
  5016. else arr[R][C] = data;
  5017. }
  5018. function prn_to_aoa_str(f, opts) {
  5019. var o = opts || {};
  5020. var arr = ([]);
  5021. if(!f || f.length === 0) return arr;
  5022. var lines = f.split(/[\r\n]/);
  5023. var L = lines.length - 1;
  5024. while(L >= 0 && lines[L].length === 0) --L;
  5025. var start = 10, idx = 0;
  5026. var R = 0;
  5027. for(; R <= L; ++R) {
  5028. idx = lines[R].indexOf(" ");
  5029. if(idx == -1) idx = lines[R].length; else idx++;
  5030. start = Math.max(start, idx);
  5031. }
  5032. for(R = 0; R <= L; ++R) {
  5033. arr[R] = [];
  5034. /* TODO: confirm that widths are always 10 */
  5035. var C = 0;
  5036. set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
  5037. for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
  5038. set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
  5039. }
  5040. if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
  5041. return arr;
  5042. }
  5043. // List of accepted CSV separators
  5044. var guess_seps = {
  5045. 0x2C: ',',
  5046. 0x09: "\t",
  5047. 0x3B: ';'
  5048. };
  5049. // CSV separator weights to be used in case of equal numbers
  5050. var guess_sep_weights = {
  5051. 0x2C: 3,
  5052. 0x09: 2,
  5053. 0x3B: 1
  5054. };
  5055. function guess_sep(str) {
  5056. var cnt = {}, instr = false, end = 0, cc = 0;
  5057. for(;end < str.length;++end) {
  5058. if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
  5059. else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
  5060. }
  5061. cc = [];
  5062. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  5063. cc.push([ cnt[end], end ]);
  5064. }
  5065. if ( !cc.length ) {
  5066. cnt = guess_sep_weights;
  5067. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  5068. cc.push([ cnt[end], end ]);
  5069. }
  5070. }
  5071. cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });
  5072. return guess_seps[cc.pop()[1]];
  5073. }
  5074. function dsv_to_sheet_str(str, opts) {
  5075. var o = opts || {};
  5076. var sep = "";
  5077. if(DENSE != null && o.dense == null) o.dense = DENSE;
  5078. var ws = o.dense ? ([]) : ({});
  5079. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  5080. if(str.slice(0,4) == "sep=") {
  5081. // If the line ends in \r\n
  5082. if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
  5083. sep = str.charAt(4); str = str.slice(7);
  5084. }
  5085. // If line ends in \r OR \n
  5086. else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
  5087. //
  5088. sep = str.charAt(4); str = str.slice(6);
  5089. }
  5090. }
  5091. else sep = guess_sep(str.slice(0,1024));
  5092. var R = 0, C = 0, v = 0;
  5093. var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0;
  5094. str = str.replace(/\r\n/mg, "\n");
  5095. var _re = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
  5096. function finish_cell() {
  5097. var s = str.slice(start, end);
  5098. var cell = ({});
  5099. if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
  5100. if(s.length === 0) cell.t = 'z';
  5101. else if(o.raw) { cell.t = 's'; cell.v = s; }
  5102. else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
  5103. else if(s.charCodeAt(0) == 0x3D) {
  5104. if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
  5105. else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
  5106. else { cell.t = 's'; cell.v = s; } }
  5107. else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
  5108. else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
  5109. else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
  5110. else if(!isNaN(fuzzydate(s).getDate()) || _re && s.match(_re)) {
  5111. cell.z = o.dateNF || SSF._table[14];
  5112. var k = 0;
  5113. if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; }
  5114. if(o.cellDates) { cell.t = 'd'; cell.v = parseDate(s, k); }
  5115. else { cell.t = 'n'; cell.v = datenum(parseDate(s, k)); }
  5116. if(o.cellText !== false) cell.w = SSF.format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
  5117. if(!o.cellNF) delete cell.z;
  5118. } else {
  5119. cell.t = 's';
  5120. cell.v = s;
  5121. }
  5122. if(cell.t == 'z'){}
  5123. else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
  5124. else ws[encode_cell({c:C,r:R})] = cell;
  5125. start = end+1;
  5126. if(range.e.c < C) range.e.c = C;
  5127. if(range.e.r < R) range.e.r = R;
  5128. if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
  5129. }
  5130. outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
  5131. case 0x22: instr = !instr; break;
  5132. case sepcc: case 0x0a: case 0x0d: if(!instr && finish_cell()) break outer; break;
  5133. default: break;
  5134. }
  5135. if(end - start > 0) finish_cell();
  5136. ws['!ref'] = encode_range(range);
  5137. return ws;
  5138. }
  5139. function prn_to_sheet_str(str, opts) {
  5140. if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
  5141. if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
  5142. if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
  5143. return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
  5144. }
  5145. function prn_to_sheet(d, opts) {
  5146. var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
  5147. switch(opts.type) {
  5148. case 'base64': str = Base64.decode(d); break;
  5149. case 'binary': str = d; break;
  5150. case 'buffer':
  5151. if(opts.codepage == 65001) str = d.toString('utf8');
  5152. else if(opts.codepage && typeof cptable !== 'undefined') str = cptable.utils.decode(opts.codepage, d);
  5153. else str = d.toString('binary');
  5154. break;
  5155. case 'array': str = cc2str(d); break;
  5156. case 'string': str = d; break;
  5157. default: throw new Error("Unrecognized type " + opts.type);
  5158. }
  5159. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
  5160. else if((opts.type == 'binary') && typeof cptable !== 'undefined' && opts.codepage) str = cptable.utils.decode(opts.codepage, cptable.utils.encode(1252,str));
  5161. if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
  5162. return prn_to_sheet_str(str, opts);
  5163. }
  5164. function prn_to_workbook(d, opts) { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }
  5165. function sheet_to_prn(ws) {
  5166. var o = [];
  5167. var r = safe_decode_range(ws['!ref']), cell;
  5168. var dense = Array.isArray(ws);
  5169. for(var R = r.s.r; R <= r.e.r; ++R) {
  5170. var oo = [];
  5171. for(var C = r.s.c; C <= r.e.c; ++C) {
  5172. var coord = encode_cell({r:R,c:C});
  5173. cell = dense ? (ws[R]||[])[C] : ws[coord];
  5174. if(!cell || cell.v == null) { oo.push(" "); continue; }
  5175. var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
  5176. while(w.length < 10) w += " ";
  5177. oo.push(w + (C === 0 ? " " : ""));
  5178. }
  5179. o.push(oo.join(""));
  5180. }
  5181. return o.join("\n");
  5182. }
  5183. return {
  5184. to_workbook: prn_to_workbook,
  5185. to_sheet: prn_to_sheet,
  5186. from_sheet: sheet_to_prn
  5187. };
  5188. })();
  5189. /* Excel defaults to SYLK but warns if data is not valid */
  5190. function read_wb_ID(d, opts) {
  5191. var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
  5192. try {
  5193. var out = SYLK.to_workbook(d, o);
  5194. o.WTF = OLD_WTF;
  5195. return out;
  5196. } catch(e) {
  5197. o.WTF = OLD_WTF;
  5198. if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
  5199. return PRN.to_workbook(d, opts);
  5200. }
  5201. }
  5202. /* 18.4.7 rPr CT_RPrElt */
  5203. function parse_rpr(rpr) {
  5204. var font = {}, m = rpr.match(tagregex), i = 0;
  5205. var pass = false;
  5206. if(m) for(;i!=m.length; ++i) {
  5207. var y = parsexmltag(m[i]);
  5208. switch(y[0].replace(/\w*:/g,"")) {
  5209. /* 18.8.12 condense CT_BooleanProperty */
  5210. /* ** not required . */
  5211. case '<condense': break;
  5212. /* 18.8.17 extend CT_BooleanProperty */
  5213. /* ** not required . */
  5214. case '<extend': break;
  5215. /* 18.8.36 shadow CT_BooleanProperty */
  5216. /* ** not required . */
  5217. case '<shadow':
  5218. if(!y.val) break;
  5219. /* falls through */
  5220. case '<shadow>':
  5221. case '<shadow/>': font.shadow = 1; break;
  5222. case '</shadow>': break;
  5223. /* 18.4.1 charset CT_IntProperty TODO */
  5224. case '<charset':
  5225. if(y.val == '1') break;
  5226. font.cp = CS2CP[parseInt(y.val, 10)];
  5227. break;
  5228. /* 18.4.2 outline CT_BooleanProperty TODO */
  5229. case '<outline':
  5230. if(!y.val) break;
  5231. /* falls through */
  5232. case '<outline>':
  5233. case '<outline/>': font.outline = 1; break;
  5234. case '</outline>': break;
  5235. /* 18.4.5 rFont CT_FontName */
  5236. case '<rFont': font.name = y.val; break;
  5237. /* 18.4.11 sz CT_FontSize */
  5238. case '<sz': font.sz = y.val; break;
  5239. /* 18.4.10 strike CT_BooleanProperty */
  5240. case '<strike':
  5241. if(!y.val) break;
  5242. /* falls through */
  5243. case '<strike>':
  5244. case '<strike/>': font.strike = 1; break;
  5245. case '</strike>': break;
  5246. /* 18.4.13 u CT_UnderlineProperty */
  5247. case '<u':
  5248. if(!y.val) break;
  5249. switch(y.val) {
  5250. case 'double': font.uval = "double"; break;
  5251. case 'singleAccounting': font.uval = "single-accounting"; break;
  5252. case 'doubleAccounting': font.uval = "double-accounting"; break;
  5253. }
  5254. /* falls through */
  5255. case '<u>':
  5256. case '<u/>': font.u = 1; break;
  5257. case '</u>': break;
  5258. /* 18.8.2 b */
  5259. case '<b':
  5260. if(y.val == '0') break;
  5261. /* falls through */
  5262. case '<b>':
  5263. case '<b/>': font.b = 1; break;
  5264. case '</b>': break;
  5265. /* 18.8.26 i */
  5266. case '<i':
  5267. if(y.val == '0') break;
  5268. /* falls through */
  5269. case '<i>':
  5270. case '<i/>': font.i = 1; break;
  5271. case '</i>': break;
  5272. /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
  5273. case '<color':
  5274. if(y.rgb) font.color = y.rgb.slice(2,8);
  5275. break;
  5276. /* 18.8.18 family ST_FontFamily */
  5277. case '<family': font.family = y.val; break;
  5278. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
  5279. case '<vertAlign': font.valign = y.val; break;
  5280. /* 18.8.35 scheme CT_FontScheme TODO */
  5281. case '<scheme': break;
  5282. /* 18.2.10 extLst CT_ExtensionList ? */
  5283. case '<extLst': case '<extLst>': case '</extLst>': break;
  5284. case '<ext': pass = true; break;
  5285. case '</ext>': pass = false; break;
  5286. default:
  5287. if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
  5288. }
  5289. }
  5290. return font;
  5291. }
  5292. var parse_rs = (function() {
  5293. var tregex = matchtag("t"), rpregex = matchtag("rPr");
  5294. /* 18.4.4 r CT_RElt */
  5295. function parse_r(r) {
  5296. /* 18.4.12 t ST_Xstring */
  5297. var t = r.match(tregex)/*, cp = 65001*/;
  5298. if(!t) return {t:"s", v:""};
  5299. var o = ({t:'s', v:unescapexml(t[1])});
  5300. var rpr = r.match(rpregex);
  5301. if(rpr) o.s = parse_rpr(rpr[1]);
  5302. return o;
  5303. }
  5304. var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  5305. return function parse_rs(rs) {
  5306. return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
  5307. };
  5308. })();
  5309. /* Parse a list of <r> tags */
  5310. var rs_to_html = (function parse_rs_factory() {
  5311. var nlregex = /(\r\n|\n)/g;
  5312. function parse_rpr2(font, intro, outro) {
  5313. var style = [];
  5314. if(font.u) style.push("text-decoration: underline;");
  5315. if(font.uval) style.push("text-underline-style:" + font.uval + ";");
  5316. if(font.sz) style.push("font-size:" + font.sz + "pt;");
  5317. if(font.outline) style.push("text-effect: outline;");
  5318. if(font.shadow) style.push("text-shadow: auto;");
  5319. intro.push('<span style="' + style.join("") + '">');
  5320. if(font.b) { intro.push("<b>"); outro.push("</b>"); }
  5321. if(font.i) { intro.push("<i>"); outro.push("</i>"); }
  5322. if(font.strike) { intro.push("<s>"); outro.push("</s>"); }
  5323. var align = font.valign || "";
  5324. if(align == "superscript" || align == "super") align = "sup";
  5325. else if(align == "subscript") align = "sub";
  5326. if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }
  5327. outro.push("</span>");
  5328. return font;
  5329. }
  5330. /* 18.4.4 r CT_RElt */
  5331. function r_to_html(r) {
  5332. var terms = [[],r.v,[]];
  5333. if(!r.v) return "";
  5334. if(r.s) parse_rpr2(r.s, terms[0], terms[2]);
  5335. return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
  5336. }
  5337. return function parse_rs(rs) {
  5338. return rs.map(r_to_html).join("");
  5339. };
  5340. })();
  5341. /* 18.4.8 si CT_Rst */
  5342. var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
  5343. var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
  5344. function parse_si(x, opts) {
  5345. var html = opts ? opts.cellHTML : true;
  5346. var z = {};
  5347. if(!x) return { t: "" };
  5348. //var y;
  5349. /* 18.4.12 t ST_Xstring (Plaintext String) */
  5350. // TODO: is whitespace actually valid here?
  5351. if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
  5352. z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""));
  5353. z.r = utf8read(x);
  5354. if(html) z.h = escapehtml(z.t);
  5355. }
  5356. /* 18.4.4 r CT_RElt (Rich Text Run) */
  5357. else if((/*y = */x.match(sirregex))) {
  5358. z.r = utf8read(x);
  5359. z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")));
  5360. if(html) z.h = rs_to_html(parse_rs(z.r));
  5361. }
  5362. /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
  5363. /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
  5364. return z;
  5365. }
  5366. /* 18.4 Shared String Table */
  5367. var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
  5368. var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
  5369. var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
  5370. function parse_sst_xml(data, opts) {
  5371. var s = ([]), ss = "";
  5372. if(!data) return s;
  5373. /* 18.4.9 sst CT_Sst */
  5374. var sst = data.match(sstr0);
  5375. if(sst) {
  5376. ss = sst[2].replace(sstr1,"").split(sstr2);
  5377. for(var i = 0; i != ss.length; ++i) {
  5378. var o = parse_si(ss[i].trim(), opts);
  5379. if(o != null) s[s.length] = o;
  5380. }
  5381. sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
  5382. }
  5383. return s;
  5384. }
  5385. RELS.SST = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
  5386. var straywsregex = /^\s|\s$|[\t\n\r]/;
  5387. function write_sst_xml(sst, opts) {
  5388. if(!opts.bookSST) return "";
  5389. var o = [XML_HEADER];
  5390. o[o.length] = (writextag('sst', null, {
  5391. xmlns: XMLNS.main[0],
  5392. count: sst.Count,
  5393. uniqueCount: sst.Unique
  5394. }));
  5395. for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
  5396. var s = sst[i];
  5397. var sitag = "<si>";
  5398. if(s.r) sitag += s.r;
  5399. else {
  5400. sitag += "<t";
  5401. if(!s.t) s.t = "";
  5402. if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
  5403. sitag += ">" + escapexml(s.t) + "</t>";
  5404. }
  5405. sitag += "</si>";
  5406. o[o.length] = (sitag);
  5407. }
  5408. if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
  5409. return o.join("");
  5410. }
  5411. function hex2RGB(h) {
  5412. var o = h.slice(h[0]==="#"?1:0).slice(0,6);
  5413. return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
  5414. }
  5415. function rgb2Hex(rgb) {
  5416. for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
  5417. return o.toString(16).toUpperCase().slice(1);
  5418. }
  5419. function rgb2HSL(rgb) {
  5420. var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
  5421. var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
  5422. if(C === 0) return [0, 0, R];
  5423. var H6 = 0, S = 0, L2 = (M + m);
  5424. S = C / (L2 > 1 ? 2 - L2 : L2);
  5425. switch(M){
  5426. case R: H6 = ((G - B) / C + 6)%6; break;
  5427. case G: H6 = ((B - R) / C + 2); break;
  5428. case B: H6 = ((R - G) / C + 4); break;
  5429. }
  5430. return [H6 / 6, S, L2 / 2];
  5431. }
  5432. function hsl2RGB(hsl){
  5433. var H = hsl[0], S = hsl[1], L = hsl[2];
  5434. var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
  5435. var rgb = [m,m,m], h6 = 6*H;
  5436. var X;
  5437. if(S !== 0) switch(h6|0) {
  5438. case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
  5439. case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
  5440. case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
  5441. case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
  5442. case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
  5443. case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
  5444. }
  5445. for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
  5446. return rgb;
  5447. }
  5448. /* 18.8.3 bgColor tint algorithm */
  5449. function rgb_tint(hex, tint) {
  5450. if(tint === 0) return hex;
  5451. var hsl = rgb2HSL(hex2RGB(hex));
  5452. if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  5453. else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  5454. return rgb2Hex(hsl2RGB(hsl));
  5455. }
  5456. /* 18.3.1.13 width calculations */
  5457. /* [MS-OI29500] 2.1.595 Column Width & Formatting */
  5458. var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
  5459. function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
  5460. function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
  5461. function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
  5462. //function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
  5463. //function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
  5464. function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
  5465. /* XLSX/XLSB/XLS specify width in units of MDW */
  5466. function find_mdw_colw(collw) {
  5467. var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  5468. 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; }
  5469. MDW = _MDW;
  5470. }
  5471. /* XLML specifies width in terms of pixels */
  5472. /*function find_mdw_wpx(wpx) {
  5473. var delta = Infinity, guess = 0, _MDW = MIN_MDW;
  5474. for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
  5475. guess = char2width_(px2char_(wpx))*256;
  5476. guess = (guess) % 1;
  5477. if(guess > 0.5) guess--;
  5478. if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
  5479. }
  5480. MDW = _MDW;
  5481. }*/
  5482. function process_col(coll) {
  5483. if(coll.width) {
  5484. coll.wpx = width2px(coll.width);
  5485. coll.wch = px2char(coll.wpx);
  5486. coll.MDW = MDW;
  5487. } else if(coll.wpx) {
  5488. coll.wch = px2char(coll.wpx);
  5489. coll.width = char2width(coll.wch);
  5490. coll.MDW = MDW;
  5491. } else if(typeof coll.wch == 'number') {
  5492. coll.width = char2width(coll.wch);
  5493. coll.wpx = width2px(coll.width);
  5494. coll.MDW = MDW;
  5495. }
  5496. if(coll.customWidth) delete coll.customWidth;
  5497. }
  5498. var DEF_PPI = 96, PPI = DEF_PPI;
  5499. function px2pt(px) { return px * 96 / PPI; }
  5500. function pt2px(pt) { return pt * PPI / 96; }
  5501. /* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
  5502. var XLMLPatternTypeMap = {
  5503. "None": "none",
  5504. "Solid": "solid",
  5505. "Gray50": "mediumGray",
  5506. "Gray75": "darkGray",
  5507. "Gray25": "lightGray",
  5508. "HorzStripe": "darkHorizontal",
  5509. "VertStripe": "darkVertical",
  5510. "ReverseDiagStripe": "darkDown",
  5511. "DiagStripe": "darkUp",
  5512. "DiagCross": "darkGrid",
  5513. "ThickDiagCross": "darkTrellis",
  5514. "ThinHorzStripe": "lightHorizontal",
  5515. "ThinVertStripe": "lightVertical",
  5516. "ThinReverseDiagStripe": "lightDown",
  5517. "ThinHorzCross": "lightGrid"
  5518. };
  5519. /* 18.8.5 borders CT_Borders */
  5520. function parse_borders(t, styles, themes, opts) {
  5521. styles.Borders = [];
  5522. var border = {};
  5523. var pass = false;
  5524. (t[0].match(tagregex)||[]).forEach(function(x) {
  5525. var y = parsexmltag(x);
  5526. switch(strip_ns(y[0])) {
  5527. case '<borders': case '<borders>': case '</borders>': break;
  5528. /* 18.8.4 border CT_Border */
  5529. case '<border': case '<border>': case '<border/>':
  5530. border = {};
  5531. if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
  5532. if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
  5533. styles.Borders.push(border);
  5534. break;
  5535. case '</border>': break;
  5536. /* note: not in spec, appears to be CT_BorderPr */
  5537. case '<left/>': break;
  5538. case '<left': case '<left>': break;
  5539. case '</left>': break;
  5540. /* note: not in spec, appears to be CT_BorderPr */
  5541. case '<right/>': break;
  5542. case '<right': case '<right>': break;
  5543. case '</right>': break;
  5544. /* 18.8.43 top CT_BorderPr */
  5545. case '<top/>': break;
  5546. case '<top': case '<top>': break;
  5547. case '</top>': break;
  5548. /* 18.8.6 bottom CT_BorderPr */
  5549. case '<bottom/>': break;
  5550. case '<bottom': case '<bottom>': break;
  5551. case '</bottom>': break;
  5552. /* 18.8.13 diagonal CT_BorderPr */
  5553. case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
  5554. case '</diagonal>': break;
  5555. /* 18.8.25 horizontal CT_BorderPr */
  5556. case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
  5557. case '</horizontal>': break;
  5558. /* 18.8.44 vertical CT_BorderPr */
  5559. case '<vertical': case '<vertical>': case '<vertical/>': break;
  5560. case '</vertical>': break;
  5561. /* 18.8.37 start CT_BorderPr */
  5562. case '<start': case '<start>': case '<start/>': break;
  5563. case '</start>': break;
  5564. /* 18.8.16 end CT_BorderPr */
  5565. case '<end': case '<end>': case '<end/>': break;
  5566. case '</end>': break;
  5567. /* 18.8.? color CT_Color */
  5568. case '<color': case '<color>':
  5569. break;
  5570. case '<color/>': case '</color>': break;
  5571. /* 18.2.10 extLst CT_ExtensionList ? */
  5572. case '<extLst': case '<extLst>': case '</extLst>': break;
  5573. case '<ext': pass = true; break;
  5574. case '</ext>': pass = false; break;
  5575. default: if(opts && opts.WTF) {
  5576. if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
  5577. }
  5578. }
  5579. });
  5580. }
  5581. /* 18.8.21 fills CT_Fills */
  5582. function parse_fills(t, styles, themes, opts) {
  5583. styles.Fills = [];
  5584. var fill = {};
  5585. var pass = false;
  5586. (t[0].match(tagregex)||[]).forEach(function(x) {
  5587. var y = parsexmltag(x);
  5588. switch(strip_ns(y[0])) {
  5589. case '<fills': case '<fills>': case '</fills>': break;
  5590. /* 18.8.20 fill CT_Fill */
  5591. case '<fill>': case '<fill': case '<fill/>':
  5592. fill = {}; styles.Fills.push(fill); break;
  5593. case '</fill>': break;
  5594. /* 18.8.24 gradientFill CT_GradientFill */
  5595. case '<gradientFill>': break;
  5596. case '<gradientFill':
  5597. case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;
  5598. /* 18.8.32 patternFill CT_PatternFill */
  5599. case '<patternFill': case '<patternFill>':
  5600. if(y.patternType) fill.patternType = y.patternType;
  5601. break;
  5602. case '<patternFill/>': case '</patternFill>': break;
  5603. /* 18.8.3 bgColor CT_Color */
  5604. case '<bgColor':
  5605. if(!fill.bgColor) fill.bgColor = {};
  5606. if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
  5607. if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
  5608. if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
  5609. /* Excel uses ARGB strings */
  5610. if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
  5611. break;
  5612. case '<bgColor/>': case '</bgColor>': break;
  5613. /* 18.8.19 fgColor CT_Color */
  5614. case '<fgColor':
  5615. if(!fill.fgColor) fill.fgColor = {};
  5616. if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
  5617. if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
  5618. /* Excel uses ARGB strings */
  5619. if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
  5620. break;
  5621. case '<fgColor/>': case '</fgColor>': break;
  5622. /* 18.8.38 stop CT_GradientStop */
  5623. case '<stop': case '<stop/>': break;
  5624. case '</stop>': break;
  5625. /* 18.8.? color CT_Color */
  5626. case '<color': case '<color/>': break;
  5627. case '</color>': break;
  5628. /* 18.2.10 extLst CT_ExtensionList ? */
  5629. case '<extLst': case '<extLst>': case '</extLst>': break;
  5630. case '<ext': pass = true; break;
  5631. case '</ext>': pass = false; break;
  5632. default: if(opts && opts.WTF) {
  5633. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
  5634. }
  5635. }
  5636. });
  5637. }
  5638. /* 18.8.23 fonts CT_Fonts */
  5639. function parse_fonts(t, styles, themes, opts) {
  5640. styles.Fonts = [];
  5641. var font = {};
  5642. var pass = false;
  5643. (t[0].match(tagregex)||[]).forEach(function(x) {
  5644. var y = parsexmltag(x);
  5645. switch(strip_ns(y[0])) {
  5646. case '<fonts': case '<fonts>': case '</fonts>': break;
  5647. /* 18.8.22 font CT_Font */
  5648. case '<font': case '<font>': break;
  5649. case '</font>': case '<font/>':
  5650. styles.Fonts.push(font);
  5651. font = {};
  5652. break;
  5653. /* 18.8.29 name CT_FontName */
  5654. case '<name': if(y.val) font.name = utf8read(y.val); break;
  5655. case '<name/>': case '</name>': break;
  5656. /* 18.8.2 b CT_BooleanProperty */
  5657. case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
  5658. case '<b/>': font.bold = 1; break;
  5659. /* 18.8.26 i CT_BooleanProperty */
  5660. case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
  5661. case '<i/>': font.italic = 1; break;
  5662. /* 18.4.13 u CT_UnderlineProperty */
  5663. case '<u':
  5664. switch(y.val) {
  5665. case "none": font.underline = 0x00; break;
  5666. case "single": font.underline = 0x01; break;
  5667. case "double": font.underline = 0x02; break;
  5668. case "singleAccounting": font.underline = 0x21; break;
  5669. case "doubleAccounting": font.underline = 0x22; break;
  5670. } break;
  5671. case '<u/>': font.underline = 1; break;
  5672. /* 18.4.10 strike CT_BooleanProperty */
  5673. case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
  5674. case '<strike/>': font.strike = 1; break;
  5675. /* 18.4.2 outline CT_BooleanProperty */
  5676. case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
  5677. case '<outline/>': font.outline = 1; break;
  5678. /* 18.8.36 shadow CT_BooleanProperty */
  5679. case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
  5680. case '<shadow/>': font.shadow = 1; break;
  5681. /* 18.8.12 condense CT_BooleanProperty */
  5682. case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
  5683. case '<condense/>': font.condense = 1; break;
  5684. /* 18.8.17 extend CT_BooleanProperty */
  5685. case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
  5686. case '<extend/>': font.extend = 1; break;
  5687. /* 18.4.11 sz CT_FontSize */
  5688. case '<sz': if(y.val) font.sz = +y.val; break;
  5689. case '<sz/>': case '</sz>': break;
  5690. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
  5691. case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
  5692. case '<vertAlign/>': case '</vertAlign>': break;
  5693. /* 18.8.18 family CT_FontFamily */
  5694. case '<family': if(y.val) font.family = parseInt(y.val,10); break;
  5695. case '<family/>': case '</family>': break;
  5696. /* 18.8.35 scheme CT_FontScheme */
  5697. case '<scheme': if(y.val) font.scheme = y.val; break;
  5698. case '<scheme/>': case '</scheme>': break;
  5699. /* 18.4.1 charset CT_IntProperty */
  5700. case '<charset':
  5701. if(y.val == '1') break;
  5702. y.codepage = CS2CP[parseInt(y.val, 10)];
  5703. break;
  5704. /* 18.?.? color CT_Color */
  5705. case '<color':
  5706. if(!font.color) font.color = {};
  5707. if(y.auto) font.color.auto = parsexmlbool(y.auto);
  5708. if(y.rgb) font.color.rgb = y.rgb.slice(-6);
  5709. else if(y.indexed) {
  5710. font.color.index = parseInt(y.indexed, 10);
  5711. var icv = XLSIcv[font.color.index];
  5712. if(font.color.index == 81) icv = XLSIcv[1];
  5713. if(!icv) throw new Error(x);
  5714. font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
  5715. } else if(y.theme) {
  5716. font.color.theme = parseInt(y.theme, 10);
  5717. if(y.tint) font.color.tint = parseFloat(y.tint);
  5718. if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
  5719. font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
  5720. }
  5721. }
  5722. break;
  5723. case '<color/>': case '</color>': break;
  5724. /* note: sometimes mc:AlternateContent appears bare */
  5725. case '<AlternateContent': pass = true; break;
  5726. case '</AlternateContent>': pass = false; break;
  5727. /* 18.2.10 extLst CT_ExtensionList ? */
  5728. case '<extLst': case '<extLst>': case '</extLst>': break;
  5729. case '<ext': pass = true; break;
  5730. case '</ext>': pass = false; break;
  5731. default: if(opts && opts.WTF) {
  5732. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
  5733. }
  5734. }
  5735. });
  5736. }
  5737. /* 18.8.31 numFmts CT_NumFmts */
  5738. function parse_numFmts(t, styles, opts) {
  5739. styles.NumberFmt = [];
  5740. var k/*Array<number>*/ = (keys(SSF._table));
  5741. for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = SSF._table[k[i]];
  5742. var m = t[0].match(tagregex);
  5743. if(!m) return;
  5744. for(i=0; i < m.length; ++i) {
  5745. var y = parsexmltag(m[i]);
  5746. switch(strip_ns(y[0])) {
  5747. case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
  5748. case '<numFmt': {
  5749. var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
  5750. styles.NumberFmt[j] = f;
  5751. if(j>0) {
  5752. if(j > 0x188) {
  5753. for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
  5754. styles.NumberFmt[j] = f;
  5755. }
  5756. SSF.load(f,j);
  5757. }
  5758. } break;
  5759. case '</numFmt>': break;
  5760. default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
  5761. }
  5762. }
  5763. }
  5764. function write_numFmts(NF) {
  5765. var o = ["<numFmts>"];
  5766. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  5767. 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])}));
  5768. });
  5769. if(o.length === 1) return "";
  5770. o[o.length] = ("</numFmts>");
  5771. o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
  5772. return o.join("");
  5773. }
  5774. /* 18.8.10 cellXfs CT_CellXfs */
  5775. var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
  5776. var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
  5777. function parse_cellXfs(t, styles, opts) {
  5778. styles.CellXf = [];
  5779. var xf;
  5780. var pass = false;
  5781. (t[0].match(tagregex)||[]).forEach(function(x) {
  5782. var y = parsexmltag(x), i = 0;
  5783. switch(strip_ns(y[0])) {
  5784. case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
  5785. /* 18.8.45 xf CT_Xf */
  5786. case '<xf': case '<xf/>':
  5787. xf = y;
  5788. delete xf[0];
  5789. for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
  5790. xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
  5791. for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
  5792. xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
  5793. if(xf.numFmtId > 0x188) {
  5794. for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
  5795. }
  5796. styles.CellXf.push(xf); break;
  5797. case '</xf>': break;
  5798. /* 18.8.1 alignment CT_CellAlignment */
  5799. case '<alignment': case '<alignment/>':
  5800. var alignment = {};
  5801. if(y.vertical) alignment.vertical = y.vertical;
  5802. if(y.horizontal) alignment.horizontal = y.horizontal;
  5803. if(y.textRotation != null) alignment.textRotation = y.textRotation;
  5804. if(y.indent) alignment.indent = y.indent;
  5805. if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
  5806. xf.alignment = alignment;
  5807. break;
  5808. case '</alignment>': break;
  5809. /* 18.8.33 protection CT_CellProtection */
  5810. case '<protection':
  5811. break;
  5812. case '</protection>': case '<protection/>': break;
  5813. /* note: sometimes mc:AlternateContent appears bare */
  5814. case '<AlternateContent': pass = true; break;
  5815. case '</AlternateContent>': pass = false; break;
  5816. /* 18.2.10 extLst CT_ExtensionList ? */
  5817. case '<extLst': case '<extLst>': case '</extLst>': break;
  5818. case '<ext': pass = true; break;
  5819. case '</ext>': pass = false; break;
  5820. default: if(opts && opts.WTF) {
  5821. if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
  5822. }
  5823. }
  5824. });
  5825. }
  5826. function write_cellXfs(cellXfs) {
  5827. var o = [];
  5828. o[o.length] = (writextag('cellXfs',null));
  5829. cellXfs.forEach(function(c) {
  5830. o[o.length] = (writextag('xf', null, c));
  5831. });
  5832. o[o.length] = ("</cellXfs>");
  5833. if(o.length === 2) return "";
  5834. o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
  5835. return o.join("");
  5836. }
  5837. /* 18.8 Styles CT_Stylesheet*/
  5838. var parse_sty_xml= (function make_pstyx() {
  5839. var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
  5840. var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
  5841. var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
  5842. var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
  5843. var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;
  5844. return function parse_sty_xml(data, themes, opts) {
  5845. var styles = {};
  5846. if(!data) return styles;
  5847. data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  5848. /* 18.8.39 styleSheet CT_Stylesheet */
  5849. var t;
  5850. /* 18.8.31 numFmts CT_NumFmts ? */
  5851. if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);
  5852. /* 18.8.23 fonts CT_Fonts ? */
  5853. if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);
  5854. /* 18.8.21 fills CT_Fills ? */
  5855. if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);
  5856. /* 18.8.5 borders CT_Borders ? */
  5857. if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);
  5858. /* 18.8.9 cellStyleXfs CT_CellStyleXfs ? */
  5859. /* 18.8.8 cellStyles CT_CellStyles ? */
  5860. /* 18.8.10 cellXfs CT_CellXfs ? */
  5861. if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);
  5862. /* 18.8.15 dxfs CT_Dxfs ? */
  5863. /* 18.8.42 tableStyles CT_TableStyles ? */
  5864. /* 18.8.11 colors CT_Colors ? */
  5865. /* 18.2.10 extLst CT_ExtensionList ? */
  5866. return styles;
  5867. };
  5868. })();
  5869. var STYLES_XML_ROOT = writextag('styleSheet', null, {
  5870. 'xmlns': XMLNS.main[0],
  5871. 'xmlns:vt': XMLNS.vt
  5872. });
  5873. RELS.STY = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
  5874. function write_sty_xml(wb, opts) {
  5875. var o = [XML_HEADER, STYLES_XML_ROOT], w;
  5876. if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
  5877. o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
  5878. o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  5879. o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
  5880. o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
  5881. if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
  5882. o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
  5883. o[o.length] = ('<dxfs count="0"/>');
  5884. o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
  5885. if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
  5886. return o.join("");
  5887. }
  5888. RELS.THEME = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
  5889. /* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
  5890. var XLSXThemeClrScheme = [
  5891. '</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
  5892. '</a:accent1>', '</a:accent2>', '</a:accent3>',
  5893. '</a:accent4>', '</a:accent5>', '</a:accent6>',
  5894. '</a:hlink>', '</a:folHlink>'
  5895. ];
  5896. /* 20.1.6.2 clrScheme CT_ColorScheme */
  5897. function parse_clrScheme(t, themes, opts) {
  5898. themes.themeElements.clrScheme = [];
  5899. var color = {};
  5900. (t[0].match(tagregex)||[]).forEach(function(x) {
  5901. var y = parsexmltag(x);
  5902. switch(y[0]) {
  5903. /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
  5904. case '<a:clrScheme': case '</a:clrScheme>': break;
  5905. /* 20.1.2.3.32 srgbClr CT_SRgbColor */
  5906. case '<a:srgbClr':
  5907. color.rgb = y.val; break;
  5908. /* 20.1.2.3.33 sysClr CT_SystemColor */
  5909. case '<a:sysClr':
  5910. color.rgb = y.lastClr; break;
  5911. /* 20.1.4.1.1 accent1 (Accent 1) */
  5912. /* 20.1.4.1.2 accent2 (Accent 2) */
  5913. /* 20.1.4.1.3 accent3 (Accent 3) */
  5914. /* 20.1.4.1.4 accent4 (Accent 4) */
  5915. /* 20.1.4.1.5 accent5 (Accent 5) */
  5916. /* 20.1.4.1.6 accent6 (Accent 6) */
  5917. /* 20.1.4.1.9 dk1 (Dark 1) */
  5918. /* 20.1.4.1.10 dk2 (Dark 2) */
  5919. /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
  5920. /* 20.1.4.1.19 hlink (Hyperlink) */
  5921. /* 20.1.4.1.22 lt1 (Light 1) */
  5922. /* 20.1.4.1.23 lt2 (Light 2) */
  5923. case '<a:dk1>': case '</a:dk1>':
  5924. case '<a:lt1>': case '</a:lt1>':
  5925. case '<a:dk2>': case '</a:dk2>':
  5926. case '<a:lt2>': case '</a:lt2>':
  5927. case '<a:accent1>': case '</a:accent1>':
  5928. case '<a:accent2>': case '</a:accent2>':
  5929. case '<a:accent3>': case '</a:accent3>':
  5930. case '<a:accent4>': case '</a:accent4>':
  5931. case '<a:accent5>': case '</a:accent5>':
  5932. case '<a:accent6>': case '</a:accent6>':
  5933. case '<a:hlink>': case '</a:hlink>':
  5934. case '<a:folHlink>': case '</a:folHlink>':
  5935. if (y[0].charAt(1) === '/') {
  5936. themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
  5937. color = {};
  5938. } else {
  5939. color.name = y[0].slice(3, y[0].length - 1);
  5940. }
  5941. break;
  5942. default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
  5943. }
  5944. });
  5945. }
  5946. /* 20.1.4.1.18 fontScheme CT_FontScheme */
  5947. function parse_fontScheme() { }
  5948. /* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
  5949. function parse_fmtScheme() { }
  5950. var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
  5951. var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
  5952. var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;
  5953. /* 20.1.6.10 themeElements CT_BaseStyles */
  5954. function parse_themeElements(data, themes, opts) {
  5955. themes.themeElements = {};
  5956. var t;
  5957. [
  5958. /* clrScheme CT_ColorScheme */
  5959. ['clrScheme', clrsregex, parse_clrScheme],
  5960. /* fontScheme CT_FontScheme */
  5961. ['fontScheme', fntsregex, parse_fontScheme],
  5962. /* fmtScheme CT_StyleMatrix */
  5963. ['fmtScheme', fmtsregex, parse_fmtScheme]
  5964. ].forEach(function(m) {
  5965. if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
  5966. m[2](t, themes, opts);
  5967. });
  5968. }
  5969. var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;
  5970. /* 14.2.7 Theme Part */
  5971. function parse_theme_xml(data, opts) {
  5972. /* 20.1.6.9 theme CT_OfficeStyleSheet */
  5973. if(!data || data.length === 0) return parse_theme_xml(write_theme());
  5974. var t;
  5975. var themes = {};
  5976. /* themeElements CT_BaseStyles */
  5977. if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
  5978. parse_themeElements(t[0], themes, opts);
  5979. themes.raw = data;
  5980. return themes;
  5981. }
  5982. function write_theme(Themes, opts) {
  5983. if(opts && opts.themeXLSX) return opts.themeXLSX;
  5984. if(Themes && typeof Themes.raw == "string") return Themes.raw;
  5985. var o = [XML_HEADER];
  5986. o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  5987. o[o.length] = '<a:themeElements>';
  5988. o[o.length] = '<a:clrScheme name="Office">';
  5989. o[o.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  5990. o[o.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  5991. o[o.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  5992. o[o.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  5993. o[o.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  5994. o[o.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  5995. o[o.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  5996. o[o.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  5997. o[o.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  5998. o[o.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  5999. o[o.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  6000. o[o.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  6001. o[o.length] = '</a:clrScheme>';
  6002. o[o.length] = '<a:fontScheme name="Office">';
  6003. o[o.length] = '<a:majorFont>';
  6004. o[o.length] = '<a:latin typeface="Cambria"/>';
  6005. o[o.length] = '<a:ea typeface=""/>';
  6006. o[o.length] = '<a:cs typeface=""/>';
  6007. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  6008. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  6009. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  6010. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  6011. o[o.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  6012. o[o.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  6013. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  6014. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  6015. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  6016. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  6017. o[o.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  6018. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  6019. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  6020. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  6021. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  6022. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  6023. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  6024. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  6025. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  6026. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  6027. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  6028. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  6029. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  6030. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  6031. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  6032. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  6033. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  6034. o[o.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  6035. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  6036. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  6037. o[o.length] = '</a:majorFont>';
  6038. o[o.length] = '<a:minorFont>';
  6039. o[o.length] = '<a:latin typeface="Calibri"/>';
  6040. o[o.length] = '<a:ea typeface=""/>';
  6041. o[o.length] = '<a:cs typeface=""/>';
  6042. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  6043. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  6044. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  6045. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  6046. o[o.length] = '<a:font script="Arab" typeface="Arial"/>';
  6047. o[o.length] = '<a:font script="Hebr" typeface="Arial"/>';
  6048. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  6049. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  6050. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  6051. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  6052. o[o.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  6053. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  6054. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  6055. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  6056. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  6057. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  6058. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  6059. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  6060. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  6061. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  6062. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  6063. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  6064. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  6065. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  6066. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  6067. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  6068. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  6069. o[o.length] = '<a:font script="Viet" typeface="Arial"/>';
  6070. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  6071. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  6072. o[o.length] = '</a:minorFont>';
  6073. o[o.length] = '</a:fontScheme>';
  6074. o[o.length] = '<a:fmtScheme name="Office">';
  6075. o[o.length] = '<a:fillStyleLst>';
  6076. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  6077. o[o.length] = '<a:gradFill rotWithShape="1">';
  6078. o[o.length] = '<a:gsLst>';
  6079. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  6080. o[o.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  6081. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  6082. o[o.length] = '</a:gsLst>';
  6083. o[o.length] = '<a:lin ang="16200000" scaled="1"/>';
  6084. o[o.length] = '</a:gradFill>';
  6085. o[o.length] = '<a:gradFill rotWithShape="1">';
  6086. o[o.length] = '<a:gsLst>';
  6087. 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>';
  6088. 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>';
  6089. o[o.length] = '</a:gsLst>';
  6090. o[o.length] = '<a:lin ang="16200000" scaled="0"/>';
  6091. o[o.length] = '</a:gradFill>';
  6092. o[o.length] = '</a:fillStyleLst>';
  6093. o[o.length] = '<a:lnStyleLst>';
  6094. 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>';
  6095. 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>';
  6096. 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>';
  6097. o[o.length] = '</a:lnStyleLst>';
  6098. o[o.length] = '<a:effectStyleLst>';
  6099. o[o.length] = '<a:effectStyle>';
  6100. o[o.length] = '<a:effectLst>';
  6101. 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>';
  6102. o[o.length] = '</a:effectLst>';
  6103. o[o.length] = '</a:effectStyle>';
  6104. o[o.length] = '<a:effectStyle>';
  6105. o[o.length] = '<a:effectLst>';
  6106. 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>';
  6107. o[o.length] = '</a:effectLst>';
  6108. o[o.length] = '</a:effectStyle>';
  6109. o[o.length] = '<a:effectStyle>';
  6110. o[o.length] = '<a:effectLst>';
  6111. 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>';
  6112. o[o.length] = '</a:effectLst>';
  6113. 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>';
  6114. o[o.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  6115. o[o.length] = '</a:effectStyle>';
  6116. o[o.length] = '</a:effectStyleLst>';
  6117. o[o.length] = '<a:bgFillStyleLst>';
  6118. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  6119. o[o.length] = '<a:gradFill rotWithShape="1">';
  6120. o[o.length] = '<a:gsLst>';
  6121. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  6122. 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>';
  6123. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  6124. o[o.length] = '</a:gsLst>';
  6125. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  6126. o[o.length] = '</a:gradFill>';
  6127. o[o.length] = '<a:gradFill rotWithShape="1">';
  6128. o[o.length] = '<a:gsLst>';
  6129. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  6130. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  6131. o[o.length] = '</a:gsLst>';
  6132. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  6133. o[o.length] = '</a:gradFill>';
  6134. o[o.length] = '</a:bgFillStyleLst>';
  6135. o[o.length] = '</a:fmtScheme>';
  6136. o[o.length] = '</a:themeElements>';
  6137. o[o.length] = '<a:objectDefaults>';
  6138. o[o.length] = '<a:spDef>';
  6139. 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>';
  6140. o[o.length] = '</a:spDef>';
  6141. o[o.length] = '<a:lnDef>';
  6142. 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>';
  6143. o[o.length] = '</a:lnDef>';
  6144. o[o.length] = '</a:objectDefaults>';
  6145. o[o.length] = '<a:extraClrSchemeLst/>';
  6146. o[o.length] = '</a:theme>';
  6147. return o.join("");
  6148. }
  6149. /* 18.14 Supplementary Workbook Data */
  6150. function parse_xlink_xml() {
  6151. //var opts = _opts || {};
  6152. //if(opts.WTF) throw "XLSX External Link";
  6153. }
  6154. /* [MS-XLSB] 2.1.7.25 External Link */
  6155. function parse_xlink_bin(data, rel, name, _opts) {
  6156. if(!data) return data;
  6157. var opts = _opts || {};
  6158. var pass = false, end = false;
  6159. recordhopper(data, function xlink_parse(val, R_n, RT) {
  6160. if(end) return;
  6161. switch(RT) {
  6162. case 0x0167: /* 'BrtSupTabs' */
  6163. case 0x016B: /* 'BrtExternTableStart' */
  6164. case 0x016C: /* 'BrtExternTableEnd' */
  6165. case 0x016E: /* 'BrtExternRowHdr' */
  6166. case 0x016F: /* 'BrtExternCellBlank' */
  6167. case 0x0170: /* 'BrtExternCellReal' */
  6168. case 0x0171: /* 'BrtExternCellBool' */
  6169. case 0x0172: /* 'BrtExternCellError' */
  6170. case 0x0173: /* 'BrtExternCellString' */
  6171. case 0x01D8: /* 'BrtExternValueMeta' */
  6172. case 0x0241: /* 'BrtSupNameStart' */
  6173. case 0x0242: /* 'BrtSupNameValueStart' */
  6174. case 0x0243: /* 'BrtSupNameValueEnd' */
  6175. case 0x0244: /* 'BrtSupNameNum' */
  6176. case 0x0245: /* 'BrtSupNameErr' */
  6177. case 0x0246: /* 'BrtSupNameSt' */
  6178. case 0x0247: /* 'BrtSupNameNil' */
  6179. case 0x0248: /* 'BrtSupNameBool' */
  6180. case 0x0249: /* 'BrtSupNameFmla' */
  6181. case 0x024A: /* 'BrtSupNameBits' */
  6182. case 0x024B: /* 'BrtSupNameEnd' */
  6183. break;
  6184. case 0x0023: /* 'BrtFRTBegin' */
  6185. pass = true; break;
  6186. case 0x0024: /* 'BrtFRTEnd' */
  6187. pass = false; break;
  6188. default:
  6189. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  6190. else if((R_n||"").indexOf("End") > 0){/* empty */}
  6191. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT.toString(16) + " " + R_n);
  6192. }
  6193. }, opts);
  6194. }
  6195. /* 20.5 DrawingML - SpreadsheetML Drawing */
  6196. RELS.IMG = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
  6197. RELS.DRAW = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
  6198. /* 20.5.2.35 wsDr CT_Drawing */
  6199. function parse_drawing(data, rels) {
  6200. if(!data) return "??";
  6201. /*
  6202. Chartsheet Drawing:
  6203. - 20.5.2.35 wsDr CT_Drawing
  6204. - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor
  6205. - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
  6206. - 20.1.2.2.16 graphic CT_GraphicalObject
  6207. - 20.1.2.2.17 graphicData CT_GraphicalObjectData
  6208. - chart reference
  6209. the actual type is based on the URI of the graphicData
  6210. TODO: handle embedded charts and other types of graphics
  6211. */
  6212. var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];
  6213. return rels['!id'][id].Target;
  6214. }
  6215. /* L.5.5.2 SpreadsheetML Comments + VML Schema */
  6216. var _shapeid = 1024;
  6217. function write_comments_vml(rId, comments) {
  6218. var csize = [21600, 21600];
  6219. /* L.5.2.1.2 Path Attribute */
  6220. var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
  6221. var o = [
  6222. writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
  6223. writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"}),
  6224. writextag("v:shapetype", [
  6225. writextag("v:stroke", null, {joinstyle:"miter"}),
  6226. writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
  6227. ].join(""), {id:"_x0000_t202", 'o:spt':202, coordsize:csize.join(","),path:bbox})
  6228. ];
  6229. while(_shapeid < rId * 1000) _shapeid += 1000;
  6230. comments.forEach(function(x) {
  6231. var c = decode_cell(x[0]);
  6232. var fillopts = {'color2':"#BEFF82", 'type':"gradient"};
  6233. if(fillopts.type == "gradient") fillopts.angle = "-180";
  6234. var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
  6235. var fillxml = writextag('v:fill', fillparm, fillopts);
  6236. var shadata = ({on:"t", 'obscured':"t"});
  6237. ++_shapeid;
  6238. o = o.concat([
  6239. '<v:shape' + wxt_helper({
  6240. id:'_x0000_s' + _shapeid,
  6241. type:"#_x0000_t202",
  6242. style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
  6243. fillcolor:"#ECFAD4",
  6244. strokecolor:"#edeaa1"
  6245. }) + '>',
  6246. fillxml,
  6247. writextag("v:shadow", null, shadata),
  6248. writextag("v:path", null, {'o:connecttype':"none"}),
  6249. '<v:textbox><div style="text-align:left"></div></v:textbox>',
  6250. '<x:ClientData ObjectType="Note">',
  6251. '<x:MoveWithCells/>',
  6252. '<x:SizeWithCells/>',
  6253. /* Part 4 19.4.2.3 Anchor (Anchor) */
  6254. writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
  6255. writetag('x:AutoFill', "False"),
  6256. writetag('x:Row', String(c.r)),
  6257. writetag('x:Column', String(c.c)),
  6258. x[1].hidden ? '' : '<x:Visible/>',
  6259. '</x:ClientData>',
  6260. '</v:shape>'
  6261. ]); });
  6262. o.push('</xml>');
  6263. return o.join("");
  6264. }
  6265. RELS.CMNT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
  6266. function sheet_insert_comments(sheet, comments) {
  6267. var dense = Array.isArray(sheet);
  6268. var cell;
  6269. comments.forEach(function(comment) {
  6270. var r = decode_cell(comment.ref);
  6271. if(dense) {
  6272. if(!sheet[r.r]) sheet[r.r] = [];
  6273. cell = sheet[r.r][r.c];
  6274. } else cell = sheet[comment.ref];
  6275. if (!cell) {
  6276. cell = ({t:"z"});
  6277. if(dense) sheet[r.r][r.c] = cell;
  6278. else sheet[comment.ref] = cell;
  6279. var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
  6280. if(range.s.r > r.r) range.s.r = r.r;
  6281. if(range.e.r < r.r) range.e.r = r.r;
  6282. if(range.s.c > r.c) range.s.c = r.c;
  6283. if(range.e.c < r.c) range.e.c = r.c;
  6284. var encoded = encode_range(range);
  6285. if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
  6286. }
  6287. if (!cell.c) cell.c = [];
  6288. var o = ({a: comment.author, t: comment.t, r: comment.r});
  6289. if(comment.h) o.h = comment.h;
  6290. cell.c.push(o);
  6291. });
  6292. }
  6293. /* 18.7 Comments */
  6294. function parse_comments_xml(data, opts) {
  6295. /* 18.7.6 CT_Comments */
  6296. if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
  6297. var authors = [];
  6298. var commentList = [];
  6299. var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
  6300. if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
  6301. if(x === "" || x.trim() === "") return;
  6302. var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
  6303. if(a) authors.push(a[1]);
  6304. });
  6305. var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
  6306. if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
  6307. if(x === "" || x.trim() === "") return;
  6308. var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
  6309. if(!cm) return;
  6310. var y = parsexmltag(cm[0]);
  6311. var comment = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid });
  6312. var cell = decode_cell(y.ref);
  6313. if(opts.sheetRows && opts.sheetRows <= cell.r) return;
  6314. var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
  6315. var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
  6316. comment.r = rt.r;
  6317. if(rt.r == "<t></t>") rt.t = rt.h = "";
  6318. comment.t = rt.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  6319. if(opts.cellHTML) comment.h = rt.h;
  6320. commentList.push(comment);
  6321. });
  6322. return commentList;
  6323. }
  6324. var CMNT_XML_ROOT = writextag('comments', null, { 'xmlns': XMLNS.main[0] });
  6325. function write_comments_xml(data) {
  6326. var o = [XML_HEADER, CMNT_XML_ROOT];
  6327. var iauthor = [];
  6328. o.push("<authors>");
  6329. data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
  6330. if(iauthor.indexOf(a) > -1) return;
  6331. iauthor.push(a);
  6332. o.push("<author>" + a + "</author>");
  6333. }); });
  6334. o.push("</authors>");
  6335. o.push("<commentList>");
  6336. data.forEach(function(d) {
  6337. d[1].forEach(function(c) {
  6338. /* 18.7.3 CT_Comment */
  6339. o.push('<comment ref="' + d[0] + '" authorId="' + iauthor.indexOf(escapexml(c.a)) + '"><text>');
  6340. o.push(writetag("t", c.t == null ? "" : escapexml(c.t)));
  6341. o.push('</text></comment>');
  6342. });
  6343. });
  6344. o.push("</commentList>");
  6345. if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
  6346. return o.join("");
  6347. }
  6348. var CT_VBA = "application/vnd.ms-office.vbaProject";
  6349. function make_vba_xls(cfb) {
  6350. var newcfb = CFB.utils.cfb_new({root:"R"});
  6351. cfb.FullPaths.forEach(function(p, i) {
  6352. if(p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/)) return;
  6353. var newpath = p.replace(/^[^\/]*/,"R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
  6354. CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  6355. });
  6356. return CFB.write(newcfb);
  6357. }
  6358. function fill_vba_xls(cfb, vba) {
  6359. vba.FullPaths.forEach(function(p, i) {
  6360. if(i == 0) return;
  6361. var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
  6362. if(newpath.slice(-1) !== "/") CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  6363. });
  6364. }
  6365. var VBAFMTS = [ "xlsb", "xlsm", "xlam", "biff8", "xla" ];
  6366. RELS.DS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet";
  6367. RELS.MS = "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet";
  6368. /* macro and dialog sheet stubs */
  6369. function parse_ds_bin() { return {'!type':'dialog'}; }
  6370. function parse_ds_xml() { return {'!type':'dialog'}; }
  6371. function parse_ms_bin() { return {'!type':'macro'}; }
  6372. function parse_ms_xml() { return {'!type':'macro'}; }
  6373. /* TODO: it will be useful to parse the function str */
  6374. var rc_to_a1 = (function(){
  6375. var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  6376. var rcbase = ({r:0,c:0});
  6377. function rcfunc($$,$1,$2,$3) {
  6378. var cRel = false, rRel = false;
  6379. if($2.length == 0) rRel = true;
  6380. else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }
  6381. if($3.length == 0) cRel = true;
  6382. else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }
  6383. var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;
  6384. if(cRel) C += rcbase.c; else --C;
  6385. if(rRel) R += rcbase.r; else --R;
  6386. return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
  6387. }
  6388. return function rc_to_a1(fstr, base) {
  6389. rcbase = base;
  6390. return fstr.replace(rcregex, rcfunc);
  6391. };
  6392. })();
  6393. 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;
  6394. var a1_to_rc =(function(){
  6395. return function a1_to_rc(fstr, base) {
  6396. return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  6397. var c = decode_col($3) - ($2 ? 0 : base.c);
  6398. var r = decode_row($5) - ($4 ? 0 : base.r);
  6399. var R = (r == 0 ? "" : !$4 ? "[" + r + "]" : (r+1));
  6400. var C = (c == 0 ? "" : !$2 ? "[" + c + "]" : (c+1));
  6401. return $1 + "R" + R + "C" + C;
  6402. });
  6403. };
  6404. })();
  6405. /* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
  6406. function shift_formula_str(f, delta) {
  6407. return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  6408. return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
  6409. });
  6410. }
  6411. function shift_formula_xlsx(f, range, cell) {
  6412. var r = decode_range(range), s = r.s, c = decode_cell(cell);
  6413. var delta = {r:c.r - s.r, c:c.c - s.c};
  6414. return shift_formula_str(f, delta);
  6415. }
  6416. /* TODO: parse formula */
  6417. function fuzzyfmla(f) {
  6418. if(f.length == 1) return false;
  6419. return true;
  6420. }
  6421. function _xlfn(f) {
  6422. return f.replace(/_xlfn\./g,"");
  6423. }
  6424. var strs = {}; // shared strings
  6425. var _ssfopts = {}; // spreadsheet formatting options
  6426. RELS.WS = [
  6427. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  6428. "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  6429. ];
  6430. /*global Map */
  6431. var browser_has_Map = typeof Map !== 'undefined';
  6432. function get_sst_id(sst, str, rev) {
  6433. var i = 0, len = sst.length;
  6434. if(rev) {
  6435. if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
  6436. var revarr = browser_has_Map ? rev.get(str) : rev[str];
  6437. for(; i < revarr.length; ++i) {
  6438. if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
  6439. }
  6440. }
  6441. } else for(; i < len; ++i) {
  6442. if(sst[i].t === str) { sst.Count ++; return i; }
  6443. }
  6444. sst[len] = ({t:str}); sst.Count ++; sst.Unique ++;
  6445. if(rev) {
  6446. if(browser_has_Map) {
  6447. if(!rev.has(str)) rev.set(str, []);
  6448. rev.get(str).push(len);
  6449. } else {
  6450. if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
  6451. rev[str].push(len);
  6452. }
  6453. }
  6454. return len;
  6455. }
  6456. function col_obj_w(C, col) {
  6457. var p = ({min:C+1,max:C+1});
  6458. /* wch (chars), wpx (pixels) */
  6459. var wch = -1;
  6460. if(col.MDW) MDW = col.MDW;
  6461. if(col.width != null) p.customWidth = 1;
  6462. else if(col.wpx != null) wch = px2char(col.wpx);
  6463. else if(col.wch != null) wch = col.wch;
  6464. if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
  6465. else if(col.width != null) p.width = col.width;
  6466. if(col.hidden) p.hidden = true;
  6467. return p;
  6468. }
  6469. function default_margins(margins, mode) {
  6470. if(!margins) return;
  6471. var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  6472. if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
  6473. if(margins.left == null) margins.left = defs[0];
  6474. if(margins.right == null) margins.right = defs[1];
  6475. if(margins.top == null) margins.top = defs[2];
  6476. if(margins.bottom == null) margins.bottom = defs[3];
  6477. if(margins.header == null) margins.header = defs[4];
  6478. if(margins.footer == null) margins.footer = defs[5];
  6479. }
  6480. function get_cell_style(styles, cell, opts) {
  6481. var z = opts.revssf[cell.z != null ? cell.z : "General"];
  6482. var i = 0x3c, len = styles.length;
  6483. if(z == null && opts.ssf) {
  6484. for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
  6485. SSF.load(cell.z, i);
  6486. // $FlowIgnore
  6487. opts.ssf[i] = cell.z;
  6488. opts.revssf[cell.z] = z = i;
  6489. break;
  6490. }
  6491. }
  6492. for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
  6493. styles[len] = {
  6494. numFmtId:z,
  6495. fontId:0,
  6496. fillId:0,
  6497. borderId:0,
  6498. xfId:0,
  6499. applyNumberFormat:1
  6500. };
  6501. return len;
  6502. }
  6503. function safe_format(p, fmtid, fillid, opts, themes, styles) {
  6504. try {
  6505. if(opts.cellNF) p.z = SSF._table[fmtid];
  6506. } catch(e) { if(opts.WTF) throw e; }
  6507. if(p.t === 'z') return;
  6508. if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
  6509. if(!opts || opts.cellText !== false) try {
  6510. if(SSF._table[fmtid] == null) SSF.load(SSFImplicit[fmtid] || "General", fmtid);
  6511. if(p.t === 'e') p.w = p.w || BErr[p.v];
  6512. else if(fmtid === 0) {
  6513. if(p.t === 'n') {
  6514. if((p.v|0) === p.v) p.w = SSF._general_int(p.v);
  6515. else p.w = SSF._general_num(p.v);
  6516. }
  6517. else if(p.t === 'd') {
  6518. var dd = datenum(p.v);
  6519. if((dd|0) === dd) p.w = SSF._general_int(dd);
  6520. else p.w = SSF._general_num(dd);
  6521. }
  6522. else if(p.v === undefined) return "";
  6523. else p.w = SSF._general(p.v,_ssfopts);
  6524. }
  6525. else if(p.t === 'd') p.w = SSF.format(fmtid,datenum(p.v),_ssfopts);
  6526. else p.w = SSF.format(fmtid,p.v,_ssfopts);
  6527. } catch(e) { if(opts.WTF) throw e; }
  6528. if(!opts.cellStyles) return;
  6529. if(fillid != null) try {
  6530. p.s = styles.Fills[fillid];
  6531. if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
  6532. p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
  6533. if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
  6534. }
  6535. if (p.s.bgColor && p.s.bgColor.theme) {
  6536. p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
  6537. if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
  6538. }
  6539. } catch(e) { if(opts.WTF && styles.Fills) throw e; }
  6540. }
  6541. function check_ws(ws, sname, i) {
  6542. if(ws && ws['!ref']) {
  6543. var range = safe_decode_range(ws['!ref']);
  6544. if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
  6545. }
  6546. }
  6547. function parse_ws_xml_dim(ws, s) {
  6548. var d = safe_decode_range(s);
  6549. 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);
  6550. }
  6551. var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
  6552. var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
  6553. var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
  6554. var dimregex = /"(\w*:\w*)"/;
  6555. var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
  6556. var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
  6557. var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
  6558. var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
  6559. var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
  6560. /* 18.3 Worksheets */
  6561. function parse_ws_xml(data, opts, idx, rels, wb, themes, styles) {
  6562. if(!data) return data;
  6563. if(!rels) rels = {'!id':{}};
  6564. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  6565. /* 18.3.1.99 worksheet CT_Worksheet */
  6566. var s = opts.dense ? ([]) : ({});
  6567. var refguess = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} });
  6568. var data1 = "", data2 = "";
  6569. var mtch = data.match(sheetdataregex);
  6570. if(mtch) {
  6571. data1 = data.slice(0, mtch.index);
  6572. data2 = data.slice(mtch.index + mtch[0].length);
  6573. } else data1 = data2 = data;
  6574. /* 18.3.1.82 sheetPr CT_SheetPr */
  6575. var sheetPr = data1.match(sheetprregex);
  6576. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  6577. /* 18.3.1.35 dimension CT_SheetDimension */
  6578. var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
  6579. if(ridx > 0) {
  6580. var ref = data1.slice(ridx,ridx+50).match(dimregex);
  6581. if(ref) parse_ws_xml_dim(s, ref[1]);
  6582. }
  6583. /* 18.3.1.88 sheetViews CT_SheetViews */
  6584. var svs = data1.match(svsregex);
  6585. if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  6586. /* 18.3.1.17 cols CT_Cols */
  6587. var columns = [];
  6588. if(opts.cellStyles) {
  6589. /* 18.3.1.13 col CT_Col */
  6590. var cols = data1.match(colregex);
  6591. if(cols) parse_ws_xml_cols(columns, cols);
  6592. }
  6593. /* 18.3.1.80 sheetData CT_SheetData ? */
  6594. if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
  6595. /* 18.3.1.2 autoFilter CT_AutoFilter */
  6596. var afilter = data2.match(afregex);
  6597. if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);
  6598. /* 18.3.1.55 mergeCells CT_MergeCells */
  6599. var merges = [];
  6600. var _merge = data2.match(mergecregex);
  6601. if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
  6602. merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
  6603. /* 18.3.1.48 hyperlinks CT_Hyperlinks */
  6604. var hlink = data2.match(hlinkregex);
  6605. if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
  6606. /* 18.3.1.62 pageMargins CT_PageMargins */
  6607. var margins = data2.match(marginregex);
  6608. if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));
  6609. if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
  6610. if(opts.sheetRows > 0 && s["!ref"]) {
  6611. var tmpref = safe_decode_range(s["!ref"]);
  6612. if(opts.sheetRows <= +tmpref.e.r) {
  6613. tmpref.e.r = opts.sheetRows - 1;
  6614. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  6615. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  6616. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  6617. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  6618. s["!fullref"] = s["!ref"];
  6619. s["!ref"] = encode_range(tmpref);
  6620. }
  6621. }
  6622. if(columns.length > 0) s["!cols"] = columns;
  6623. if(merges.length > 0) s["!merges"] = merges;
  6624. return s;
  6625. }
  6626. function write_ws_xml_merges(merges) {
  6627. if(merges.length === 0) return "";
  6628. var o = '<mergeCells count="' + merges.length + '">';
  6629. for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
  6630. return o + '</mergeCells>';
  6631. }
  6632. /* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
  6633. function parse_ws_xml_sheetpr(sheetPr, s, wb, idx) {
  6634. var data = parsexmltag(sheetPr);
  6635. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  6636. if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
  6637. }
  6638. function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
  6639. var needed = false;
  6640. var props = {}, payload = null;
  6641. if(opts.bookType !== 'xlsx' && wb.vbaraw) {
  6642. var cname = wb.SheetNames[idx];
  6643. try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
  6644. needed = true;
  6645. props.codeName = utf8write(escapexml(cname));
  6646. }
  6647. if(ws && ws["!outline"]) {
  6648. var outlineprops = {summaryBelow:1, summaryRight:1};
  6649. if(ws["!outline"].above) outlineprops.summaryBelow = 0;
  6650. if(ws["!outline"].left) outlineprops.summaryRight = 0;
  6651. payload = (payload||"") + writextag('outlinePr', null, outlineprops);
  6652. }
  6653. if(!needed && !payload) return;
  6654. o[o.length] = (writextag('sheetPr', payload, props));
  6655. }
  6656. /* 18.3.1.85 sheetProtection CT_SheetProtection */
  6657. var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
  6658. var sheetprot_deftrue = [
  6659. "formatColumns", "formatRows", "formatCells",
  6660. "insertColumns", "insertRows", "insertHyperlinks",
  6661. "deleteColumns", "deleteRows",
  6662. "sort", "autoFilter", "pivotTables"
  6663. ];
  6664. function write_ws_xml_protection(sp) {
  6665. // algorithmName, hashValue, saltValue, spinCount
  6666. var o = ({sheet:1});
  6667. sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
  6668. sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
  6669. /* TODO: algorithm */
  6670. if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
  6671. return writextag('sheetProtection', null, o);
  6672. }
  6673. function parse_ws_xml_hlinks(s, data, rels) {
  6674. var dense = Array.isArray(s);
  6675. for(var i = 0; i != data.length; ++i) {
  6676. var val = parsexmltag(utf8read(data[i]), true);
  6677. if(!val.ref) return;
  6678. var rel = ((rels || {})['!id']||[])[val.id];
  6679. if(rel) {
  6680. val.Target = rel.Target;
  6681. if(val.location) val.Target += "#"+val.location;
  6682. } else {
  6683. val.Target = "#" + val.location;
  6684. rel = {Target: val.Target, TargetMode: 'Internal'};
  6685. }
  6686. val.Rel = rel;
  6687. if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
  6688. var rng = safe_decode_range(val.ref);
  6689. for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
  6690. var addr = encode_cell({c:C,r:R});
  6691. if(dense) {
  6692. if(!s[R]) s[R] = [];
  6693. if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
  6694. s[R][C].l = val;
  6695. } else {
  6696. if(!s[addr]) s[addr] = {t:"z",v:undefined};
  6697. s[addr].l = val;
  6698. }
  6699. }
  6700. }
  6701. }
  6702. function parse_ws_xml_margins(margin) {
  6703. var o = {};
  6704. ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
  6705. if(margin[k]) o[k] = parseFloat(margin[k]);
  6706. });
  6707. return o;
  6708. }
  6709. function write_ws_xml_margins(margin) {
  6710. default_margins(margin);
  6711. return writextag('pageMargins', null, margin);
  6712. }
  6713. function parse_ws_xml_cols(columns, cols) {
  6714. var seencol = false;
  6715. for(var coli = 0; coli != cols.length; ++coli) {
  6716. var coll = parsexmltag(cols[coli], true);
  6717. if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
  6718. var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
  6719. delete coll.min; delete coll.max; coll.width = +coll.width;
  6720. if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
  6721. process_col(coll);
  6722. while(colm <= colM) columns[colm++] = dup(coll);
  6723. }
  6724. }
  6725. function write_ws_xml_cols(ws, cols) {
  6726. var o = ["<cols>"], col;
  6727. for(var i = 0; i != cols.length; ++i) {
  6728. if(!(col = cols[i])) continue;
  6729. o[o.length] = (writextag('col', null, col_obj_w(i, col)));
  6730. }
  6731. o[o.length] = "</cols>";
  6732. return o.join("");
  6733. }
  6734. function parse_ws_xml_autofilter(data) {
  6735. var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
  6736. return o;
  6737. }
  6738. function write_ws_xml_autofilter(data, ws, wb, idx) {
  6739. var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
  6740. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  6741. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  6742. var names = wb.Workbook.Names;
  6743. var range = decode_range(ref);
  6744. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  6745. for(var i = 0; i < names.length; ++i) {
  6746. var name = names[i];
  6747. if(name.Name != '_xlnm._FilterDatabase') continue;
  6748. if(name.Sheet != idx) continue;
  6749. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  6750. }
  6751. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  6752. return writextag("autoFilter", null, {ref:ref});
  6753. }
  6754. /* 18.3.1.88 sheetViews CT_SheetViews */
  6755. /* 18.3.1.87 sheetView CT_SheetView */
  6756. var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
  6757. function parse_ws_xml_sheetviews(data, wb) {
  6758. if(!wb.Views) wb.Views = [{}];
  6759. (data.match(sviewregex)||[]).forEach(function(r, i) {
  6760. var tag = parsexmltag(r);
  6761. // $FlowIgnore
  6762. if(!wb.Views[i]) wb.Views[i] = {};
  6763. // $FlowIgnore
  6764. if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
  6765. });
  6766. }
  6767. function write_ws_xml_sheetviews(ws, opts, idx, wb) {
  6768. var sview = ({workbookViewId:"0"});
  6769. // $FlowIgnore
  6770. if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
  6771. return writextag("sheetViews", writextag("sheetView", null, sview), {});
  6772. }
  6773. function write_ws_xml_cell(cell, ref, ws, opts) {
  6774. if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z') return "";
  6775. var vv = "";
  6776. var oldt = cell.t, oldv = cell.v;
  6777. if(cell.t !== "z") switch(cell.t) {
  6778. case 'b': vv = cell.v ? "1" : "0"; break;
  6779. case 'n': vv = ''+cell.v; break;
  6780. case 'e': vv = BErr[cell.v]; break;
  6781. case 'd':
  6782. if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
  6783. else {
  6784. cell = dup(cell);
  6785. cell.t = 'n';
  6786. vv = ''+(cell.v = datenum(parseDate(cell.v)));
  6787. }
  6788. if(typeof cell.z === 'undefined') cell.z = SSF._table[14];
  6789. break;
  6790. default: vv = cell.v; break;
  6791. }
  6792. var v = writetag('v', escapexml(vv)), o = ({r:ref});
  6793. /* TODO: cell style */
  6794. var os = get_cell_style(opts.cellXfs, cell, opts);
  6795. if(os !== 0) o.s = os;
  6796. switch(cell.t) {
  6797. case 'n': break;
  6798. case 'd': o.t = "d"; break;
  6799. case 'b': o.t = "b"; break;
  6800. case 'e': o.t = "e"; break;
  6801. case 'z': break;
  6802. default: if(cell.v == null) { delete cell.t; break; }
  6803. if(opts && opts.bookSST) {
  6804. v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
  6805. o.t = "s"; break;
  6806. }
  6807. o.t = "str"; break;
  6808. }
  6809. if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
  6810. if(typeof cell.f == "string" && cell.f) {
  6811. var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
  6812. v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
  6813. }
  6814. if(cell.l) ws['!links'].push([ref, cell.l]);
  6815. if(cell.c) ws['!comments'].push([ref, cell.c]);
  6816. return writextag('c', v, o);
  6817. }
  6818. var parse_ws_xml_data = (function() {
  6819. var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  6820. var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
  6821. var refregex = /ref=["']([^"']*)["']/;
  6822. var match_v = matchtag("v"), match_f = matchtag("f");
  6823. return function parse_ws_xml_data(sdata, s, opts, guess, themes, styles) {
  6824. var ri = 0, x = "", cells = [], cref = [], idx=0, i=0, cc=0, d="", p;
  6825. var tag, tagr = 0, tagc = 0;
  6826. var sstr, ftag;
  6827. var fmtid = 0, fillid = 0;
  6828. var do_format = Array.isArray(styles.CellXf), cf;
  6829. var arrayf = [];
  6830. var sharedf = [];
  6831. var dense = Array.isArray(s);
  6832. var rows = [], rowobj = {}, rowrite = false;
  6833. var sheetStubs = !!opts.sheetStubs;
  6834. for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
  6835. x = marr[mt].trim();
  6836. var xlen = x.length;
  6837. if(xlen === 0) continue;
  6838. /* 18.3.1.73 row CT_Row */
  6839. for(ri = 0; ri < xlen; ++ri) if(x.charCodeAt(ri) === 62) break; ++ri;
  6840. tag = parsexmltag(x.slice(0,ri), true);
  6841. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  6842. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  6843. if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
  6844. if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
  6845. if(opts && opts.cellStyles) {
  6846. rowobj = {}; rowrite = false;
  6847. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  6848. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  6849. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  6850. if(rowrite) rows[tagr-1] = rowobj;
  6851. }
  6852. /* 18.3.1.4 c CT_Cell */
  6853. cells = x.slice(ri).split(cellregex);
  6854. for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
  6855. cells = cells.slice(rslice);
  6856. for(ri = 0; ri != cells.length; ++ri) {
  6857. x = cells[ri].trim();
  6858. if(x.length === 0) continue;
  6859. cref = x.match(rregex); idx = ri; i=0; cc=0;
  6860. x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
  6861. if(cref != null && cref.length === 2) {
  6862. idx = 0; d=cref[1];
  6863. for(i=0; i != d.length; ++i) {
  6864. if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
  6865. idx = 26*idx + cc;
  6866. }
  6867. --idx;
  6868. tagc = idx;
  6869. } else ++tagc;
  6870. for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
  6871. tag = parsexmltag(x.slice(0,i), true);
  6872. if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
  6873. d = x.slice(i);
  6874. p = ({t:""});
  6875. if((cref=d.match(match_v))!= null && cref[1] !== '') p.v=unescapexml(cref[1]);
  6876. if(opts.cellFormula) {
  6877. if((cref=d.match(match_f))!= null && cref[1] !== '') {
  6878. /* TODO: match against XLSXFutureFunctions */
  6879. p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
  6880. if(!opts.xlfn) p.f = _xlfn(p.f);
  6881. if(cref[0].indexOf('t="array"') > -1) {
  6882. p.F = (d.match(refregex)||[])[1];
  6883. if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
  6884. } else if(cref[0].indexOf('t="shared"') > -1) {
  6885. // TODO: parse formula
  6886. ftag = parsexmltag(cref[0]);
  6887. var ___f = unescapexml(utf8read(cref[1]));
  6888. if(!opts.xlfn) ___f = _xlfn(___f);
  6889. sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
  6890. }
  6891. } else if((cref=d.match(/<f[^>]*\/>/))) {
  6892. ftag = parsexmltag(cref[0]);
  6893. if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
  6894. }
  6895. /* TODO: factor out contains logic */
  6896. var _tag = decode_cell(tag.r);
  6897. for(i = 0; i < arrayf.length; ++i)
  6898. if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
  6899. if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
  6900. p.F = arrayf[i][1];
  6901. }
  6902. if(tag.t == null && p.v === undefined) {
  6903. if(p.f || p.F) {
  6904. p.v = 0; p.t = "n";
  6905. } else if(!sheetStubs) continue;
  6906. else p.t = "z";
  6907. }
  6908. else p.t = tag.t || "n";
  6909. if(guess.s.c > tagc) guess.s.c = tagc;
  6910. if(guess.e.c < tagc) guess.e.c = tagc;
  6911. /* 18.18.11 t ST_CellType */
  6912. switch(p.t) {
  6913. case 'n':
  6914. if(p.v == "" || p.v == null) {
  6915. if(!sheetStubs) continue;
  6916. p.t = 'z';
  6917. } else p.v = parseFloat(p.v);
  6918. break;
  6919. case 's':
  6920. if(typeof p.v == 'undefined') {
  6921. if(!sheetStubs) continue;
  6922. p.t = 'z';
  6923. } else {
  6924. sstr = strs[parseInt(p.v, 10)];
  6925. p.v = sstr.t;
  6926. p.r = sstr.r;
  6927. if(opts.cellHTML) p.h = sstr.h;
  6928. }
  6929. break;
  6930. case 'str':
  6931. p.t = "s";
  6932. p.v = (p.v!=null) ? utf8read(p.v) : '';
  6933. if(opts.cellHTML) p.h = escapehtml(p.v);
  6934. break;
  6935. case 'inlineStr':
  6936. cref = d.match(isregex);
  6937. p.t = 's';
  6938. if(cref != null && (sstr = parse_si(cref[1]))) {
  6939. p.v = sstr.t;
  6940. if(opts.cellHTML) p.h = sstr.h;
  6941. } else p.v = "";
  6942. break;
  6943. case 'b': p.v = parsexmlbool(p.v); break;
  6944. case 'd':
  6945. if(opts.cellDates) p.v = parseDate(p.v, 1);
  6946. else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
  6947. break;
  6948. /* error string in .w, number in .v */
  6949. case 'e':
  6950. if(!opts || opts.cellText !== false) p.w = p.v;
  6951. p.v = RBErr[p.v]; break;
  6952. }
  6953. /* formatting */
  6954. fmtid = fillid = 0;
  6955. cf = null;
  6956. if(do_format && tag.s !== undefined) {
  6957. cf = styles.CellXf[tag.s];
  6958. if(cf != null) {
  6959. if(cf.numFmtId != null) fmtid = cf.numFmtId;
  6960. if(opts.cellStyles) {
  6961. if(cf.fillId != null) fillid = cf.fillId;
  6962. }
  6963. }
  6964. }
  6965. safe_format(p, fmtid, fillid, opts, themes, styles);
  6966. if(opts.cellDates && do_format && p.t == 'n' && SSF.is_date(SSF._table[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
  6967. if(dense) {
  6968. var _r = decode_cell(tag.r);
  6969. if(!s[_r.r]) s[_r.r] = [];
  6970. s[_r.r][_r.c] = p;
  6971. } else s[tag.r] = p;
  6972. }
  6973. }
  6974. if(rows.length > 0) s['!rows'] = rows;
  6975. }; })();
  6976. function write_ws_xml_data(ws, opts, idx, wb) {
  6977. var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
  6978. var dense = Array.isArray(ws);
  6979. var params = ({r:rr}), row, height = -1;
  6980. for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
  6981. for(R = range.s.r; R <= range.e.r; ++R) {
  6982. r = [];
  6983. rr = encode_row(R);
  6984. for(C = range.s.c; C <= range.e.c; ++C) {
  6985. ref = cols[C] + rr;
  6986. var _cell = dense ? (ws[R]||[])[C]: ws[ref];
  6987. if(_cell === undefined) continue;
  6988. if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
  6989. }
  6990. if(r.length > 0 || (rows && rows[R])) {
  6991. params = ({r:rr});
  6992. if(rows && rows[R]) {
  6993. row = rows[R];
  6994. if(row.hidden) params.hidden = 1;
  6995. height = -1;
  6996. if(row.hpx) height = px2pt(row.hpx);
  6997. else if(row.hpt) height = row.hpt;
  6998. if(height > -1) { params.ht = height; params.customHeight = 1; }
  6999. if(row.level) { params.outlineLevel = row.level; }
  7000. }
  7001. o[o.length] = (writextag('row', r.join(""), params));
  7002. }
  7003. }
  7004. if(rows) for(; R < rows.length; ++R) {
  7005. if(rows && rows[R]) {
  7006. params = ({r:R+1});
  7007. row = rows[R];
  7008. if(row.hidden) params.hidden = 1;
  7009. height = -1;
  7010. if (row.hpx) height = px2pt(row.hpx);
  7011. else if (row.hpt) height = row.hpt;
  7012. if (height > -1) { params.ht = height; params.customHeight = 1; }
  7013. if (row.level) { params.outlineLevel = row.level; }
  7014. o[o.length] = (writextag('row', "", params));
  7015. }
  7016. }
  7017. return o.join("");
  7018. }
  7019. var WS_XML_ROOT = writextag('worksheet', null, {
  7020. 'xmlns': XMLNS.main[0],
  7021. 'xmlns:r': XMLNS.r
  7022. });
  7023. function write_ws_xml(idx, opts, wb, rels) {
  7024. var o = [XML_HEADER, WS_XML_ROOT];
  7025. var s = wb.SheetNames[idx], sidx = 0, rdata = "";
  7026. var ws = wb.Sheets[s];
  7027. if(ws == null) ws = {};
  7028. var ref = ws['!ref'] || 'A1';
  7029. var range = safe_decode_range(ref);
  7030. if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
  7031. if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
  7032. range.e.c = Math.min(range.e.c, 0x3FFF);
  7033. range.e.r = Math.min(range.e.c, 0xFFFFF);
  7034. ref = encode_range(range);
  7035. }
  7036. if(!rels) rels = {};
  7037. ws['!comments'] = [];
  7038. var _drawing = [];
  7039. write_ws_xml_sheetpr(ws, wb, idx, opts, o);
  7040. o[o.length] = (writextag('dimension', null, {'ref': ref}));
  7041. o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
  7042. /* TODO: store in WB, process styles */
  7043. if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
  7044. defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
  7045. baseColWidth:opts.sheetFormat.baseColWidth||'10',
  7046. outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
  7047. }));
  7048. if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
  7049. o[sidx = o.length] = '<sheetData/>';
  7050. ws['!links'] = [];
  7051. if(ws['!ref'] != null) {
  7052. rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
  7053. if(rdata.length > 0) o[o.length] = (rdata);
  7054. }
  7055. if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
  7056. /* sheetCalcPr */
  7057. if(ws['!protect'] != null) o[o.length] = write_ws_xml_protection(ws['!protect']);
  7058. /* protectedRanges */
  7059. /* scenarios */
  7060. if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
  7061. /* sortState */
  7062. /* dataConsolidate */
  7063. /* customSheetViews */
  7064. if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
  7065. /* phoneticPr */
  7066. /* conditionalFormatting */
  7067. /* dataValidations */
  7068. var relc = -1, rel, rId = -1;
  7069. if(ws['!links'].length > 0) {
  7070. o[o.length] = "<hyperlinks>";
  7071. ws['!links'].forEach(function(l) {
  7072. if(!l[1].Target) return;
  7073. rel = ({"ref":l[0]});
  7074. if(l[1].Target.charAt(0) != "#") {
  7075. rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
  7076. rel["r:id"] = "rId"+rId;
  7077. }
  7078. if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
  7079. if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
  7080. o[o.length] = writextag("hyperlink",null,rel);
  7081. });
  7082. o[o.length] = "</hyperlinks>";
  7083. }
  7084. delete ws['!links'];
  7085. /* printOptions */
  7086. if(ws['!margins'] != null) o[o.length] = write_ws_xml_margins(ws['!margins']);
  7087. /* pageSetup */
  7088. /* headerFooter */
  7089. /* rowBreaks */
  7090. /* colBreaks */
  7091. /* customProperties */
  7092. /* cellWatches */
  7093. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
  7094. /* smartTags */
  7095. if(_drawing.length > 0) {
  7096. rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  7097. o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
  7098. ws['!drawing'] = _drawing;
  7099. }
  7100. if(ws['!comments'].length > 0) {
  7101. rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  7102. o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
  7103. ws['!legacy'] = rId;
  7104. }
  7105. /* legacyDrawingHF */
  7106. /* picture */
  7107. /* oleObjects */
  7108. /* controls */
  7109. /* webPublishItems */
  7110. /* tableParts */
  7111. /* extLst */
  7112. if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
  7113. return o.join("");
  7114. }
  7115. RELS.CHART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
  7116. RELS.CHARTEX = "http://schemas.microsoft.com/office/2014/relationships/chartEx";
  7117. function parse_Cache(data) {
  7118. var col = [];
  7119. var num = data.match(/^<c:numCache>/);
  7120. var f;
  7121. /* 21.2.2.150 pt CT_NumVal */
  7122. (data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
  7123. var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
  7124. if(!q) return;
  7125. col[+q[1]] = num ? +q[2] : q[2];
  7126. });
  7127. /* 21.2.2.71 formatCode CT_Xstring */
  7128. var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);
  7129. (data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });
  7130. return [col, nf, f];
  7131. }
  7132. /* 21.2 DrawingML - Charts */
  7133. function parse_chart(data, name, opts, rels, wb, csheet) {
  7134. var cs = ((csheet || {"!type":"chart"}));
  7135. if(!data) return csheet;
  7136. /* 21.2.2.27 chart CT_Chart */
  7137. var C = 0, R = 0, col = "A";
  7138. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  7139. /* 21.2.2.120 numCache CT_NumData */
  7140. (data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
  7141. var cache = parse_Cache(nc);
  7142. refguess.s.r = refguess.s.c = 0;
  7143. refguess.e.c = C;
  7144. col = encode_col(C);
  7145. cache[0].forEach(function(n,i) {
  7146. cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
  7147. R = i;
  7148. });
  7149. if(refguess.e.r < R) refguess.e.r = R;
  7150. ++C;
  7151. });
  7152. if(C > 0) cs["!ref"] = encode_range(refguess);
  7153. return cs;
  7154. }
  7155. RELS.CS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet";
  7156. var CS_XML_ROOT = writextag('chartsheet', null, {
  7157. 'xmlns': XMLNS.main[0],
  7158. 'xmlns:r': XMLNS.r
  7159. });
  7160. /* 18.3 Worksheets also covers Chartsheets */
  7161. function parse_cs_xml(data, opts, idx, rels, wb) {
  7162. if(!data) return data;
  7163. /* 18.3.1.12 chartsheet CT_ChartSheet */
  7164. if(!rels) rels = {'!id':{}};
  7165. var s = ({'!type':"chart", '!drawel':null, '!rel':""});
  7166. var m;
  7167. /* 18.3.1.83 sheetPr CT_ChartsheetPr */
  7168. var sheetPr = data.match(sheetprregex);
  7169. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  7170. /* 18.3.1.36 drawing CT_Drawing */
  7171. if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];
  7172. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  7173. return s;
  7174. }
  7175. function write_cs_xml(idx, opts, wb, rels) {
  7176. var o = [XML_HEADER, CS_XML_ROOT];
  7177. o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
  7178. add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  7179. if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
  7180. return o.join("");
  7181. }
  7182. /* [MS-XLSB] 2.4.331 BrtCsProp */
  7183. function parse_BrtCsProp(data, length) {
  7184. data.l += 10;
  7185. var name = parse_XLWideString(data, length - 10);
  7186. return { name: name };
  7187. }
  7188. /* [MS-XLSB] 2.1.7.7 Chart Sheet */
  7189. function parse_cs_bin(data, opts, idx, rels, wb) {
  7190. if(!data) return data;
  7191. if(!rels) rels = {'!id':{}};
  7192. var s = {'!type':"chart", '!drawel':null, '!rel':""};
  7193. var state = [];
  7194. var pass = false;
  7195. recordhopper(data, function cs_parse(val, R_n, RT) {
  7196. switch(RT) {
  7197. case 0x0226: /* 'BrtDrawing' */
  7198. s['!rel'] = val; break;
  7199. case 0x028B: /* 'BrtCsProp' */
  7200. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  7201. if(val.name) wb.Sheets[idx].CodeName = val.name;
  7202. break;
  7203. case 0x0232: /* 'BrtBkHim' */
  7204. case 0x028C: /* 'BrtCsPageSetup' */
  7205. case 0x029D: /* 'BrtCsProtection' */
  7206. case 0x02A7: /* 'BrtCsProtectionIso' */
  7207. case 0x0227: /* 'BrtLegacyDrawing' */
  7208. case 0x0228: /* 'BrtLegacyDrawingHF' */
  7209. case 0x01DC: /* 'BrtMargins' */
  7210. case 0x0C00: /* 'BrtUid' */
  7211. break;
  7212. case 0x0023: /* 'BrtFRTBegin' */
  7213. pass = true; break;
  7214. case 0x0024: /* 'BrtFRTEnd' */
  7215. pass = false; break;
  7216. case 0x0025: /* 'BrtACBegin' */
  7217. state.push(R_n); break;
  7218. case 0x0026: /* 'BrtACEnd' */
  7219. state.pop(); break;
  7220. default:
  7221. if((R_n||"").indexOf("Begin") > 0) state.push(R_n);
  7222. else if((R_n||"").indexOf("End") > 0) state.pop();
  7223. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  7224. }
  7225. }, opts);
  7226. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  7227. return s;
  7228. }
  7229. function write_cs_bin() {
  7230. var ba = buf_array();
  7231. write_record(ba, "BrtBeginSheet");
  7232. /* [BrtCsProp] */
  7233. /* CSVIEWS */
  7234. /* [[BrtCsProtectionIso] BrtCsProtection] */
  7235. /* [USERCSVIEWS] */
  7236. /* [BrtMargins] */
  7237. /* [BrtCsPageSetup] */
  7238. /* [HEADERFOOTER] */
  7239. /* BrtDrawing */
  7240. /* [BrtLegacyDrawing] */
  7241. /* [BrtLegacyDrawingHF] */
  7242. /* [BrtBkHim] */
  7243. /* [WEBPUBITEMS] */
  7244. /* FRTCHARTSHEET */
  7245. write_record(ba, "BrtEndSheet");
  7246. return ba.end();
  7247. }
  7248. /* 18.2.28 (CT_WorkbookProtection) Defaults */
  7249. var WBPropsDef = [
  7250. ['allowRefreshQuery', false, "bool"],
  7251. ['autoCompressPictures', true, "bool"],
  7252. ['backupFile', false, "bool"],
  7253. ['checkCompatibility', false, "bool"],
  7254. ['CodeName', ''],
  7255. ['date1904', false, "bool"],
  7256. ['defaultThemeVersion', 0, "int"],
  7257. ['filterPrivacy', false, "bool"],
  7258. ['hidePivotFieldList', false, "bool"],
  7259. ['promptedSolutions', false, "bool"],
  7260. ['publishItems', false, "bool"],
  7261. ['refreshAllConnections', false, "bool"],
  7262. ['saveExternalLinkValues', true, "bool"],
  7263. ['showBorderUnselectedTables', true, "bool"],
  7264. ['showInkAnnotation', true, "bool"],
  7265. ['showObjects', 'all'],
  7266. ['showPivotChartFilter', false, "bool"],
  7267. ['updateLinks', 'userSet']
  7268. ];
  7269. /* 18.2.30 (CT_BookView) Defaults */
  7270. var WBViewDef = [
  7271. ['activeTab', 0, "int"],
  7272. ['autoFilterDateGrouping', true, "bool"],
  7273. ['firstSheet', 0, "int"],
  7274. ['minimized', false, "bool"],
  7275. ['showHorizontalScroll', true, "bool"],
  7276. ['showSheetTabs', true, "bool"],
  7277. ['showVerticalScroll', true, "bool"],
  7278. ['tabRatio', 600, "int"],
  7279. ['visibility', 'visible']
  7280. //window{Height,Width}, {x,y}Window
  7281. ];
  7282. /* 18.2.19 (CT_Sheet) Defaults */
  7283. var SheetDef = [
  7284. //['state', 'visible']
  7285. ];
  7286. /* 18.2.2 (CT_CalcPr) Defaults */
  7287. var CalcPrDef = [
  7288. ['calcCompleted', 'true'],
  7289. ['calcMode', 'auto'],
  7290. ['calcOnSave', 'true'],
  7291. ['concurrentCalc', 'true'],
  7292. ['fullCalcOnLoad', 'false'],
  7293. ['fullPrecision', 'true'],
  7294. ['iterate', 'false'],
  7295. ['iterateCount', '100'],
  7296. ['iterateDelta', '0.001'],
  7297. ['refMode', 'A1']
  7298. ];
  7299. /* 18.2.3 (CT_CustomWorkbookView) Defaults */
  7300. /*var CustomWBViewDef = [
  7301. ['autoUpdate', 'false'],
  7302. ['changesSavedWin', 'false'],
  7303. ['includeHiddenRowCol', 'true'],
  7304. ['includePrintSettings', 'true'],
  7305. ['maximized', 'false'],
  7306. ['minimized', 'false'],
  7307. ['onlySync', 'false'],
  7308. ['personalView', 'false'],
  7309. ['showComments', 'commIndicator'],
  7310. ['showFormulaBar', 'true'],
  7311. ['showHorizontalScroll', 'true'],
  7312. ['showObjects', 'all'],
  7313. ['showSheetTabs', 'true'],
  7314. ['showStatusbar', 'true'],
  7315. ['showVerticalScroll', 'true'],
  7316. ['tabRatio', '600'],
  7317. ['xWindow', '0'],
  7318. ['yWindow', '0']
  7319. ];*/
  7320. function push_defaults_array(target, defaults) {
  7321. for(var j = 0; j != target.length; ++j) { var w = target[j];
  7322. for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
  7323. if(w[z[0]] == null) w[z[0]] = z[1];
  7324. else switch(z[2]) {
  7325. case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
  7326. case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
  7327. }
  7328. }
  7329. }
  7330. }
  7331. function push_defaults(target, defaults) {
  7332. for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
  7333. if(target[z[0]] == null) target[z[0]] = z[1];
  7334. else switch(z[2]) {
  7335. case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
  7336. case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
  7337. }
  7338. }
  7339. }
  7340. function parse_wb_defaults(wb) {
  7341. push_defaults(wb.WBProps, WBPropsDef);
  7342. push_defaults(wb.CalcPr, CalcPrDef);
  7343. push_defaults_array(wb.WBView, WBViewDef);
  7344. push_defaults_array(wb.Sheets, SheetDef);
  7345. _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
  7346. }
  7347. function safe1904(wb) {
  7348. /* TODO: store date1904 somewhere else */
  7349. if(!wb.Workbook) return "false";
  7350. if(!wb.Workbook.WBProps) return "false";
  7351. return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
  7352. }
  7353. var badchars = "][*?\/\\".split("");
  7354. function check_ws_name(n, safe) {
  7355. if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
  7356. var _good = true;
  7357. badchars.forEach(function(c) {
  7358. if(n.indexOf(c) == -1) return;
  7359. if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
  7360. _good = false;
  7361. });
  7362. return _good;
  7363. }
  7364. function check_wb_names(N, S, codes) {
  7365. N.forEach(function(n,i) {
  7366. check_ws_name(n);
  7367. for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
  7368. if(codes) {
  7369. var cn = (S && S[i] && S[i].CodeName) || n;
  7370. if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
  7371. }
  7372. });
  7373. }
  7374. function check_wb(wb) {
  7375. if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
  7376. if(!wb.SheetNames.length) throw new Error("Workbook is empty");
  7377. var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
  7378. check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
  7379. for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
  7380. /* TODO: validate workbook */
  7381. }
  7382. /* 18.2 Workbook */
  7383. var wbnsregex = /<\w+:workbook/;
  7384. function parse_wb_xml(data, opts) {
  7385. if(!data) throw new Error("Could not find file");
  7386. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" };
  7387. var pass = false, xmlns = "xmlns";
  7388. var dname = {}, dnstart = 0;
  7389. data.replace(tagregex, function xml_wb(x, idx) {
  7390. var y = parsexmltag(x);
  7391. switch(strip_ns(y[0])) {
  7392. case '<?xml': break;
  7393. /* 18.2.27 workbook CT_Workbook 1 */
  7394. case '<workbook':
  7395. if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
  7396. wb.xmlns = y[xmlns];
  7397. break;
  7398. case '</workbook>': break;
  7399. /* 18.2.13 fileVersion CT_FileVersion ? */
  7400. case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
  7401. case '<fileVersion/>': case '</fileVersion>': break;
  7402. /* 18.2.12 fileSharing CT_FileSharing ? */
  7403. case '<fileSharing':
  7404. break;
  7405. case '<fileSharing/>': break;
  7406. /* 18.2.28 workbookPr CT_WorkbookPr ? */
  7407. case '<workbookPr':
  7408. case '<workbookPr/>':
  7409. WBPropsDef.forEach(function(w) {
  7410. if(y[w[0]] == null) return;
  7411. switch(w[2]) {
  7412. case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
  7413. case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
  7414. default: wb.WBProps[w[0]] = y[w[0]];
  7415. }
  7416. });
  7417. if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
  7418. break;
  7419. case '</workbookPr>': break;
  7420. /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
  7421. case '<workbookProtection':
  7422. break;
  7423. case '<workbookProtection/>': break;
  7424. /* 18.2.1 bookViews CT_BookViews ? */
  7425. case '<bookViews': case '<bookViews>': case '</bookViews>': break;
  7426. /* 18.2.30 workbookView CT_BookView + */
  7427. case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
  7428. case '</workbookView>': break;
  7429. /* 18.2.20 sheets CT_Sheets 1 */
  7430. case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
  7431. /* 18.2.19 sheet CT_Sheet + */
  7432. case '<sheet':
  7433. switch(y.state) {
  7434. case "hidden": y.Hidden = 1; break;
  7435. case "veryHidden": y.Hidden = 2; break;
  7436. default: y.Hidden = 0;
  7437. }
  7438. delete y.state;
  7439. y.name = unescapexml(utf8read(y.name));
  7440. delete y[0]; wb.Sheets.push(y); break;
  7441. case '</sheet>': break;
  7442. /* 18.2.15 functionGroups CT_FunctionGroups ? */
  7443. case '<functionGroups': case '<functionGroups/>': break;
  7444. /* 18.2.14 functionGroup CT_FunctionGroup + */
  7445. case '<functionGroup': break;
  7446. /* 18.2.9 externalReferences CT_ExternalReferences ? */
  7447. case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
  7448. /* 18.2.8 externalReference CT_ExternalReference + */
  7449. case '<externalReference': break;
  7450. /* 18.2.6 definedNames CT_DefinedNames ? */
  7451. case '<definedNames/>': break;
  7452. case '<definedNames>': case '<definedNames': pass=true; break;
  7453. case '</definedNames>': pass=false; break;
  7454. /* 18.2.5 definedName CT_DefinedName + */
  7455. case '<definedName': {
  7456. dname = {};
  7457. dname.Name = utf8read(y.name);
  7458. if(y.comment) dname.Comment = y.comment;
  7459. if(y.localSheetId) dname.Sheet = +y.localSheetId;
  7460. if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
  7461. dnstart = idx + x.length;
  7462. } break;
  7463. case '</definedName>': {
  7464. dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
  7465. wb.Names.push(dname);
  7466. } break;
  7467. case '<definedName/>': break;
  7468. /* 18.2.2 calcPr CT_CalcPr ? */
  7469. case '<calcPr': delete y[0]; wb.CalcPr = y; break;
  7470. case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
  7471. case '</calcPr>': break;
  7472. /* 18.2.16 oleSize CT_OleSize ? (ref required) */
  7473. case '<oleSize': break;
  7474. /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
  7475. case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
  7476. /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
  7477. case '<customWorkbookView': case '</customWorkbookView>': break;
  7478. /* 18.2.18 pivotCaches CT_PivotCaches ? */
  7479. case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
  7480. /* 18.2.17 pivotCache CT_PivotCache ? */
  7481. case '<pivotCache': break;
  7482. /* 18.2.21 smartTagPr CT_SmartTagPr ? */
  7483. case '<smartTagPr': case '<smartTagPr/>': break;
  7484. /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
  7485. case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
  7486. /* 18.2.22 smartTagType CT_SmartTagType ? */
  7487. case '<smartTagType': break;
  7488. /* 18.2.24 webPublishing CT_WebPublishing ? */
  7489. case '<webPublishing': case '<webPublishing/>': break;
  7490. /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
  7491. case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
  7492. /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
  7493. case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
  7494. /* 18.2.25 webPublishObject CT_WebPublishObject ? */
  7495. case '<webPublishObject': break;
  7496. /* 18.2.10 extLst CT_ExtensionList ? */
  7497. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  7498. /* 18.2.7 ext CT_Extension + */
  7499. case '<ext': pass=true; break; //TODO: check with versions of excel
  7500. case '</ext>': pass=false; break;
  7501. /* Others */
  7502. case '<ArchID': break;
  7503. case '<AlternateContent':
  7504. case '<AlternateContent>': pass=true; break;
  7505. case '</AlternateContent>': pass=false; break;
  7506. /* TODO */
  7507. case '<revisionPtr': break;
  7508. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
  7509. }
  7510. return x;
  7511. });
  7512. if(XMLNS.main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  7513. parse_wb_defaults(wb);
  7514. return wb;
  7515. }
  7516. var WB_XML_ROOT = writextag('workbook', null, {
  7517. 'xmlns': XMLNS.main[0],
  7518. //'xmlns:mx': XMLNS.mx,
  7519. //'xmlns:s': XMLNS.main[0],
  7520. 'xmlns:r': XMLNS.r
  7521. });
  7522. function write_wb_xml(wb) {
  7523. var o = [XML_HEADER];
  7524. o[o.length] = WB_XML_ROOT;
  7525. var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);
  7526. /* fileVersion */
  7527. /* fileSharing */
  7528. var workbookPr = ({codeName:"ThisWorkbook"});
  7529. if(wb.Workbook && wb.Workbook.WBProps) {
  7530. WBPropsDef.forEach(function(x) {
  7531. if((wb.Workbook.WBProps[x[0]]) == null) return;
  7532. if((wb.Workbook.WBProps[x[0]]) == x[1]) return;
  7533. workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]);
  7534. });
  7535. if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
  7536. }
  7537. o[o.length] = (writextag('workbookPr', null, workbookPr));
  7538. /* workbookProtection */
  7539. var sheets = wb.Workbook && wb.Workbook.Sheets || [];
  7540. var i = 0;
  7541. /* bookViews only written if first worksheet is hidden */
  7542. if(sheets && sheets[0] && !!sheets[0].Hidden) {
  7543. o[o.length] = "<bookViews>";
  7544. for(i = 0; i != wb.SheetNames.length; ++i) {
  7545. if(!sheets[i]) break;
  7546. if(!sheets[i].Hidden) break;
  7547. }
  7548. if(i == wb.SheetNames.length) i = 0;
  7549. o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
  7550. o[o.length] = "</bookViews>";
  7551. }
  7552. o[o.length] = "<sheets>";
  7553. for(i = 0; i != wb.SheetNames.length; ++i) {
  7554. var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))});
  7555. sht.sheetId = ""+(i+1);
  7556. sht["r:id"] = "rId"+(i+1);
  7557. if(sheets[i]) switch(sheets[i].Hidden) {
  7558. case 1: sht.state = "hidden"; break;
  7559. case 2: sht.state = "veryHidden"; break;
  7560. }
  7561. o[o.length] = (writextag('sheet',null,sht));
  7562. }
  7563. o[o.length] = "</sheets>";
  7564. /* functionGroups */
  7565. /* externalReferences */
  7566. if(write_names) {
  7567. o[o.length] = "<definedNames>";
  7568. if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
  7569. var d = {name:n.Name};
  7570. if(n.Comment) d.comment = n.Comment;
  7571. if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
  7572. if(n.Hidden) d.hidden = "1";
  7573. if(!n.Ref) return;
  7574. o[o.length] = writextag('definedName', escapexml(n.Ref), d);
  7575. });
  7576. o[o.length] = "</definedNames>";
  7577. }
  7578. /* calcPr */
  7579. /* oleSize */
  7580. /* customWorkbookViews */
  7581. /* pivotCaches */
  7582. /* smartTagPr */
  7583. /* smartTagTypes */
  7584. /* webPublishing */
  7585. /* fileRecoveryPr */
  7586. /* webPublishObjects */
  7587. /* extLst */
  7588. if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
  7589. return o.join("");
  7590. }
  7591. function parse_wb(data, name, opts) {
  7592. if(name.slice(-4)===".bin") return parse_wb_bin((data), opts);
  7593. return parse_wb_xml((data), opts);
  7594. }
  7595. function parse_ws(data, name, idx, opts, rels, wb, themes, styles) {
  7596. if(name.slice(-4)===".bin") return parse_ws_bin((data), opts, idx, rels, wb, themes, styles);
  7597. return parse_ws_xml((data), opts, idx, rels, wb, themes, styles);
  7598. }
  7599. function parse_cs(data, name, idx, opts, rels, wb, themes, styles) {
  7600. if(name.slice(-4)===".bin") return parse_cs_bin((data), opts, idx, rels, wb, themes, styles);
  7601. return parse_cs_xml((data), opts, idx, rels, wb, themes, styles);
  7602. }
  7603. function parse_ms(data, name, idx, opts, rels, wb, themes, styles) {
  7604. if(name.slice(-4)===".bin") return parse_ms_bin((data), opts, idx, rels, wb, themes, styles);
  7605. return parse_ms_xml((data), opts, idx, rels, wb, themes, styles);
  7606. }
  7607. function parse_ds(data, name, idx, opts, rels, wb, themes, styles) {
  7608. if(name.slice(-4)===".bin") return parse_ds_bin((data), opts, idx, rels, wb, themes, styles);
  7609. return parse_ds_xml((data), opts, idx, rels, wb, themes, styles);
  7610. }
  7611. function parse_sty(data, name, themes, opts) {
  7612. if(name.slice(-4)===".bin") return parse_sty_bin((data), themes, opts);
  7613. return parse_sty_xml((data), themes, opts);
  7614. }
  7615. function parse_theme(data, name, opts) {
  7616. return parse_theme_xml(data, opts);
  7617. }
  7618. function parse_sst(data, name, opts) {
  7619. if(name.slice(-4)===".bin") return parse_sst_bin((data), opts);
  7620. return parse_sst_xml((data), opts);
  7621. }
  7622. function parse_cmnt(data, name, opts) {
  7623. if(name.slice(-4)===".bin") return parse_comments_bin((data), opts);
  7624. return parse_comments_xml((data), opts);
  7625. }
  7626. function parse_cc(data, name, opts) {
  7627. if(name.slice(-4)===".bin") return parse_cc_bin((data), name, opts);
  7628. return parse_cc_xml((data), name, opts);
  7629. }
  7630. function parse_xlink(data, rel, name, opts) {
  7631. if(name.slice(-4)===".bin") return parse_xlink_bin((data), rel, name, opts);
  7632. return parse_xlink_xml((data), rel, name, opts);
  7633. }
  7634. function write_wb(wb, name, opts) {
  7635. return (name.slice(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
  7636. }
  7637. function write_ws(data, name, opts, wb, rels) {
  7638. return (name.slice(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb, rels);
  7639. }
  7640. // eslint-disable-next-line no-unused-vars
  7641. function write_cs(data, name, opts, wb, rels) {
  7642. return (name.slice(-4)===".bin" ? write_cs_bin : write_cs_xml)(data, opts, wb, rels);
  7643. }
  7644. function write_sty(data, name, opts) {
  7645. return (name.slice(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
  7646. }
  7647. function write_sst(data, name, opts) {
  7648. return (name.slice(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
  7649. }
  7650. function write_cmnt(data, name, opts) {
  7651. return (name.slice(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
  7652. }
  7653. /*
  7654. function write_cc(data, name:string, opts) {
  7655. return (name.slice(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
  7656. }
  7657. */
  7658. /* note: browser DOM element cannot see mso- style attrs, must parse */
  7659. var HTML_ = (function() {
  7660. function html_to_sheet(str, _opts) {
  7661. var opts = _opts || {};
  7662. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  7663. var ws = opts.dense ? ([]) : ({});
  7664. str = str.replace(/<!--.*?-->/g, "");
  7665. var mtch = str.match(/<table/i);
  7666. if(!mtch) throw new Error("Invalid HTML: could not find <table>");
  7667. var mtch2 = str.match(/<\/table/i);
  7668. var i = mtch.index, j = mtch2 && mtch2.index || str.length;
  7669. var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
  7670. var R = -1, C = 0, RS = 0, CS = 0;
  7671. var range = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
  7672. var merges = [];
  7673. for(i = 0; i < rows.length; ++i) {
  7674. var row = rows[i].trim();
  7675. var hd = row.slice(0,3).toLowerCase();
  7676. if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
  7677. if(hd != "<td" && hd != "<th") continue;
  7678. var cells = row.split(/<\/t[dh]>/i);
  7679. for(j = 0; j < cells.length; ++j) {
  7680. var cell = cells[j].trim();
  7681. if(!cell.match(/<t[dh]/i)) continue;
  7682. var m = cell, cc = 0;
  7683. /* TODO: parse styles etc */
  7684. while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
  7685. for(var midx = 0; midx < merges.length; ++midx) {
  7686. var _merge = merges[midx];
  7687. if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
  7688. }
  7689. var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
  7690. CS = tag.colspan ? +tag.colspan : 1;
  7691. if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
  7692. var _t = tag.t || "";
  7693. /* TODO: generate stub cells */
  7694. if(!m.length) { C += CS; continue; }
  7695. m = htmldecode(m);
  7696. if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
  7697. if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
  7698. if(!m.length) continue;
  7699. var o = {t:'s', v:m};
  7700. if(opts.raw || !m.trim().length || _t == 's'){}
  7701. else if(m === 'TRUE') o = {t:'b', v:true};
  7702. else if(m === 'FALSE') o = {t:'b', v:false};
  7703. else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
  7704. else if(!isNaN(fuzzydate(m).getDate())) {
  7705. o = ({t:'d', v:parseDate(m)});
  7706. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  7707. o.z = opts.dateNF || SSF._table[14];
  7708. }
  7709. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
  7710. else ws[encode_cell({r:R, c:C})] = o;
  7711. C += CS;
  7712. }
  7713. }
  7714. ws['!ref'] = encode_range(range);
  7715. if(merges.length) ws["!merges"] = merges;
  7716. return ws;
  7717. }
  7718. function html_to_book(str, opts) {
  7719. return sheet_to_workbook(html_to_sheet(str, opts), opts);
  7720. }
  7721. function make_html_row(ws, r, R, o) {
  7722. var M = (ws['!merges'] ||[]);
  7723. var oo = [];
  7724. for(var C = r.s.c; C <= r.e.c; ++C) {
  7725. var RS = 0, CS = 0;
  7726. for(var j = 0; j < M.length; ++j) {
  7727. if(M[j].s.r > R || M[j].s.c > C) continue;
  7728. if(M[j].e.r < R || M[j].e.c < C) continue;
  7729. if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
  7730. RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
  7731. }
  7732. if(RS < 0) continue;
  7733. var coord = encode_cell({r:R,c:C});
  7734. var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
  7735. /* TODO: html entities */
  7736. var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
  7737. var sp = ({});
  7738. if(RS > 1) sp.rowspan = RS;
  7739. if(CS > 1) sp.colspan = CS;
  7740. sp.t = cell && cell.t || 'z';
  7741. if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
  7742. sp.id = (o.id || "sjs") + "-" + coord;
  7743. if(sp.t != "z") { sp.v = cell.v; if(cell.z != null) sp.z = cell.z; }
  7744. oo.push(writextag('td', w, sp));
  7745. }
  7746. var preamble = "<tr>";
  7747. return preamble + oo.join("") + "</tr>";
  7748. }
  7749. function make_html_preamble(ws, R, o) {
  7750. var out = [];
  7751. return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
  7752. }
  7753. var _BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
  7754. var _END = '</body></html>';
  7755. function sheet_to_html(ws, opts/*, wb:?Workbook*/) {
  7756. var o = opts || {};
  7757. var header = o.header != null ? o.header : _BEGIN;
  7758. var footer = o.footer != null ? o.footer : _END;
  7759. var out = [header];
  7760. var r = decode_range(ws['!ref']);
  7761. o.dense = Array.isArray(ws);
  7762. out.push(make_html_preamble(ws, r, o));
  7763. for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
  7764. out.push("</table>" + footer);
  7765. return out.join("");
  7766. }
  7767. return {
  7768. to_workbook: html_to_book,
  7769. to_sheet: html_to_sheet,
  7770. _row: make_html_row,
  7771. BEGIN: _BEGIN,
  7772. END: _END,
  7773. _preamble: make_html_preamble,
  7774. from_sheet: sheet_to_html
  7775. };
  7776. })();
  7777. function sheet_add_dom(ws, table, _opts) {
  7778. var opts = _opts || {};
  7779. if(DENSE != null) opts.dense = DENSE;
  7780. var or_R = 0, or_C = 0;
  7781. if(opts.origin != null) {
  7782. if(typeof opts.origin == 'number') or_R = opts.origin;
  7783. else {
  7784. var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
  7785. or_R = _origin.r; or_C = _origin.c;
  7786. }
  7787. }
  7788. var rows = table.getElementsByTagName('tr');
  7789. var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
  7790. var range = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
  7791. if(ws["!ref"]) {
  7792. var _range = decode_range(ws["!ref"]);
  7793. range.s.r = Math.min(range.s.r, _range.s.r);
  7794. range.s.c = Math.min(range.s.c, _range.s.c);
  7795. range.e.r = Math.max(range.e.r, _range.e.r);
  7796. range.e.c = Math.max(range.e.c, _range.e.c);
  7797. if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
  7798. }
  7799. var merges = [], midx = 0;
  7800. var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  7801. var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  7802. if(!ws["!cols"]) ws['!cols'] = [];
  7803. for(; _R < rows.length && R < sheetRows; ++_R) {
  7804. var row = rows[_R];
  7805. if (is_dom_element_hidden(row)) {
  7806. if (opts.display) continue;
  7807. rowinfo[R] = {hidden: true};
  7808. }
  7809. var elts = (row.children);
  7810. for(_C = C = 0; _C < elts.length; ++_C) {
  7811. var elt = elts[_C];
  7812. if (opts.display && is_dom_element_hidden(elt)) continue;
  7813. var v = elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
  7814. var z = elt.getAttribute('z');
  7815. for(midx = 0; midx < merges.length; ++midx) {
  7816. var m = merges[midx];
  7817. 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; }
  7818. }
  7819. /* TODO: figure out how to extract nonstandard mso- style */
  7820. CS = +elt.getAttribute("colspan") || 1;
  7821. 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}});
  7822. var o = {t:'s', v:v};
  7823. var _t = elt.getAttribute("t") || "";
  7824. if(v != null) {
  7825. if(v.length == 0) o.t = _t || 'z';
  7826. else if(opts.raw || v.trim().length == 0 || _t == "s"){}
  7827. else if(v === 'TRUE') o = {t:'b', v:true};
  7828. else if(v === 'FALSE') o = {t:'b', v:false};
  7829. else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
  7830. else if(!isNaN(fuzzydate(v).getDate())) {
  7831. o = ({t:'d', v:parseDate(v)});
  7832. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  7833. o.z = opts.dateNF || SSF._table[14];
  7834. }
  7835. }
  7836. if(o.z === undefined && z != null) o.z = z;
  7837. if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
  7838. else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
  7839. if(range.e.c < C + or_C) range.e.c = C + or_C;
  7840. C += CS;
  7841. }
  7842. ++R;
  7843. }
  7844. if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
  7845. range.e.r = Math.max(range.e.r, R - 1 + or_R);
  7846. ws['!ref'] = encode_range(range);
  7847. 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
  7848. return ws;
  7849. }
  7850. function parse_dom_table(table, _opts) {
  7851. var opts = _opts || {};
  7852. var ws = opts.dense ? ([]) : ({});
  7853. return sheet_add_dom(ws, table, _opts);
  7854. }
  7855. function table_to_book(table, opts) {
  7856. return sheet_to_workbook(parse_dom_table(table, opts), opts);
  7857. }
  7858. function is_dom_element_hidden(element) {
  7859. var display = '';
  7860. var get_computed_style = get_get_computed_style_function(element);
  7861. if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
  7862. 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)
  7863. return display === 'none';
  7864. }
  7865. /* global getComputedStyle */
  7866. function get_get_computed_style_function(element) {
  7867. // The proper getComputedStyle implementation is the one defined in the element window
  7868. if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
  7869. // If it is not available, try to get one from the global namespace
  7870. if(typeof getComputedStyle === 'function') return getComputedStyle;
  7871. return null;
  7872. }
  7873. function write_sheet_index(wb, sheet) {
  7874. if(!sheet) return 0;
  7875. var idx = wb.SheetNames.indexOf(sheet);
  7876. if(idx == -1) throw new Error("Sheet not found: " + sheet);
  7877. return idx;
  7878. }
  7879. function write_obj_str(factory) {
  7880. return function write_str(wb, o) {
  7881. var idx = write_sheet_index(wb, o.sheet);
  7882. return factory.from_sheet(wb.Sheets[wb.SheetNames[idx]], o, wb);
  7883. };
  7884. }
  7885. var write_htm_str = write_obj_str(HTML_);
  7886. var write_csv_str = write_obj_str({from_sheet:sheet_to_csv});
  7887. var write_slk_str = write_obj_str(typeof SYLK !== "undefined" ? SYLK : {});
  7888. var write_dif_str = write_obj_str(typeof DIF !== "undefined" ? DIF : {});
  7889. var write_prn_str = write_obj_str(typeof PRN !== "undefined" ? PRN : {});
  7890. var write_rtf_str = write_obj_str(typeof RTF !== "undefined" ? RTF : {});
  7891. var write_txt_str = write_obj_str({from_sheet:sheet_to_txt});
  7892. var write_dbf_buf = write_obj_str(typeof DBF !== "undefined" ? DBF : {});
  7893. var write_eth_str = write_obj_str(typeof ETH !== "undefined" ? ETH : {});
  7894. function fix_opts_func(defaults) {
  7895. return function fix_opts(opts) {
  7896. for(var i = 0; i != defaults.length; ++i) {
  7897. var d = defaults[i];
  7898. if(opts[d[0]] === undefined) opts[d[0]] = d[1];
  7899. if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
  7900. }
  7901. };
  7902. }
  7903. var fix_read_opts = function(opts) {
  7904. fix_opts_func([
  7905. ['cellNF', false], /* emit cell number format string as .z */
  7906. ['cellHTML', true], /* emit html string as .h */
  7907. ['cellFormula', true], /* emit formulae as .f */
  7908. ['cellStyles', false], /* emits style/theme as .s */
  7909. ['cellText', true], /* emit formatted text as .w */
  7910. ['cellDates', false], /* emit date cells with type `d` */
  7911. ['sheetStubs', false], /* emit empty cells */
  7912. ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
  7913. ['bookDeps', false], /* parse calculation chains */
  7914. ['bookSheets', false], /* only try to get sheet names (no Sheets) */
  7915. ['bookProps', false], /* only try to get properties (no Sheets) */
  7916. ['bookFiles', false], /* include raw file structure (keys, files, cfb) */
  7917. ['bookVBA', false], /* include vba raw data (vbaraw) */
  7918. ['password',''], /* password */
  7919. ['WTF', false] /* WTF mode (throws errors) */
  7920. ])(opts);
  7921. };
  7922. var fix_write_opts = fix_opts_func([
  7923. ['cellDates', false], /* write date cells with type `d` */
  7924. ['bookSST', false], /* Generate Shared String Table */
  7925. ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
  7926. ['compression', false], /* Use file compression */
  7927. ['WTF', false] /* WTF mode (throws errors) */
  7928. ]);
  7929. function get_sheet_type(n) {
  7930. if(RELS.WS.indexOf(n) > -1) return "sheet";
  7931. if(RELS.CS && n == RELS.CS) return "chart";
  7932. if(RELS.DS && n == RELS.DS) return "dialog";
  7933. if(RELS.MS && n == RELS.MS) return "macro";
  7934. return (n && n.length) ? n : "sheet";
  7935. }
  7936. function safe_parse_wbrels(wbrels, sheets) {
  7937. if(!wbrels) return 0;
  7938. try {
  7939. 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)]; });
  7940. } catch(e) { return null; }
  7941. return !wbrels || wbrels.length === 0 ? null : wbrels;
  7942. }
  7943. function safe_parse_sheet(zip, path, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles) {
  7944. try {
  7945. sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
  7946. var data = getzipdata(zip, path);
  7947. var _ws;
  7948. switch(stype) {
  7949. case 'sheet': _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  7950. case 'chart': _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
  7951. if(!_ws || !_ws['!drawel']) break;
  7952. var dfile = resolve_path(_ws['!drawel'].Target, path);
  7953. var drelsp = get_rels_path(dfile);
  7954. var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
  7955. var chartp = resolve_path(draw, dfile);
  7956. var crelsp = get_rels_path(chartp);
  7957. _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
  7958. break;
  7959. case 'macro': _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  7960. case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  7961. default: throw new Error("Unrecognized sheet type " + stype);
  7962. }
  7963. sheets[sheet] = _ws;
  7964. /* scan rels for comments */
  7965. var comments = [];
  7966. if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
  7967. if(sheetRels[sheet][n].Type == RELS.CMNT) {
  7968. var dfile = resolve_path(sheetRels[sheet][n].Target, path);
  7969. comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
  7970. if(!comments || !comments.length) return;
  7971. sheet_insert_comments(_ws, comments);
  7972. }
  7973. });
  7974. } catch(e) { if(opts.WTF) throw e; }
  7975. }
  7976. function strip_front_slash(x) { return x.charAt(0) == '/' ? x.slice(1) : x; }
  7977. function parse_zip(zip, opts) {
  7978. make_ssf(SSF);
  7979. opts = opts || {};
  7980. fix_read_opts(opts);
  7981. /* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
  7982. if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
  7983. /* UOC */
  7984. if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
  7985. /* Numbers */
  7986. if(safegetzipfile(zip, 'Index/Document.iwa')) throw new Error('Unsupported NUMBERS file');
  7987. var entries = zipentries(zip);
  7988. var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')));
  7989. var xlsb = false;
  7990. var sheets, binname;
  7991. if(dir.workbooks.length === 0) {
  7992. binname = "xl/workbook.xml";
  7993. if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
  7994. }
  7995. if(dir.workbooks.length === 0) {
  7996. binname = "xl/workbook.bin";
  7997. if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
  7998. dir.workbooks.push(binname);
  7999. xlsb = true;
  8000. }
  8001. if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  8002. var themes = ({});
  8003. var styles = ({});
  8004. if(!opts.bookSheets && !opts.bookProps) {
  8005. strs = [];
  8006. if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }
  8007. if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"",dir.themes[0], opts);
  8008. if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  8009. }
  8010. /*var externbooks = */dir.links.map(function(link) {
  8011. try {
  8012. var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
  8013. return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
  8014. } catch(e) {}
  8015. });
  8016. var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  8017. var props = {}, propdata = "";
  8018. if(dir.coreprops.length) {
  8019. propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
  8020. if(propdata) props = parse_core_props(propdata);
  8021. if(dir.extprops.length !== 0) {
  8022. propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
  8023. if(propdata) parse_ext_props(propdata, props, opts);
  8024. }
  8025. }
  8026. var custprops = {};
  8027. if(!opts.bookSheets || opts.bookProps) {
  8028. if (dir.custprops.length !== 0) {
  8029. propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
  8030. if(propdata) custprops = parse_cust_props(propdata, opts);
  8031. }
  8032. }
  8033. var out = ({});
  8034. if(opts.bookSheets || opts.bookProps) {
  8035. if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
  8036. else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
  8037. if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
  8038. if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
  8039. if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  8040. }
  8041. sheets = {};
  8042. var deps = {};
  8043. if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);
  8044. var i=0;
  8045. var sheetRels = ({});
  8046. var path, relsPath;
  8047. {
  8048. var wbsheets = wb.Sheets;
  8049. props.Worksheets = wbsheets.length;
  8050. props.SheetNames = [];
  8051. for(var j = 0; j != wbsheets.length; ++j) {
  8052. props.SheetNames[j] = wbsheets[j].name;
  8053. }
  8054. }
  8055. var wbext = xlsb ? "bin" : "xml";
  8056. var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  8057. var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
  8058. if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
  8059. var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile);
  8060. if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  8061. /* Numbers iOS hack */
  8062. var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
  8063. wsloop: for(i = 0; i != props.Worksheets; ++i) {
  8064. var stype = "sheet";
  8065. if(wbrels && wbrels[i]) {
  8066. path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
  8067. if(!safegetzipfile(zip, path)) path = wbrels[i][1];
  8068. if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
  8069. stype = wbrels[i][2];
  8070. } else {
  8071. path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
  8072. path = path.replace(/sheet0\./,"sheet.");
  8073. }
  8074. relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
  8075. if(opts && opts.sheets != null) switch(typeof opts.sheets) {
  8076. case "number": if(i != opts.sheets) continue wsloop; break;
  8077. case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
  8078. default: if(Array.isArray && Array.isArray(opts.sheets)) {
  8079. var snjseen = false;
  8080. for(var snj = 0; snj != opts.sheets.length; ++snj) {
  8081. if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
  8082. if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
  8083. }
  8084. if(!snjseen) continue wsloop;
  8085. }
  8086. }
  8087. safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
  8088. }
  8089. out = ({
  8090. Directory: dir,
  8091. Workbook: wb,
  8092. Props: props,
  8093. Custprops: custprops,
  8094. Deps: deps,
  8095. Sheets: sheets,
  8096. SheetNames: props.SheetNames,
  8097. Strings: strs,
  8098. Styles: styles,
  8099. Themes: themes,
  8100. SSF: SSF.get_table()
  8101. });
  8102. if(opts && opts.bookFiles) {
  8103. out.keys = entries;
  8104. out.files = zip.files;
  8105. }
  8106. if(opts && opts.bookVBA) {
  8107. if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
  8108. else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
  8109. }
  8110. return out;
  8111. }
  8112. /* [MS-OFFCRYPTO] 2.1.1 */
  8113. function parse_xlsxcfb(cfb, _opts) {
  8114. var opts = _opts || {};
  8115. var f = 'Workbook', data = CFB.find(cfb, f);
  8116. try {
  8117. f = '/!DataSpaces/Version';
  8118. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  8119. /*var version = */parse_DataSpaceVersionInfo(data.content);
  8120. /* 2.3.4.1 */
  8121. f = '/!DataSpaces/DataSpaceMap';
  8122. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  8123. var dsm = parse_DataSpaceMap(data.content);
  8124. 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")
  8125. throw new Error("ECMA-376 Encrypted file bad " + f);
  8126. /* 2.3.4.2 */
  8127. f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
  8128. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  8129. var seds = parse_DataSpaceDefinition(data.content);
  8130. if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
  8131. throw new Error("ECMA-376 Encrypted file bad " + f);
  8132. /* 2.3.4.3 */
  8133. f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
  8134. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  8135. /*var hdr = */parse_Primary(data.content);
  8136. } catch(e) {}
  8137. f = '/EncryptionInfo';
  8138. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  8139. var einfo = parse_EncryptionInfo(data.content);
  8140. /* 2.3.4.4 */
  8141. f = '/EncryptedPackage';
  8142. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  8143. /*global decrypt_agile */
  8144. if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  8145. /*global decrypt_std76 */
  8146. if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  8147. throw new Error("File is password-protected");
  8148. }
  8149. function write_zip(wb, opts) {
  8150. _shapeid = 1024;
  8151. if(opts.bookType == "ods") return write_ods(wb, opts);
  8152. if(wb && !wb.SSF) {
  8153. wb.SSF = SSF.get_table();
  8154. }
  8155. if(wb && wb.SSF) {
  8156. make_ssf(SSF); SSF.load_table(wb.SSF);
  8157. // $FlowIgnore
  8158. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  8159. opts.ssf = wb.SSF;
  8160. }
  8161. opts.rels = {}; opts.wbrels = {};
  8162. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  8163. if(browser_has_Map) opts.revStrings = new Map();
  8164. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  8165. var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
  8166. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  8167. var ct = new_ct();
  8168. fix_write_opts(opts = opts || {});
  8169. var zip = zip_new();
  8170. var f = "", rId = 0;
  8171. opts.cellXfs = [];
  8172. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  8173. if(!wb.Props) wb.Props = {};
  8174. f = "docProps/core.xml";
  8175. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  8176. ct.coreprops.push(f);
  8177. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  8178. f = "docProps/app.xml";
  8179. if(wb.Props && wb.Props.SheetNames){/* empty */}
  8180. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  8181. else {
  8182. var _sn = [];
  8183. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  8184. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  8185. wb.Props.SheetNames = _sn;
  8186. }
  8187. wb.Props.Worksheets = wb.Props.SheetNames.length;
  8188. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  8189. ct.extprops.push(f);
  8190. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  8191. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  8192. f = "docProps/custom.xml";
  8193. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  8194. ct.custprops.push(f);
  8195. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  8196. }
  8197. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  8198. var wsrels = {'!id':{}};
  8199. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  8200. var _type = (ws || {})["!type"] || "sheet";
  8201. switch(_type) {
  8202. case "chart":
  8203. /* falls through */
  8204. default:
  8205. f = "xl/worksheets/sheet" + rId + "." + wbext;
  8206. zip_add_file(zip, f, write_ws(rId-1, f, opts, wb, wsrels));
  8207. ct.sheets.push(f);
  8208. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  8209. }
  8210. if(ws) {
  8211. var comments = ws['!comments'];
  8212. var need_vml = false;
  8213. if(comments && comments.length > 0) {
  8214. var cf = "xl/comments" + rId + "." + wbext;
  8215. zip_add_file(zip, cf, write_cmnt(comments, cf, opts));
  8216. ct.comments.push(cf);
  8217. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  8218. need_vml = true;
  8219. }
  8220. if(ws['!legacy']) {
  8221. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
  8222. }
  8223. delete ws['!comments'];
  8224. delete ws['!legacy'];
  8225. }
  8226. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  8227. }
  8228. if(opts.Strings != null && opts.Strings.length > 0) {
  8229. f = "xl/sharedStrings." + wbext;
  8230. zip_add_file(zip, f, write_sst(opts.Strings, f, opts));
  8231. ct.strs.push(f);
  8232. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  8233. }
  8234. f = "xl/workbook." + wbext;
  8235. zip_add_file(zip, f, write_wb(wb, f, opts));
  8236. ct.workbooks.push(f);
  8237. add_rels(opts.rels, 1, f, RELS.WB);
  8238. /* TODO: something more intelligent with themes */
  8239. f = "xl/theme/theme1.xml";
  8240. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  8241. ct.themes.push(f);
  8242. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  8243. /* TODO: something more intelligent with styles */
  8244. f = "xl/styles." + wbext;
  8245. zip_add_file(zip, f, write_sty(wb, f, opts));
  8246. ct.styles.push(f);
  8247. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  8248. if(wb.vbaraw && vbafmt) {
  8249. f = "xl/vbaProject.bin";
  8250. zip_add_file(zip, f, wb.vbaraw);
  8251. ct.vba.push(f);
  8252. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  8253. }
  8254. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  8255. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  8256. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  8257. delete opts.revssf; delete opts.ssf;
  8258. return zip;
  8259. }
  8260. function firstbyte(f,o) {
  8261. var x = "";
  8262. switch((o||{}).type || "base64") {
  8263. case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  8264. case 'base64': x = Base64.decode(f.slice(0,12)); break;
  8265. case 'binary': x = f; break;
  8266. case 'array': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  8267. default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
  8268. }
  8269. 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)];
  8270. }
  8271. function read_cfb(cfb, opts) {
  8272. if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  8273. return parse_xlscfb(cfb, opts);
  8274. }
  8275. function read_zip(data, opts) {
  8276. var zip, d = data;
  8277. var o = opts||{};
  8278. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  8279. zip = zip_read(d, o);
  8280. return parse_zip(zip, o);
  8281. }
  8282. function read_plaintext(data, o) {
  8283. var i = 0;
  8284. main: while(i < data.length) switch(data.charCodeAt(i)) {
  8285. case 0x0A: case 0x0D: case 0x20: ++i; break;
  8286. case 0x3C: return parse_xlml(data.slice(i),o);
  8287. default: break main;
  8288. }
  8289. return PRN.to_workbook(data, o);
  8290. }
  8291. function read_plaintext_raw(data, o) {
  8292. var str = "", bytes = firstbyte(data, o);
  8293. switch(o.type) {
  8294. case 'base64': str = Base64.decode(data); break;
  8295. case 'binary': str = data; break;
  8296. case 'buffer': str = data.toString('binary'); break;
  8297. case 'array': str = cc2str(data); break;
  8298. default: throw new Error("Unrecognized type " + o.type);
  8299. }
  8300. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
  8301. return read_plaintext(str, o);
  8302. }
  8303. function read_utf16(data, o) {
  8304. var d = data;
  8305. if(o.type == 'base64') d = Base64.decode(d);
  8306. d = cptable.utils.decode(1200, d.slice(2), 'str');
  8307. o.type = "binary";
  8308. return read_plaintext(d, o);
  8309. }
  8310. function bstrify(data) {
  8311. return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
  8312. }
  8313. function read_prn(data, d, o, str) {
  8314. if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
  8315. return PRN.to_workbook(d, o);
  8316. }
  8317. function readSync(data, opts) {
  8318. reset_cp();
  8319. if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), opts);
  8320. var d = data, n = [0,0,0,0], str = false;
  8321. var o = opts||{};
  8322. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  8323. _ssfopts = {};
  8324. if(o.dateNF) _ssfopts.dateNF = o.dateNF;
  8325. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  8326. if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); }
  8327. if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
  8328. if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
  8329. // $FlowIgnore
  8330. var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
  8331. // $FlowIgnore
  8332. if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
  8333. }
  8334. switch((n = firstbyte(d, o))[0]) {
  8335. 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;
  8336. case 0x09: if(n[1] <= 0x04) return parse_xlscfb(d, o); break;
  8337. case 0x3C: return parse_xlml(d, o);
  8338. case 0x49: if(n[1] === 0x44) return read_wb_ID(d, o); break;
  8339. case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
  8340. case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
  8341. case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
  8342. case 0xFF: if(n[1] === 0xFE) { return read_utf16(d, o); } break;
  8343. case 0x00: if(n[1] === 0x00 && n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o); break;
  8344. case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
  8345. case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return RTF.to_workbook(d, o); break;
  8346. case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
  8347. }
  8348. if(DBF.versions.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
  8349. return read_prn(data, d, o, str);
  8350. }
  8351. function readFileSync(filename, opts) {
  8352. var o = opts||{}; o.type = 'file';
  8353. return readSync(filename, o);
  8354. }
  8355. function write_cfb_ctr(cfb, o) {
  8356. switch(o.type) {
  8357. case "base64": case "binary": break;
  8358. case "buffer": case "array": o.type = ""; break;
  8359. case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
  8360. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  8361. default: throw new Error("Unrecognized type " + o.type);
  8362. }
  8363. return CFB.write(cfb, o);
  8364. }
  8365. function write_zip_type(wb, opts) {
  8366. var o = opts||{};
  8367. var z = write_zip(wb, o);
  8368. var oopts = {};
  8369. if(o.compression) oopts.compression = 'DEFLATE';
  8370. if(o.password) oopts.type = has_buf ? "nodebuffer" : "string";
  8371. else switch(o.type) {
  8372. case "base64": oopts.type = "base64"; break;
  8373. case "binary": oopts.type = "string"; break;
  8374. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  8375. case "buffer":
  8376. case "file": oopts.type = has_buf ? "nodebuffer" : "string"; break;
  8377. default: throw new Error("Unrecognized type " + o.type);
  8378. }
  8379. var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: {"nodebuffer": "buffer", "string": "binary"}[oopts.type] || oopts.type}) : z.generate(oopts);
  8380. /*jshint -W083 */
  8381. if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
  8382. /*jshint +W083 */
  8383. if(o.type === "file") return write_dl(o.file, out);
  8384. return o.type == "string" ? utf8read(out) : out;
  8385. }
  8386. function write_cfb_type(wb, opts) {
  8387. var o = opts||{};
  8388. var cfb = write_xlscfb(wb, o);
  8389. return write_cfb_ctr(cfb, o);
  8390. }
  8391. function write_string_type(out, opts, bom) {
  8392. if(!bom) bom = "";
  8393. var o = bom + out;
  8394. switch(opts.type) {
  8395. case "base64": return Base64.encode(utf8write(o));
  8396. case "binary": return utf8write(o);
  8397. case "string": return out;
  8398. case "file": return write_dl(opts.file, o, 'utf8');
  8399. case "buffer": {
  8400. if(has_buf) return Buffer_from(o, 'utf8');
  8401. else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
  8402. }
  8403. }
  8404. throw new Error("Unrecognized type " + opts.type);
  8405. }
  8406. function write_stxt_type(out, opts) {
  8407. switch(opts.type) {
  8408. case "base64": return Base64.encode(out);
  8409. case "binary": return out;
  8410. case "string": return out; /* override in sheet_to_txt */
  8411. case "file": return write_dl(opts.file, out, 'binary');
  8412. case "buffer": {
  8413. if(has_buf) return Buffer_from(out, 'binary');
  8414. else return out.split("").map(function(c) { return c.charCodeAt(0); });
  8415. }
  8416. }
  8417. throw new Error("Unrecognized type " + opts.type);
  8418. }
  8419. /* TODO: test consistency */
  8420. function write_binary_type(out, opts) {
  8421. switch(opts.type) {
  8422. case "string":
  8423. case "base64":
  8424. case "binary":
  8425. var bstr = "";
  8426. // $FlowIgnore
  8427. for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
  8428. return opts.type == 'base64' ? Base64.encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
  8429. case "file": return write_dl(opts.file, out);
  8430. case "buffer": return out;
  8431. default: throw new Error("Unrecognized type " + opts.type);
  8432. }
  8433. }
  8434. function writeSync(wb, opts) {
  8435. reset_cp();
  8436. check_wb(wb);
  8437. var o = opts||{};
  8438. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  8439. if(o.type == "array") { o.type = "binary"; var out = (writeSync(wb, o)); o.type = "array"; return s2ab(out); }
  8440. switch(o.bookType || 'xlsb') {
  8441. case 'xml':
  8442. case 'xlml': return write_string_type(write_xlml(wb, o), o);
  8443. case 'slk':
  8444. case 'sylk': return write_string_type(write_slk_str(wb, o), o);
  8445. case 'htm':
  8446. case 'html': return write_string_type(write_htm_str(wb, o), o);
  8447. case 'txt': return write_stxt_type(write_txt_str(wb, o), o);
  8448. case 'csv': return write_string_type(write_csv_str(wb, o), o, "\ufeff");
  8449. case 'dif': return write_string_type(write_dif_str(wb, o), o);
  8450. case 'dbf': return write_binary_type(write_dbf_buf(wb, o), o);
  8451. case 'prn': return write_string_type(write_prn_str(wb, o), o);
  8452. case 'rtf': return write_string_type(write_rtf_str(wb, o), o);
  8453. case 'eth': return write_string_type(write_eth_str(wb, o), o);
  8454. case 'fods': return write_string_type(write_ods(wb, o), o);
  8455. case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
  8456. case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
  8457. case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
  8458. case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
  8459. case 'biff8':
  8460. case 'xla':
  8461. case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
  8462. case 'xlsx':
  8463. case 'xlsm':
  8464. case 'xlam':
  8465. case 'xlsb':
  8466. case 'ods': return write_zip_type(wb, o);
  8467. default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
  8468. }
  8469. }
  8470. function resolve_book_type(o) {
  8471. if(o.bookType) return;
  8472. var _BT = {
  8473. "xls": "biff8",
  8474. "htm": "html",
  8475. "slk": "sylk",
  8476. "socialcalc": "eth",
  8477. "Sh33tJS": "WTF"
  8478. };
  8479. var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
  8480. if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
  8481. o.bookType = _BT[o.bookType] || o.bookType;
  8482. }
  8483. function writeFileSync(wb, filename, opts) {
  8484. var o = opts||{}; o.type = 'file';
  8485. o.file = filename;
  8486. resolve_book_type(o);
  8487. return writeSync(wb, o);
  8488. }
  8489. function writeFileAsync(filename, wb, opts, cb) {
  8490. var o = opts||{}; o.type = 'file';
  8491. o.file = filename;
  8492. resolve_book_type(o);
  8493. o.type = 'buffer';
  8494. var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts);
  8495. return _fs.writeFile(filename, writeSync(wb, o), _cb);
  8496. }
  8497. function make_json_row(sheet, r, R, cols, header, hdr, dense, o) {
  8498. var rr = encode_row(R);
  8499. var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
  8500. var isempty = true;
  8501. var row = (header === 1) ? [] : {};
  8502. if(header !== 1) {
  8503. if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
  8504. else row.__rowNum__ = R;
  8505. }
  8506. if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
  8507. var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  8508. if(val === undefined || val.t === undefined) {
  8509. if(defval === undefined) continue;
  8510. if(hdr[C] != null) { row[hdr[C]] = defval; }
  8511. continue;
  8512. }
  8513. var v = val.v;
  8514. switch(val.t){
  8515. case 'z': if(v == null) break; continue;
  8516. case 'e': v = void 0; break;
  8517. case 's': case 'd': case 'b': case 'n': break;
  8518. default: throw new Error('unrecognized type ' + val.t);
  8519. }
  8520. if(hdr[C] != null) {
  8521. if(v == null) {
  8522. if(defval !== undefined) row[hdr[C]] = defval;
  8523. else if(raw && v === null) row[hdr[C]] = null;
  8524. else continue;
  8525. } else {
  8526. row[hdr[C]] = raw || (o.rawNumbers && val.t == "n") ? v : format_cell(val,v,o);
  8527. }
  8528. if(v != null) isempty = false;
  8529. }
  8530. }
  8531. return { row: row, isempty: isempty };
  8532. }
  8533. function sheet_to_json(sheet, opts) {
  8534. if(sheet == null || sheet["!ref"] == null) return [];
  8535. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  8536. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  8537. var o = opts || {};
  8538. var range = o.range != null ? o.range : sheet["!ref"];
  8539. if(o.header === 1) header = 1;
  8540. else if(o.header === "A") header = 2;
  8541. else if(Array.isArray(o.header)) header = 3;
  8542. else if(o.header == null) header = 0;
  8543. switch(typeof range) {
  8544. case 'string': r = safe_decode_range(range); break;
  8545. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  8546. default: r = range;
  8547. }
  8548. if(header > 0) offset = 0;
  8549. var rr = encode_row(r.s.r);
  8550. var cols = [];
  8551. var out = [];
  8552. var outi = 0, counter = 0;
  8553. var dense = Array.isArray(sheet);
  8554. var R = r.s.r, C = 0, CC = 0;
  8555. if(dense && !sheet[R]) sheet[R] = [];
  8556. for(C = r.s.c; C <= r.e.c; ++C) {
  8557. cols[C] = encode_col(C);
  8558. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  8559. switch(header) {
  8560. case 1: hdr[C] = C - r.s.c; break;
  8561. case 2: hdr[C] = cols[C]; break;
  8562. case 3: hdr[C] = o.header[C - r.s.c]; break;
  8563. default:
  8564. if(val == null) val = {w: "__EMPTY", t: "s"};
  8565. vv = v = format_cell(val, null, o);
  8566. counter = 0;
  8567. for(CC = 0; CC < hdr.length; ++CC) if(hdr[CC] == vv) vv = v + "_" + (++counter);
  8568. hdr[C] = vv;
  8569. }
  8570. }
  8571. for (R = r.s.r + offset; R <= r.e.r; ++R) {
  8572. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  8573. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
  8574. }
  8575. out.length = outi;
  8576. return out;
  8577. }
  8578. var qreg = /"/g;
  8579. function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
  8580. var isempty = true;
  8581. var row = [], txt = "", rr = encode_row(R);
  8582. for(var C = r.s.c; C <= r.e.c; ++C) {
  8583. if (!cols[C]) continue;
  8584. var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
  8585. if(val == null) txt = "";
  8586. else if(val.v != null) {
  8587. isempty = false;
  8588. txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
  8589. 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; }
  8590. if(txt == "ID") txt = '"ID"';
  8591. } else if(val.f != null && !val.F) {
  8592. isempty = false;
  8593. txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
  8594. } else txt = "";
  8595. /* NOTE: Excel CSV does not support array formulae */
  8596. row.push(txt);
  8597. }
  8598. if(o.blankrows === false && isempty) return null;
  8599. return row.join(FS);
  8600. }
  8601. function sheet_to_csv(sheet, opts) {
  8602. var out = [];
  8603. var o = opts == null ? {} : opts;
  8604. if(sheet == null || sheet["!ref"] == null) return "";
  8605. var r = safe_decode_range(sheet["!ref"]);
  8606. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  8607. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  8608. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  8609. var row = "", cols = [];
  8610. o.dense = Array.isArray(sheet);
  8611. var colinfo = o.skipHidden && sheet["!cols"] || [];
  8612. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  8613. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  8614. for(var R = r.s.r; R <= r.e.r; ++R) {
  8615. if ((rowinfo[R]||{}).hidden) continue;
  8616. row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
  8617. if(row == null) { continue; }
  8618. if(o.strip) row = row.replace(endregex,"");
  8619. out.push(row + RS);
  8620. }
  8621. delete o.dense;
  8622. return out.join("");
  8623. }
  8624. function sheet_to_txt(sheet, opts) {
  8625. if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
  8626. var s = sheet_to_csv(sheet, opts);
  8627. if(typeof cptable == 'undefined' || opts.type == 'string') return s;
  8628. var o = cptable.utils.encode(1200, s, 'str');
  8629. return String.fromCharCode(255) + String.fromCharCode(254) + o;
  8630. }
  8631. function sheet_to_formulae(sheet) {
  8632. var y = "", x, val="";
  8633. if(sheet == null || sheet["!ref"] == null) return [];
  8634. var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
  8635. var cmds = [];
  8636. var dense = Array.isArray(sheet);
  8637. for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
  8638. for(var R = r.s.r; R <= r.e.r; ++R) {
  8639. rr = encode_row(R);
  8640. for(C = r.s.c; C <= r.e.c; ++C) {
  8641. y = cols[C] + rr;
  8642. x = dense ? (sheet[R]||[])[C] : sheet[y];
  8643. val = "";
  8644. if(x === undefined) continue;
  8645. else if(x.F != null) {
  8646. y = x.F;
  8647. if(!x.f) continue;
  8648. val = x.f;
  8649. if(y.indexOf(":") == -1) y = y + ":" + y;
  8650. }
  8651. if(x.f != null) val = x.f;
  8652. else if(x.t == 'z') continue;
  8653. else if(x.t == 'n' && x.v != null) val = "" + x.v;
  8654. else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
  8655. else if(x.w !== undefined) val = "'" + x.w;
  8656. else if(x.v === undefined) continue;
  8657. else if(x.t == 's') val = "'" + x.v;
  8658. else val = ""+x.v;
  8659. cmds[cmds.length] = y + "=" + val;
  8660. }
  8661. }
  8662. return cmds;
  8663. }
  8664. function sheet_add_json(_ws, js, opts) {
  8665. var o = opts || {};
  8666. var offset = +!o.skipHeader;
  8667. var ws = _ws || ({});
  8668. var _R = 0, _C = 0;
  8669. if(ws && o.origin != null) {
  8670. if(typeof o.origin == 'number') _R = o.origin;
  8671. else {
  8672. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  8673. _R = _origin.r; _C = _origin.c;
  8674. }
  8675. }
  8676. var cell;
  8677. var range = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}});
  8678. if(ws['!ref']) {
  8679. var _range = safe_decode_range(ws['!ref']);
  8680. range.e.c = Math.max(range.e.c, _range.e.c);
  8681. range.e.r = Math.max(range.e.r, _range.e.r);
  8682. if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
  8683. } else {
  8684. if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
  8685. }
  8686. var hdr = o.header || [], C = 0;
  8687. js.forEach(function (JS, R) {
  8688. keys(JS).forEach(function(k) {
  8689. if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
  8690. var v = JS[k];
  8691. var t = 'z';
  8692. var z = "";
  8693. var ref = encode_cell({c:_C + C,r:_R + R + offset});
  8694. cell = utils.sheet_get_cell(ws, ref);
  8695. if(v && typeof v === 'object' && !(v instanceof Date)){
  8696. ws[ref] = v;
  8697. } else {
  8698. if(typeof v == 'number') t = 'n';
  8699. else if(typeof v == 'boolean') t = 'b';
  8700. else if(typeof v == 'string') t = 's';
  8701. else if(v instanceof Date) {
  8702. t = 'd';
  8703. if(!o.cellDates) { t = 'n'; v = datenum(v); }
  8704. z = (o.dateNF || SSF._table[14]);
  8705. }
  8706. if(!cell) ws[ref] = cell = ({t:t, v:v});
  8707. else {
  8708. cell.t = t; cell.v = v;
  8709. delete cell.w; delete cell.R;
  8710. if(z) cell.z = z;
  8711. }
  8712. if(z) cell.z = z;
  8713. }
  8714. });
  8715. });
  8716. range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
  8717. var __R = encode_row(_R);
  8718. if(offset) for(C = 0; C < hdr.length; ++C) ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
  8719. ws['!ref'] = encode_range(range);
  8720. return ws;
  8721. }
  8722. function json_to_sheet(js, opts) { return sheet_add_json(null, js, opts); }
  8723. var utils = {
  8724. encode_col: encode_col,
  8725. encode_row: encode_row,
  8726. encode_cell: encode_cell,
  8727. encode_range: encode_range,
  8728. decode_col: decode_col,
  8729. decode_row: decode_row,
  8730. split_cell: split_cell,
  8731. decode_cell: decode_cell,
  8732. decode_range: decode_range,
  8733. format_cell: format_cell,
  8734. get_formulae: sheet_to_formulae,
  8735. make_csv: sheet_to_csv,
  8736. make_json: sheet_to_json,
  8737. make_formulae: sheet_to_formulae,
  8738. sheet_add_aoa: sheet_add_aoa,
  8739. sheet_add_json: sheet_add_json,
  8740. sheet_add_dom: sheet_add_dom,
  8741. aoa_to_sheet: aoa_to_sheet,
  8742. json_to_sheet: json_to_sheet,
  8743. table_to_sheet: parse_dom_table,
  8744. table_to_book: table_to_book,
  8745. sheet_to_csv: sheet_to_csv,
  8746. sheet_to_txt: sheet_to_txt,
  8747. sheet_to_json: sheet_to_json,
  8748. sheet_to_html: HTML_.from_sheet,
  8749. sheet_to_formulae: sheet_to_formulae,
  8750. sheet_to_row_object_array: sheet_to_json
  8751. };
  8752. (function(utils) {
  8753. utils.consts = utils.consts || {};
  8754. function add_consts(R/*Array<any>*/) { R.forEach(function(a){ utils.consts[a[0]] = a[1]; }); }
  8755. function get_default(x, y, z) { return x[y] != null ? x[y] : (x[y] = z); }
  8756. /* get cell, creating a stub if necessary */
  8757. function ws_get_cell_stub(ws, R, C) {
  8758. /* A1 cell address */
  8759. if(typeof R == "string") {
  8760. /* dense */
  8761. if(Array.isArray(ws)) {
  8762. var RC = decode_cell(R);
  8763. if(!ws[RC.r]) ws[RC.r] = [];
  8764. return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
  8765. }
  8766. return ws[R] || (ws[R] = {t:'z'});
  8767. }
  8768. /* cell address object */
  8769. if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
  8770. /* R and C are 0-based indices */
  8771. return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
  8772. }
  8773. utils.sheet_get_cell = ws_get_cell_stub;
  8774. /* find sheet index for given name / validate index */
  8775. function wb_sheet_idx(wb, sh) {
  8776. if(typeof sh == "number") {
  8777. if(sh >= 0 && wb.SheetNames.length > sh) return sh;
  8778. throw new Error("Cannot find sheet # " + sh);
  8779. } else if(typeof sh == "string") {
  8780. var idx = wb.SheetNames.indexOf(sh);
  8781. if(idx > -1) return idx;
  8782. throw new Error("Cannot find sheet name |" + sh + "|");
  8783. } else throw new Error("Cannot find sheet |" + sh + "|");
  8784. }
  8785. /* simple blank workbook object */
  8786. utils.book_new = function() {
  8787. return { SheetNames: [], Sheets: {} };
  8788. };
  8789. /* add a worksheet to the end of a given workbook */
  8790. utils.book_append_sheet = function(wb, ws, name) {
  8791. if(!name) for(var i = 1; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
  8792. if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
  8793. check_ws_name(name);
  8794. if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  8795. wb.SheetNames.push(name);
  8796. wb.Sheets[name] = ws;
  8797. };
  8798. /* set sheet visibility (visible/hidden/very hidden) */
  8799. utils.book_set_sheet_visibility = function(wb, sh, vis) {
  8800. get_default(wb,"Workbook",{});
  8801. get_default(wb.Workbook,"Sheets",[]);
  8802. var idx = wb_sheet_idx(wb, sh);
  8803. // $FlowIgnore
  8804. get_default(wb.Workbook.Sheets,idx, {});
  8805. switch(vis) {
  8806. case 0: case 1: case 2: break;
  8807. default: throw new Error("Bad sheet visibility setting " + vis);
  8808. }
  8809. // $FlowIgnore
  8810. wb.Workbook.Sheets[idx].Hidden = vis;
  8811. };
  8812. add_consts([
  8813. ["SHEET_VISIBLE", 0],
  8814. ["SHEET_HIDDEN", 1],
  8815. ["SHEET_VERY_HIDDEN", 2]
  8816. ]);
  8817. /* set number format */
  8818. utils.cell_set_number_format = function(cell, fmt) {
  8819. cell.z = fmt;
  8820. return cell;
  8821. };
  8822. /* set cell hyperlink */
  8823. utils.cell_set_hyperlink = function(cell, target, tooltip) {
  8824. if(!target) {
  8825. delete cell.l;
  8826. } else {
  8827. cell.l = ({ Target: target });
  8828. if(tooltip) cell.l.Tooltip = tooltip;
  8829. }
  8830. return cell;
  8831. };
  8832. utils.cell_set_internal_link = function(cell, range, tooltip) { return utils.cell_set_hyperlink(cell, "#" + range, tooltip); };
  8833. /* add to cell comments */
  8834. utils.cell_add_comment = function(cell, text, author) {
  8835. if(!cell.c) cell.c = [];
  8836. cell.c.push({t:text, a:author||"SheetJS"});
  8837. };
  8838. /* set array formula and flush related cells */
  8839. utils.sheet_set_array_formula = function(ws, range, formula) {
  8840. var rng = typeof range != "string" ? range : safe_decode_range(range);
  8841. var rngstr = typeof range == "string" ? range : encode_range(range);
  8842. for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
  8843. var cell = ws_get_cell_stub(ws, R, C);
  8844. cell.t = 'n';
  8845. cell.F = rngstr;
  8846. delete cell.v;
  8847. if(R == rng.s.r && C == rng.s.c) cell.f = formula;
  8848. }
  8849. return ws;
  8850. };
  8851. return utils;
  8852. })(utils);
  8853. if(typeof parse_xlscfb !== "undefined") XLSX.parse_xlscfb = parse_xlscfb;
  8854. XLSX.parse_zip = parse_zip;
  8855. XLSX.read = readSync; //xlsread
  8856. XLSX.readFile = readFileSync; //readFile
  8857. XLSX.readFileSync = readFileSync;
  8858. XLSX.write = writeSync;
  8859. XLSX.writeFile = writeFileSync;
  8860. XLSX.writeFileSync = writeFileSync;
  8861. XLSX.writeFileAsync = writeFileAsync;
  8862. XLSX.utils = utils;
  8863. XLSX.SSF = SSF;
  8864. if(typeof CFB !== "undefined") XLSX.CFB = CFB;
  8865. }
  8866. /*global define */
  8867. if(typeof exports !== 'undefined') make_xlsx_lib(exports);
  8868. else if(typeof module !== 'undefined' && module.exports) make_xlsx_lib(module.exports);
  8869. else if(typeof define === 'function' && define.amd) define(function() { if(!XLSX.version) make_xlsx_lib(XLSX); return XLSX; });
  8870. else make_xlsx_lib(XLSX);
  8871. /*exported XLS, ODS */
  8872. var XLS = XLSX, ODS = XLSX;