xlsx.js 890 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447
  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, DataView:false, Deno:false, Set:false */
  5. var XLSX = {};
  6. function make_xlsx_lib(XLSX){
  7. XLSX.version = '0.18.12';
  8. var current_codepage = 1200, current_ansi = 1252;
  9. /*global cptable:true, window */
  10. var $cptable;
  11. var VALID_ANSI = [ 874, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 10000 ];
  12. /* ECMA-376 Part I 18.4.1 charset to codepage mapping */
  13. var CS2CP = ({
  14. 0: 1252, /* ANSI */
  15. 1: 65001, /* DEFAULT */
  16. 2: 65001, /* SYMBOL */
  17. 77: 10000, /* MAC */
  18. 128: 932, /* SHIFTJIS */
  19. 129: 949, /* HANGUL */
  20. 130: 1361, /* JOHAB */
  21. 134: 936, /* GB2312 */
  22. 136: 950, /* CHINESEBIG5 */
  23. 161: 1253, /* GREEK */
  24. 162: 1254, /* TURKISH */
  25. 163: 1258, /* VIETNAMESE */
  26. 177: 1255, /* HEBREW */
  27. 178: 1256, /* ARABIC */
  28. 186: 1257, /* BALTIC */
  29. 204: 1251, /* RUSSIAN */
  30. 222: 874, /* THAI */
  31. 238: 1250, /* EASTEUROPE */
  32. 255: 1252, /* OEM */
  33. 69: 6969 /* MISC */
  34. });
  35. var set_ansi = function(cp) { if(VALID_ANSI.indexOf(cp) == -1) return; current_ansi = CS2CP[0] = cp; };
  36. function reset_ansi() { set_ansi(1252); }
  37. var set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  38. function reset_cp() { set_cp(1200); reset_ansi(); }
  39. function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
  40. function utf16leread(data) {
  41. var o = [];
  42. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
  43. return o.join("");
  44. }
  45. function utf16beread(data) {
  46. var o = [];
  47. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
  48. return o.join("");
  49. }
  50. var debom = function(data) {
  51. var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
  52. if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.slice(2));
  53. if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.slice(2));
  54. if(c1 == 0xFEFF) return data.slice(1);
  55. return data;
  56. };
  57. var _getchar = function _gc1(x) { return String.fromCharCode(x); };
  58. var _getansi = function _ga1(x) { return String.fromCharCode(x); };
  59. function set_cptable(cptable) {
  60. $cptable = cptable;
  61. set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  62. debom = function(data) {
  63. if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return $cptable.utils.decode(1200, char_codes(data.slice(2))); }
  64. return data;
  65. };
  66. _getchar = function _gc2(x) {
  67. if(current_codepage === 1200) return String.fromCharCode(x);
  68. return $cptable.utils.decode(current_codepage, [x&255,x>>8])[0];
  69. };
  70. _getansi = function _ga2(x) {
  71. return $cptable.utils.decode(current_ansi, [x])[0];
  72. };
  73. cpdoit();
  74. }
  75. var DENSE = null;
  76. var DIF_XL = true;
  77. var Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  78. function Base64_encode(input) {
  79. var o = "";
  80. var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  81. for (var i = 0; i < input.length; ) {
  82. c1 = input.charCodeAt(i++);
  83. e1 = c1 >> 2;
  84. c2 = input.charCodeAt(i++);
  85. e2 = (c1 & 3) << 4 | c2 >> 4;
  86. c3 = input.charCodeAt(i++);
  87. e3 = (c2 & 15) << 2 | c3 >> 6;
  88. e4 = c3 & 63;
  89. if (isNaN(c2)) {
  90. e3 = e4 = 64;
  91. } else if (isNaN(c3)) {
  92. e4 = 64;
  93. }
  94. o += Base64_map.charAt(e1) + Base64_map.charAt(e2) + Base64_map.charAt(e3) + Base64_map.charAt(e4);
  95. }
  96. return o;
  97. }
  98. function Base64_encode_pass(input) {
  99. var o = "";
  100. var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  101. for (var i = 0; i < input.length; ) {
  102. c1 = input.charCodeAt(i++);
  103. if (c1 > 255)
  104. c1 = 95;
  105. e1 = c1 >> 2;
  106. c2 = input.charCodeAt(i++);
  107. if (c2 > 255)
  108. c2 = 95;
  109. e2 = (c1 & 3) << 4 | c2 >> 4;
  110. c3 = input.charCodeAt(i++);
  111. if (c3 > 255)
  112. c3 = 95;
  113. e3 = (c2 & 15) << 2 | c3 >> 6;
  114. e4 = c3 & 63;
  115. if (isNaN(c2)) {
  116. e3 = e4 = 64;
  117. } else if (isNaN(c3)) {
  118. e4 = 64;
  119. }
  120. o += Base64_map.charAt(e1) + Base64_map.charAt(e2) + Base64_map.charAt(e3) + Base64_map.charAt(e4);
  121. }
  122. return o;
  123. }
  124. function Base64_decode(input) {
  125. var o = "";
  126. var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  127. input = input.replace(/^data:([^\/]+\/[^\/]+)?;base64\,/, "").replace(/[^\w\+\/\=]/g, "");
  128. for (var i = 0; i < input.length; ) {
  129. e1 = Base64_map.indexOf(input.charAt(i++));
  130. e2 = Base64_map.indexOf(input.charAt(i++));
  131. c1 = e1 << 2 | e2 >> 4;
  132. o += String.fromCharCode(c1);
  133. e3 = Base64_map.indexOf(input.charAt(i++));
  134. c2 = (e2 & 15) << 4 | e3 >> 2;
  135. if (e3 !== 64) {
  136. o += String.fromCharCode(c2);
  137. }
  138. e4 = Base64_map.indexOf(input.charAt(i++));
  139. c3 = (e3 & 3) << 6 | e4;
  140. if (e4 !== 64) {
  141. o += String.fromCharCode(c3);
  142. }
  143. }
  144. return o;
  145. }
  146. var has_buf = (function() { return typeof Buffer !== 'undefined' && typeof process !== 'undefined' && typeof process.versions !== 'undefined' && !!process.versions.node; })();
  147. var Buffer_from = (function() {
  148. if(typeof Buffer !== 'undefined') {
  149. var nbfs = !Buffer.from;
  150. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  151. return nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  152. }
  153. return function() {};
  154. })();
  155. var buf_utf16le = (function() {
  156. if(typeof Buffer === 'undefined') return false;
  157. var x = Buffer_from([65,0]);
  158. if(!x) return false;
  159. var o = x.toString("utf16le");
  160. return o.length == 1;
  161. })();
  162. function new_raw_buf(len) {
  163. /* jshint -W056 */
  164. if(has_buf) return Buffer.alloc ? Buffer.alloc(len) : new Buffer(len);
  165. return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
  166. /* jshint +W056 */
  167. }
  168. function new_unsafe_buf(len) {
  169. /* jshint -W056 */
  170. if(has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len);
  171. return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
  172. /* jshint +W056 */
  173. }
  174. var s2a = function s2a(s) {
  175. if(has_buf) return Buffer_from(s, "binary");
  176. return s.split("").map(function(x){ return x.charCodeAt(0) & 0xff; });
  177. };
  178. function s2ab(s) {
  179. if(typeof ArrayBuffer === 'undefined') return s2a(s);
  180. var buf = new ArrayBuffer(s.length), view = new Uint8Array(buf);
  181. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  182. return buf;
  183. }
  184. function a2s(data) {
  185. if(Array.isArray(data)) return data.map(function(c) { return String.fromCharCode(c); }).join("");
  186. var o = []; for(var i = 0; i < data.length; ++i) o[i] = String.fromCharCode(data[i]); return o.join("");
  187. }
  188. function a2u(data) {
  189. if(typeof Uint8Array === 'undefined') throw new Error("Unsupported");
  190. return new Uint8Array(data);
  191. }
  192. function ab2a(data) {
  193. if(typeof ArrayBuffer == 'undefined') throw new Error("Unsupported");
  194. if(data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
  195. var o = new Array(data.length);
  196. for(var i = 0; i < data.length; ++i) o[i] = data[i];
  197. return o;
  198. }
  199. var bconcat = has_buf ? function(bufs) { return Buffer.concat(bufs.map(function(buf) { return Buffer.isBuffer(buf) ? buf : Buffer_from(buf); })); } : function(bufs) {
  200. if(typeof Uint8Array !== "undefined") {
  201. var i = 0, maxlen = 0;
  202. for(i = 0; i < bufs.length; ++i) maxlen += bufs[i].length;
  203. var o = new Uint8Array(maxlen);
  204. var len = 0;
  205. for(i = 0, maxlen = 0; i < bufs.length; maxlen += len, ++i) {
  206. len = bufs[i].length;
  207. if(bufs[i] instanceof Uint8Array) o.set(bufs[i], maxlen);
  208. else if(typeof bufs[i] == "string") o.set(new Uint8Array(s2a(bufs[i])), maxlen);
  209. else o.set(new Uint8Array(bufs[i]), maxlen);
  210. }
  211. return o;
  212. }
  213. return [].concat.apply([], bufs.map(function(buf) { return Array.isArray(buf) ? buf : [].slice.call(buf); }));
  214. };
  215. function utf8decode(content) {
  216. var out = [], widx = 0, L = content.length + 250;
  217. var o = new_raw_buf(content.length + 255);
  218. for(var ridx = 0; ridx < content.length; ++ridx) {
  219. var c = content.charCodeAt(ridx);
  220. if(c < 0x80) o[widx++] = c;
  221. else if(c < 0x800) {
  222. o[widx++] = (192|((c>>6)&31));
  223. o[widx++] = (128|(c&63));
  224. } else if(c >= 0xD800 && c < 0xE000) {
  225. c = (c&1023)+64;
  226. var d = content.charCodeAt(++ridx)&1023;
  227. o[widx++] = (240|((c>>8)&7));
  228. o[widx++] = (128|((c>>2)&63));
  229. o[widx++] = (128|((d>>6)&15)|((c&3)<<4));
  230. o[widx++] = (128|(d&63));
  231. } else {
  232. o[widx++] = (224|((c>>12)&15));
  233. o[widx++] = (128|((c>>6)&63));
  234. o[widx++] = (128|(c&63));
  235. }
  236. if(widx > L) {
  237. out.push(o.slice(0, widx));
  238. widx = 0;
  239. o = new_raw_buf(65535);
  240. L = 65530;
  241. }
  242. }
  243. out.push(o.slice(0, widx));
  244. return bconcat(out);
  245. }
  246. var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/g;
  247. /* ssf.js (C) 2013-present SheetJS -- http://sheetjs.com */
  248. /*jshint -W041 */
  249. function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
  250. function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  251. function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;}
  252. function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);}
  253. function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;}
  254. function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  255. var p2_32 = Math.pow(2,32);
  256. function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
  257. /* yes, in 2022 this is still faster than string compare */
  258. function SSF_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; }
  259. var days = [
  260. ['Sun', 'Sunday'],
  261. ['Mon', 'Monday'],
  262. ['Tue', 'Tuesday'],
  263. ['Wed', 'Wednesday'],
  264. ['Thu', 'Thursday'],
  265. ['Fri', 'Friday'],
  266. ['Sat', 'Saturday']
  267. ];
  268. var months = [
  269. ['J', 'Jan', 'January'],
  270. ['F', 'Feb', 'February'],
  271. ['M', 'Mar', 'March'],
  272. ['A', 'Apr', 'April'],
  273. ['M', 'May', 'May'],
  274. ['J', 'Jun', 'June'],
  275. ['J', 'Jul', 'July'],
  276. ['A', 'Aug', 'August'],
  277. ['S', 'Sep', 'September'],
  278. ['O', 'Oct', 'October'],
  279. ['N', 'Nov', 'November'],
  280. ['D', 'Dec', 'December']
  281. ];
  282. function SSF_init_table(t) {
  283. if(!t) t = {};
  284. t[0]= 'General';
  285. t[1]= '0';
  286. t[2]= '0.00';
  287. t[3]= '#,##0';
  288. t[4]= '#,##0.00';
  289. t[9]= '0%';
  290. t[10]= '0.00%';
  291. t[11]= '0.00E+00';
  292. t[12]= '# ?/?';
  293. t[13]= '# ??/??';
  294. t[14]= 'm/d/yy';
  295. t[15]= 'd-mmm-yy';
  296. t[16]= 'd-mmm';
  297. t[17]= 'mmm-yy';
  298. t[18]= 'h:mm AM/PM';
  299. t[19]= 'h:mm:ss AM/PM';
  300. t[20]= 'h:mm';
  301. t[21]= 'h:mm:ss';
  302. t[22]= 'm/d/yy h:mm';
  303. t[37]= '#,##0 ;(#,##0)';
  304. t[38]= '#,##0 ;[Red](#,##0)';
  305. t[39]= '#,##0.00;(#,##0.00)';
  306. t[40]= '#,##0.00;[Red](#,##0.00)';
  307. t[45]= 'mm:ss';
  308. t[46]= '[h]:mm:ss';
  309. t[47]= 'mmss.0';
  310. t[48]= '##0.0E+0';
  311. t[49]= '@';
  312. t[56]= '"上午/下午 "hh"時"mm"分"ss"秒 "';
  313. return t;
  314. }
  315. /* repeated to satiate webpack */
  316. var table_fmt = {
  317. 0: 'General',
  318. 1: '0',
  319. 2: '0.00',
  320. 3: '#,##0',
  321. 4: '#,##0.00',
  322. 9: '0%',
  323. 10: '0.00%',
  324. 11: '0.00E+00',
  325. 12: '# ?/?',
  326. 13: '# ??/??',
  327. 14: 'm/d/yy',
  328. 15: 'd-mmm-yy',
  329. 16: 'd-mmm',
  330. 17: 'mmm-yy',
  331. 18: 'h:mm AM/PM',
  332. 19: 'h:mm:ss AM/PM',
  333. 20: 'h:mm',
  334. 21: 'h:mm:ss',
  335. 22: 'm/d/yy h:mm',
  336. 37: '#,##0 ;(#,##0)',
  337. 38: '#,##0 ;[Red](#,##0)',
  338. 39: '#,##0.00;(#,##0.00)',
  339. 40: '#,##0.00;[Red](#,##0.00)',
  340. 45: 'mm:ss',
  341. 46: '[h]:mm:ss',
  342. 47: 'mmss.0',
  343. 48: '##0.0E+0',
  344. 49: '@',
  345. 56: '"上午/下午 "hh"時"mm"分"ss"秒 "'
  346. };
  347. /* Defaults determined by systematically testing in Excel 2019 */
  348. /* These formats appear to default to other formats in the table */
  349. var SSF_default_map = {
  350. 5: 37, 6: 38, 7: 39, 8: 40, // 5 -> 37 ... 8 -> 40
  351. 23: 0, 24: 0, 25: 0, 26: 0, // 23 -> 0 ... 26 -> 0
  352. 27: 14, 28: 14, 29: 14, 30: 14, 31: 14, // 27 -> 14 ... 31 -> 14
  353. 50: 14, 51: 14, 52: 14, 53: 14, 54: 14, // 50 -> 14 ... 58 -> 14
  354. 55: 14, 56: 14, 57: 14, 58: 14,
  355. 59: 1, 60: 2, 61: 3, 62: 4, // 59 -> 1 ... 62 -> 4
  356. 67: 9, 68: 10, // 67 -> 9 ... 68 -> 10
  357. 69: 12, 70: 13, 71: 14, // 69 -> 12 ... 71 -> 14
  358. 72: 14, 73: 15, 74: 16, 75: 17, // 72 -> 14 ... 75 -> 17
  359. 76: 20, 77: 21, 78: 22, // 76 -> 20 ... 78 -> 22
  360. 79: 45, 80: 46, 81: 47, // 79 -> 45 ... 81 -> 47
  361. 82: 0 // 82 -> 0 ... 65536 -> 0 (omitted)
  362. };
  363. /* These formats technically refer to Accounting formats with no equivalent */
  364. var SSF_default_str = {
  365. // 5 -- Currency, 0 decimal, black negative
  366. 5: '"$"#,##0_);\\("$"#,##0\\)',
  367. 63: '"$"#,##0_);\\("$"#,##0\\)',
  368. // 6 -- Currency, 0 decimal, red negative
  369. 6: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  370. 64: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  371. // 7 -- Currency, 2 decimal, black negative
  372. 7: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  373. 65: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  374. // 8 -- Currency, 2 decimal, red negative
  375. 8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  376. 66: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  377. // 41 -- Accounting, 0 decimal, No Symbol
  378. 41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',
  379. // 42 -- Accounting, 0 decimal, $ Symbol
  380. 42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',
  381. // 43 -- Accounting, 2 decimal, No Symbol
  382. 43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',
  383. // 44 -- Accounting, 2 decimal, $ Symbol
  384. 44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'
  385. };
  386. function SSF_frac(x, D, mixed) {
  387. var sgn = x < 0 ? -1 : 1;
  388. var B = x * sgn;
  389. var P_2 = 0, P_1 = 1, P = 0;
  390. var Q_2 = 1, Q_1 = 0, Q = 0;
  391. var A = Math.floor(B);
  392. while(Q_1 < D) {
  393. A = Math.floor(B);
  394. P = A * P_1 + P_2;
  395. Q = A * Q_1 + Q_2;
  396. if((B - A) < 0.00000005) break;
  397. B = 1 / (B - A);
  398. P_2 = P_1; P_1 = P;
  399. Q_2 = Q_1; Q_1 = Q;
  400. }
  401. if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
  402. if(!mixed) return [0, sgn * P, Q];
  403. var q = Math.floor(sgn * P/Q);
  404. return [q, sgn*P - q*Q, Q];
  405. }
  406. function SSF_parse_date_code(v,opts,b2) {
  407. if(v > 2958465 || v < 0) return null;
  408. var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
  409. var dout=[];
  410. 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};
  411. if(Math.abs(out.u) < 1e-6) out.u = 0;
  412. if(opts && opts.date1904) date += 1462;
  413. if(out.u > 0.9999) {
  414. out.u = 0;
  415. if(++time == 86400) { out.T = time = 0; ++date; ++out.D; }
  416. }
  417. if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
  418. else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
  419. else {
  420. if(date > 60) --date;
  421. /* 1 = Jan 1 1900 in Gregorian */
  422. var d = new Date(1900, 0, 1);
  423. d.setDate(d.getDate() + date - 1);
  424. dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
  425. dow = d.getDay();
  426. if(date < 60) dow = (dow + 6) % 7;
  427. if(b2) dow = SSF_fix_hijri(d, dout);
  428. }
  429. out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
  430. out.S = time % 60; time = Math.floor(time / 60);
  431. out.M = time % 60; time = Math.floor(time / 60);
  432. out.H = time;
  433. out.q = dow;
  434. return out;
  435. }
  436. var SSFbasedate = new Date(1899, 11, 31, 0, 0, 0);
  437. var SSFdnthresh = SSFbasedate.getTime();
  438. var SSFbase1904 = new Date(1900, 2, 1, 0, 0, 0);
  439. function datenum_local(v, date1904) {
  440. var epoch = v.getTime();
  441. if(date1904) epoch -= 1461*24*60*60*1000;
  442. else if(v >= SSFbase1904) epoch += 24*60*60*1000;
  443. return (epoch - (SSFdnthresh + (v.getTimezoneOffset() - SSFbasedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
  444. }
  445. /* ECMA-376 18.8.30 numFmt*/
  446. /* Note: `toPrecision` uses standard form when prec > E and E >= -6 */
  447. /* exponent >= -9 and <= 9 */
  448. function SSF_strip_decimal(o) {
  449. return (o.indexOf(".") == -1) ? o : o.replace(/(?:\.0*|(\.\d*[1-9])0+)$/, "$1");
  450. }
  451. /* General Exponential always shows 2 digits exp and trims the mantissa */
  452. function SSF_normalize_exp(o) {
  453. if(o.indexOf("E") == -1) return o;
  454. return o.replace(/(?:\.0*|(\.\d*[1-9])0+)[Ee]/,"$1E").replace(/(E[+-])(\d)$/,"$10$2");
  455. }
  456. /* exponent >= -9 and <= 9 */
  457. function SSF_small_exp(v) {
  458. var w = (v<0?12:11);
  459. var o = SSF_strip_decimal(v.toFixed(12)); if(o.length <= w) return o;
  460. o = v.toPrecision(10); if(o.length <= w) return o;
  461. return v.toExponential(5);
  462. }
  463. /* exponent >= 11 or <= -10 likely exponential */
  464. function SSF_large_exp(v) {
  465. var o = SSF_strip_decimal(v.toFixed(11));
  466. return (o.length > (v<0?12:11) || o === "0" || o === "-0") ? v.toPrecision(6) : o;
  467. }
  468. function SSF_general_num(v) {
  469. var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;
  470. if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
  471. else if(Math.abs(V) <= 9) o = SSF_small_exp(v);
  472. else if(V === 10) o = v.toFixed(10).substr(0,12);
  473. else o = SSF_large_exp(v);
  474. return SSF_strip_decimal(SSF_normalize_exp(o.toUpperCase()));
  475. }
  476. /*
  477. "General" rules:
  478. - text is passed through ("@")
  479. - booleans are rendered as TRUE/FALSE
  480. - "up to 11 characters" displayed for numbers
  481. - Default date format (code 14) used for Dates
  482. The longest 32-bit integer text is "-2147483648", exactly 11 chars
  483. TODO: technically the display depends on the width of the cell
  484. */
  485. function SSF_general(v, opts) {
  486. switch(typeof v) {
  487. case 'string': return v;
  488. case 'boolean': return v ? "TRUE" : "FALSE";
  489. case 'number': return (v|0) === v ? v.toString(10) : SSF_general_num(v);
  490. case 'undefined': return "";
  491. case 'object':
  492. if(v == null) return "";
  493. if(v instanceof Date) return SSF_format(14, datenum_local(v, opts && opts.date1904), opts);
  494. }
  495. throw new Error("unsupported value in General format: " + v);
  496. }
  497. function SSF_fix_hijri(date, o) {
  498. /* TODO: properly adjust y/m/d and */
  499. o[0] -= 581;
  500. var dow = date.getDay();
  501. if(date < 60) dow = (dow + 6) % 7;
  502. return dow;
  503. }
  504. //var THAI_DIGITS = "\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59".split("");
  505. function SSF_write_date(type, fmt, val, ss0) {
  506. var o="", ss=0, tt=0, y = val.y, out, outl = 0;
  507. switch(type) {
  508. case 98: /* 'b' buddhist year */
  509. y = val.y + 543;
  510. /* falls through */
  511. case 121: /* 'y' year */
  512. switch(fmt.length) {
  513. case 1: case 2: out = y % 100; outl = 2; break;
  514. default: out = y % 10000; outl = 4; break;
  515. } break;
  516. case 109: /* 'm' month */
  517. switch(fmt.length) {
  518. case 1: case 2: out = val.m; outl = fmt.length; break;
  519. case 3: return months[val.m-1][1];
  520. case 5: return months[val.m-1][0];
  521. default: return months[val.m-1][2];
  522. } break;
  523. case 100: /* 'd' day */
  524. switch(fmt.length) {
  525. case 1: case 2: out = val.d; outl = fmt.length; break;
  526. case 3: return days[val.q][0];
  527. default: return days[val.q][1];
  528. } break;
  529. case 104: /* 'h' 12-hour */
  530. switch(fmt.length) {
  531. case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
  532. default: throw 'bad hour format: ' + fmt;
  533. } break;
  534. case 72: /* 'H' 24-hour */
  535. switch(fmt.length) {
  536. case 1: case 2: out = val.H; outl = fmt.length; break;
  537. default: throw 'bad hour format: ' + fmt;
  538. } break;
  539. case 77: /* 'M' minutes */
  540. switch(fmt.length) {
  541. case 1: case 2: out = val.M; outl = fmt.length; break;
  542. default: throw 'bad minute format: ' + fmt;
  543. } break;
  544. case 115: /* 's' seconds */
  545. if(fmt != 's' && fmt != 'ss' && fmt != '.0' && fmt != '.00' && fmt != '.000') throw 'bad second format: ' + fmt;
  546. if(val.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val.S, fmt.length);
  547. if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
  548. else tt = ss0 === 1 ? 10 : 1;
  549. ss = Math.round((tt)*(val.S + val.u));
  550. if(ss >= 60*tt) ss = 0;
  551. if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
  552. o = pad0(ss,2 + ss0);
  553. if(fmt === 'ss') return o.substr(0,2);
  554. return "." + o.substr(2,fmt.length-1);
  555. case 90: /* 'Z' absolute time */
  556. switch(fmt) {
  557. case '[h]': case '[hh]': out = val.D*24+val.H; break;
  558. case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
  559. case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
  560. default: throw 'bad abstime format: ' + fmt;
  561. } outl = fmt.length === 3 ? 1 : 2; break;
  562. case 101: /* 'e' era */
  563. out = y; outl = 1; break;
  564. }
  565. var outstr = outl > 0 ? pad0(out, outl) : "";
  566. return outstr;
  567. }
  568. /*jshint -W086 */
  569. /*jshint +W086 */
  570. function commaify(s) {
  571. var w = 3;
  572. if(s.length <= w) return s;
  573. var j = (s.length % w), o = s.substr(0,j);
  574. for(; j!=s.length; j+=w) o+=(o.length > 0 ? "," : "") + s.substr(j,w);
  575. return o;
  576. }
  577. var pct1 = /%/g;
  578. function write_num_pct(type, fmt, val){
  579. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  580. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  581. }
  582. function write_num_cm(type, fmt, val){
  583. var idx = fmt.length - 1;
  584. while(fmt.charCodeAt(idx-1) === 44) --idx;
  585. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  586. }
  587. function write_num_exp(fmt, val){
  588. var o;
  589. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  590. if(fmt.match(/^#+0.0E\+0$/)) {
  591. if(val == 0) return "0.0E+0";
  592. else if(val < 0) return "-" + write_num_exp(fmt, -val);
  593. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  594. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  595. if(ee < 0) ee += period;
  596. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  597. if(o.indexOf("e") === -1) {
  598. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  599. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  600. else o += "E+" + (fakee - ee);
  601. while(o.substr(0,2) === "0.") {
  602. o = o.charAt(0) + o.substr(2,period) + "." + o.substr(2+period);
  603. o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
  604. }
  605. o = o.replace(/\+-/,"-");
  606. }
  607. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  608. } else o = val.toExponential(idx);
  609. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  610. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  611. return o.replace("e","E");
  612. }
  613. var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
  614. function write_num_f1(r, aval, sign) {
  615. var den = parseInt(r[4],10), rr = Math.round(aval * den), base = Math.floor(rr/den);
  616. var myn = (rr - base*den), myd = den;
  617. 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));
  618. }
  619. function write_num_f2(r, aval, sign) {
  620. return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length);
  621. }
  622. var dec1 = /^#*0*\.([0#]+)/;
  623. var closeparen = /\).*[0#]/;
  624. var phone = /\(###\) ###\\?-####/;
  625. function hashq(str) {
  626. var o = "", cc;
  627. for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
  628. case 35: break;
  629. case 63: o+= " "; break;
  630. case 48: o+= "0"; break;
  631. default: o+= String.fromCharCode(cc);
  632. }
  633. return o;
  634. }
  635. function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
  636. function dec(val, d) {
  637. var _frac = val - Math.floor(val), dd = Math.pow(10,d);
  638. if (d < ('' + Math.round(_frac * dd)).length) return 0;
  639. return Math.round(_frac * dd);
  640. }
  641. function carry(val, d) {
  642. if (d < ('' + Math.round((val-Math.floor(val))*Math.pow(10,d))).length) {
  643. return 1;
  644. }
  645. return 0;
  646. }
  647. function flr(val) {
  648. if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0));
  649. return ""+Math.floor(val);
  650. }
  651. function write_num_flt(type, fmt, val) {
  652. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  653. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  654. if(val >= 0) return write_num_flt('n', ffmt, val);
  655. return '(' + write_num_flt('n', ffmt, -val) + ')';
  656. }
  657. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
  658. if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
  659. if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
  660. if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  661. var o;
  662. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  663. if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
  664. if(fmt.match(/^[#?]+$/)) {
  665. o = pad0r(val,0); if(o === "0") o = "";
  666. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  667. }
  668. if((r = fmt.match(frac1))) return write_num_f1(r, aval, sign);
  669. if(fmt.match(/^#+0+$/)) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
  670. if((r = fmt.match(dec1))) {
  671. 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); });
  672. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  673. }
  674. fmt = fmt.replace(/^#+([0.])/, "$1");
  675. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  676. return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  677. }
  678. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify(pad0r(aval,0));
  679. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  680. 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);
  681. }
  682. if((r = fmt.match(/^#,#*,#0/))) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
  683. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  684. o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
  685. ri = 0;
  686. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  687. }
  688. if(fmt.match(phone)) {
  689. o = write_num_flt(type, "##########", val);
  690. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  691. }
  692. var oa = "";
  693. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  694. ri = Math.min(r[4].length,7);
  695. ff = SSF_frac(aval, Math.pow(10,ri)-1, false);
  696. o = "" + sign;
  697. oa = write_num("n", r[1], ff[1]);
  698. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  699. o += oa + r[2] + "/" + r[3];
  700. oa = rpad_(ff[2],ri);
  701. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  702. o += oa;
  703. return o;
  704. }
  705. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  706. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  707. ff = SSF_frac(aval, Math.pow(10,ri)-1, true);
  708. 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));
  709. }
  710. if((r = fmt.match(/^[#0?]+$/))) {
  711. o = pad0r(val, 0);
  712. if(fmt.length <= o.length) return o;
  713. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  714. }
  715. if((r = fmt.match(/^([#0?]+)\.([#0]+)$/))) {
  716. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  717. ri = o.indexOf(".");
  718. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  719. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  720. }
  721. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  722. ri = dec(val, r[1].length);
  723. 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);
  724. }
  725. switch(fmt) {
  726. case "###,##0.00": return write_num_flt(type, "#,##0.00", val);
  727. case "###,###":
  728. case "##,###":
  729. case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
  730. case "###,###.00": return write_num_flt(type, "###,##0.00",val).replace(/^0\./,".");
  731. case "#,###.00": return write_num_flt(type, "#,##0.00",val).replace(/^0\./,".");
  732. default:
  733. }
  734. throw new Error("unsupported format |" + fmt + "|");
  735. }
  736. function write_num_cm2(type, fmt, val){
  737. var idx = fmt.length - 1;
  738. while(fmt.charCodeAt(idx-1) === 44) --idx;
  739. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  740. }
  741. function write_num_pct2(type, fmt, val){
  742. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  743. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  744. }
  745. function write_num_exp2(fmt, val){
  746. var o;
  747. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  748. if(fmt.match(/^#+0.0E\+0$/)) {
  749. if(val == 0) return "0.0E+0";
  750. else if(val < 0) return "-" + write_num_exp2(fmt, -val);
  751. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  752. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  753. if(ee < 0) ee += period;
  754. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  755. if(!o.match(/[Ee]/)) {
  756. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  757. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  758. else o += "E+" + (fakee - ee);
  759. o = o.replace(/\+-/,"-");
  760. }
  761. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  762. } else o = val.toExponential(idx);
  763. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  764. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  765. return o.replace("e","E");
  766. }
  767. function write_num_int(type, fmt, val) {
  768. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  769. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  770. if(val >= 0) return write_num_int('n', ffmt, val);
  771. return '(' + write_num_int('n', ffmt, -val) + ')';
  772. }
  773. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
  774. if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
  775. if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
  776. if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  777. var o;
  778. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  779. if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
  780. if(fmt.match(/^[#?]+$/)) {
  781. o = (""+val); if(val === 0) o = "";
  782. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  783. }
  784. if((r = fmt.match(frac1))) return write_num_f2(r, aval, sign);
  785. if(fmt.match(/^#+0+$/)) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
  786. if((r = fmt.match(dec1))) {
  787. o = (""+val).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1]));
  788. o = o.replace(/\.(\d*)$/,function($$, $1) {
  789. return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  790. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  791. }
  792. fmt = fmt.replace(/^#+([0.])/, "$1");
  793. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  794. return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  795. }
  796. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify((""+aval));
  797. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  798. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length);
  799. }
  800. if((r = fmt.match(/^#,#*,#0/))) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
  801. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  802. o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
  803. ri = 0;
  804. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  805. }
  806. if(fmt.match(phone)) {
  807. o = write_num_int(type, "##########", val);
  808. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  809. }
  810. var oa = "";
  811. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  812. ri = Math.min(r[4].length,7);
  813. ff = SSF_frac(aval, Math.pow(10,ri)-1, false);
  814. o = "" + sign;
  815. oa = write_num("n", r[1], ff[1]);
  816. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  817. o += oa + r[2] + "/" + r[3];
  818. oa = rpad_(ff[2],ri);
  819. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  820. o += oa;
  821. return o;
  822. }
  823. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  824. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  825. ff = SSF_frac(aval, Math.pow(10,ri)-1, true);
  826. 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));
  827. }
  828. if((r = fmt.match(/^[#0?]+$/))) {
  829. o = "" + val;
  830. if(fmt.length <= o.length) return o;
  831. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  832. }
  833. if((r = fmt.match(/^([#0]+)\.([#0]+)$/))) {
  834. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  835. ri = o.indexOf(".");
  836. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  837. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  838. }
  839. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  840. 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);
  841. }
  842. switch(fmt) {
  843. case "###,###":
  844. case "##,###":
  845. case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
  846. default:
  847. if(fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0,fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
  848. }
  849. throw new Error("unsupported format |" + fmt + "|");
  850. }
  851. function write_num(type, fmt, val) {
  852. return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
  853. }
  854. function SSF_split_fmt(fmt) {
  855. var out = [];
  856. var in_str = false/*, cc*/;
  857. for(var i = 0, j = 0; i < fmt.length; ++i) switch((/*cc=*/fmt.charCodeAt(i))) {
  858. case 34: /* '"' */
  859. in_str = !in_str; break;
  860. case 95: case 42: case 92: /* '_' '*' '\\' */
  861. ++i; break;
  862. case 59: /* ';' */
  863. out[out.length] = fmt.substr(j,i-j);
  864. j = i+1;
  865. }
  866. out[out.length] = fmt.substr(j);
  867. if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
  868. return out;
  869. }
  870. var SSF_abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
  871. function fmt_is_date(fmt) {
  872. var i = 0, /*cc = 0,*/ c = "", o = "";
  873. while(i < fmt.length) {
  874. switch((c = fmt.charAt(i))) {
  875. case 'G': if(SSF_isgeneral(fmt, i)) i+= 6; i++; break;
  876. case '"': for(;(/*cc=*/fmt.charCodeAt(++i)) !== 34 && i < fmt.length;){/*empty*/} ++i; break;
  877. case '\\': i+=2; break;
  878. case '_': i+=2; break;
  879. case '@': ++i; break;
  880. case 'B': case 'b':
  881. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") return true;
  882. /* falls through */
  883. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  884. /* falls through */
  885. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': return true;
  886. case 'A': case 'a': case '上':
  887. if(fmt.substr(i, 3).toUpperCase() === "A/P") return true;
  888. if(fmt.substr(i, 5).toUpperCase() === "AM/PM") return true;
  889. if(fmt.substr(i, 5).toUpperCase() === "上午/下午") return true;
  890. ++i; break;
  891. case '[':
  892. o = c;
  893. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  894. if(o.match(SSF_abstime)) return true;
  895. break;
  896. case '.':
  897. /* falls through */
  898. case '0': case '#':
  899. 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 */}
  900. break;
  901. case '?': while(fmt.charAt(++i) === c){/* empty */} break;
  902. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break;
  903. case '(': case ')': ++i; break;
  904. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  905. while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1){/* empty */} break;
  906. case ' ': ++i; break;
  907. default: ++i; break;
  908. }
  909. }
  910. return false;
  911. }
  912. function eval_fmt(fmt, v, opts, flen) {
  913. var out = [], o = "", i = 0, c = "", lst='t', dt, j, cc;
  914. var hr='H';
  915. /* Tokenize */
  916. while(i < fmt.length) {
  917. switch((c = fmt.charAt(i))) {
  918. case 'G': /* General */
  919. if(!SSF_isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
  920. out[out.length] = {t:'G', v:'General'}; i+=7; break;
  921. case '"': /* Literal text */
  922. for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
  923. out[out.length] = {t:'t', v:o}; ++i; break;
  924. case '\\': var w = fmt.charAt(++i), t = (w === "(" || w === ")") ? w : 't';
  925. out[out.length] = {t:t, v:w}; ++i; break;
  926. case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
  927. case '@': /* Text Placeholder */
  928. out[out.length] = {t:'T', v:v}; ++i; break;
  929. case 'B': case 'b':
  930. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") {
  931. if(dt==null) { dt=SSF_parse_date_code(v, opts, fmt.charAt(i+1) === "2"); if(dt==null) return ""; }
  932. out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
  933. }
  934. /* falls through */
  935. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  936. c = c.toLowerCase();
  937. /* falls through */
  938. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
  939. if(v < 0) return "";
  940. if(dt==null) { dt=SSF_parse_date_code(v, opts); if(dt==null) return ""; }
  941. o = c; while(++i < fmt.length && fmt.charAt(i).toLowerCase() === c) o+=c;
  942. if(c === 'm' && lst.toLowerCase() === 'h') c = 'M';
  943. if(c === 'h') c = hr;
  944. out[out.length] = {t:c, v:o}; lst = c; break;
  945. case 'A': case 'a': case '上':
  946. var q={t:c, v:c};
  947. if(dt==null) dt=SSF_parse_date_code(v, opts);
  948. if(fmt.substr(i, 3).toUpperCase() === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? fmt.charAt(i+2) : c; q.t = 'T'; hr='h';i+=3;}
  949. 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'; }
  950. else if(fmt.substr(i,5).toUpperCase() === "上午/下午") { if(dt!=null) q.v = dt.H >= 12 ? "下午" : "上午"; q.t = 'T'; i+=5; hr='h'; }
  951. else { q.t = "t"; ++i; }
  952. if(dt==null && q.t === 'T') return "";
  953. out[out.length] = q; lst = c; break;
  954. case '[':
  955. o = c;
  956. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  957. if(o.slice(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
  958. if(o.match(SSF_abstime)) {
  959. if(dt==null) { dt=SSF_parse_date_code(v, opts); if(dt==null) return ""; }
  960. out[out.length] = {t:'Z', v:o.toLowerCase()};
  961. lst = o.charAt(1);
  962. } else if(o.indexOf("$") > -1) {
  963. o = (o.match(/\$([^-\[\]]*)/)||[])[1]||"$";
  964. if(!fmt_is_date(fmt)) out[out.length] = {t:'t',v:o};
  965. }
  966. break;
  967. /* Numbers */
  968. case '.':
  969. if(dt != null) {
  970. o = c; while(++i < fmt.length && (c=fmt.charAt(i)) === "0") o += c;
  971. out[out.length] = {t:'s', v:o}; break;
  972. }
  973. /* falls through */
  974. case '0': case '#':
  975. o = c; while(++i < fmt.length && "0#?.,E+-%".indexOf(c=fmt.charAt(i)) > -1) o += c;
  976. out[out.length] = {t:'n', v:o}; break;
  977. case '?':
  978. o = c; while(fmt.charAt(++i) === c) o+=c;
  979. out[out.length] = {t:c, v:o}; lst = c; break;
  980. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break; // **
  981. case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
  982. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  983. o = c; while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) o+=fmt.charAt(i);
  984. out[out.length] = {t:'D', v:o}; break;
  985. case ' ': out[out.length] = {t:c, v:c}; ++i; break;
  986. case '$': out[out.length] = {t:'t', v:'$'}; ++i; break;
  987. default:
  988. if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
  989. out[out.length] = {t:'t', v:c}; ++i; break;
  990. }
  991. }
  992. /* Scan for date/time parts */
  993. var bt = 0, ss0 = 0, ssm;
  994. for(i=out.length-1, lst='t'; i >= 0; --i) {
  995. switch(out[i].t) {
  996. case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
  997. case 's':
  998. if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
  999. if(bt < 3) bt = 3;
  1000. /* falls through */
  1001. case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
  1002. case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
  1003. case 'X': /*if(out[i].v === "B2");*/
  1004. break;
  1005. case 'Z':
  1006. if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
  1007. if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
  1008. if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
  1009. }
  1010. }
  1011. /* time rounding depends on presence of minute / second / usec fields */
  1012. switch(bt) {
  1013. case 0: break;
  1014. case 1:
  1015. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  1016. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  1017. if(dt.M >= 60) { dt.M = 0; ++dt.H; }
  1018. break;
  1019. case 2:
  1020. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  1021. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  1022. break;
  1023. }
  1024. /* replace fields */
  1025. var nstr = "", jj;
  1026. for(i=0; i < out.length; ++i) {
  1027. switch(out[i].t) {
  1028. case 't': case 'T': case ' ': case 'D': break;
  1029. case 'X': out[i].v = ""; out[i].t = ";"; break;
  1030. case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
  1031. out[i].v = SSF_write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
  1032. out[i].t = 't'; break;
  1033. case 'n': case '?':
  1034. jj = i+1;
  1035. while(out[jj] != null && (
  1036. (c=out[jj].t) === "?" || c === "D" ||
  1037. ((c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/')) ||
  1038. (out[i].t === '(' && (c === ' ' || c === 'n' || c === ')')) ||
  1039. (c === 't' && (out[jj].v === '/' || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?'))
  1040. )) {
  1041. out[i].v += out[jj].v;
  1042. out[jj] = {v:"", t:";"}; ++jj;
  1043. }
  1044. nstr += out[i].v;
  1045. i = jj-1; break;
  1046. case 'G': out[i].t = 't'; out[i].v = SSF_general(v,opts); break;
  1047. }
  1048. }
  1049. var vv = "", myv, ostr;
  1050. if(nstr.length > 0) {
  1051. if(nstr.charCodeAt(0) == 40) /* '(' */ {
  1052. myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v);
  1053. ostr = write_num('n', nstr, myv);
  1054. } else {
  1055. myv = (v<0 && flen > 1 ? -v : v);
  1056. ostr = write_num('n', nstr, myv);
  1057. if(myv < 0 && out[0] && out[0].t == 't') {
  1058. ostr = ostr.substr(1);
  1059. out[0].v = "-" + out[0].v;
  1060. }
  1061. }
  1062. jj=ostr.length-1;
  1063. var decpt = out.length;
  1064. for(i=0; i < out.length; ++i) if(out[i] != null && out[i].t != 't' && out[i].v.indexOf(".") > -1) { decpt = i; break; }
  1065. var lasti=out.length;
  1066. if(decpt === out.length && ostr.indexOf("E") === -1) {
  1067. for(i=out.length-1; i>= 0;--i) {
  1068. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  1069. if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
  1070. else if(jj < 0) out[i].v = "";
  1071. else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
  1072. out[i].t = 't';
  1073. lasti = i;
  1074. }
  1075. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  1076. }
  1077. else if(decpt !== out.length && ostr.indexOf("E") === -1) {
  1078. jj = ostr.indexOf(".")-1;
  1079. for(i=decpt; i>= 0; --i) {
  1080. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  1081. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
  1082. vv = out[i].v.substr(j+1);
  1083. for(; j>=0; --j) {
  1084. if(jj>=0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#")) vv = ostr.charAt(jj--) + vv;
  1085. }
  1086. out[i].v = vv;
  1087. out[i].t = 't';
  1088. lasti = i;
  1089. }
  1090. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  1091. jj = ostr.indexOf(".")+1;
  1092. for(i=decpt; i<out.length; ++i) {
  1093. if(out[i] == null || ('n?('.indexOf(out[i].t) === -1 && i !== decpt)) continue;
  1094. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
  1095. vv = out[i].v.substr(0,j);
  1096. for(; j<out[i].v.length; ++j) {
  1097. if(jj<ostr.length) vv += ostr.charAt(jj++);
  1098. }
  1099. out[i].v = vv;
  1100. out[i].t = 't';
  1101. lasti = i;
  1102. }
  1103. }
  1104. }
  1105. for(i=0; i<out.length; ++i) if(out[i] != null && 'n?'.indexOf(out[i].t)>-1) {
  1106. myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
  1107. out[i].v = write_num(out[i].t, out[i].v, myv);
  1108. out[i].t = 't';
  1109. }
  1110. var retval = "";
  1111. for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
  1112. return retval;
  1113. }
  1114. var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
  1115. function chkcond(v, rr) {
  1116. if(rr == null) return false;
  1117. var thresh = parseFloat(rr[2]);
  1118. switch(rr[1]) {
  1119. case "=": if(v == thresh) return true; break;
  1120. case ">": if(v > thresh) return true; break;
  1121. case "<": if(v < thresh) return true; break;
  1122. case "<>": if(v != thresh) return true; break;
  1123. case ">=": if(v >= thresh) return true; break;
  1124. case "<=": if(v <= thresh) return true; break;
  1125. }
  1126. return false;
  1127. }
  1128. function choose_fmt(f, v) {
  1129. var fmt = SSF_split_fmt(f);
  1130. var l = fmt.length, lat = fmt[l-1].indexOf("@");
  1131. if(l<4 && lat>-1) --l;
  1132. if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
  1133. if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
  1134. switch(fmt.length) {
  1135. case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
  1136. case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
  1137. case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
  1138. case 4: break;
  1139. }
  1140. var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
  1141. if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
  1142. if(fmt[0].match(/\[[=<>]/) != null || fmt[1].match(/\[[=<>]/) != null) {
  1143. var m1 = fmt[0].match(cfregex2);
  1144. var m2 = fmt[1].match(cfregex2);
  1145. return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
  1146. }
  1147. return [l, ff];
  1148. }
  1149. function SSF_format(fmt,v,o) {
  1150. if(o == null) o = {};
  1151. var sfmt = "";
  1152. switch(typeof fmt) {
  1153. case "string":
  1154. if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
  1155. else sfmt = fmt;
  1156. break;
  1157. case "number":
  1158. if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
  1159. else sfmt = (o.table != null ? (o.table) : table_fmt)[fmt];
  1160. if(sfmt == null) sfmt = (o.table && o.table[SSF_default_map[fmt]]) || table_fmt[SSF_default_map[fmt]];
  1161. if(sfmt == null) sfmt = SSF_default_str[fmt] || "General";
  1162. break;
  1163. }
  1164. if(SSF_isgeneral(sfmt,0)) return SSF_general(v, o);
  1165. if(v instanceof Date) v = datenum_local(v, o.date1904);
  1166. var f = choose_fmt(sfmt, v);
  1167. if(SSF_isgeneral(f[1])) return SSF_general(v, o);
  1168. if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
  1169. else if(v === "" || v == null) return "";
  1170. return eval_fmt(f[1], v, o, f[0]);
  1171. }
  1172. function SSF_load(fmt, idx) {
  1173. if(typeof idx != 'number') {
  1174. idx = +idx || -1;
  1175. for(var i = 0; i < 0x0188; ++i) {
  1176. if(table_fmt[i] == undefined) { if(idx < 0) idx = i; continue; }
  1177. if(table_fmt[i] == fmt) { idx = i; break; }
  1178. }
  1179. if(idx < 0) idx = 0x187;
  1180. }
  1181. table_fmt[idx] = fmt;
  1182. return idx;
  1183. }
  1184. function SSF_load_table(tbl) {
  1185. for(var i=0; i!=0x0188; ++i)
  1186. if(tbl[i] !== undefined) SSF_load(tbl[i], i);
  1187. }
  1188. function make_ssf() {
  1189. table_fmt = SSF_init_table();
  1190. }
  1191. var SSF = {
  1192. format: SSF_format,
  1193. load: SSF_load,
  1194. _table: table_fmt,
  1195. load_table: SSF_load_table,
  1196. parse_date_code: SSF_parse_date_code,
  1197. is_date: fmt_is_date,
  1198. get_table: function get_table() { return SSF._table = table_fmt; }
  1199. };
  1200. var SSFImplicit/*{[number]:string}*/ = ({
  1201. "5": '"$"#,##0_);\\("$"#,##0\\)',
  1202. "6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  1203. "7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  1204. "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1205. "23": 'General', "24": 'General', "25": 'General', "26": 'General',
  1206. "27": 'm/d/yy', "28": 'm/d/yy', "29": 'm/d/yy', "30": 'm/d/yy', "31": 'm/d/yy',
  1207. "32": 'h:mm:ss', "33": 'h:mm:ss', "34": 'h:mm:ss', "35": 'h:mm:ss',
  1208. "36": 'm/d/yy',
  1209. "41": '_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
  1210. "42": '_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
  1211. "43": '_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
  1212. "44": '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
  1213. "50": 'm/d/yy', "51": 'm/d/yy', "52": 'm/d/yy', "53": 'm/d/yy', "54": 'm/d/yy',
  1214. "55": 'm/d/yy', "56": 'm/d/yy', "57": 'm/d/yy', "58": 'm/d/yy',
  1215. "59": '0',
  1216. "60": '0.00',
  1217. "61": '#,##0',
  1218. "62": '#,##0.00',
  1219. "63": '"$"#,##0_);\\("$"#,##0\\)',
  1220. "64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  1221. "65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  1222. "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1223. "67": '0%',
  1224. "68": '0.00%',
  1225. "69": '# ?/?',
  1226. "70": '# ??/??',
  1227. "71": 'm/d/yy',
  1228. "72": 'm/d/yy',
  1229. "73": 'd-mmm-yy',
  1230. "74": 'd-mmm',
  1231. "75": 'mmm-yy',
  1232. "76": 'h:mm',
  1233. "77": 'h:mm:ss',
  1234. "78": 'm/d/yy h:mm',
  1235. "79": 'mm:ss',
  1236. "80": '[h]:mm:ss',
  1237. "81": 'mmss.0'
  1238. });
  1239. /* dateNF parse TODO: move to SSF */
  1240. var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
  1241. function dateNF_regex(dateNF) {
  1242. var fmt = typeof dateNF == "number" ? table_fmt[dateNF] : dateNF;
  1243. fmt = fmt.replace(dateNFregex, "(\\d+)");
  1244. return new RegExp("^" + fmt + "$");
  1245. }
  1246. function dateNF_fix(str, dateNF, match) {
  1247. var Y = -1, m = -1, d = -1, H = -1, M = -1, S = -1;
  1248. (dateNF.match(dateNFregex)||[]).forEach(function(n, i) {
  1249. var v = parseInt(match[i+1], 10);
  1250. switch(n.toLowerCase().charAt(0)) {
  1251. case 'y': Y = v; break; case 'd': d = v; break;
  1252. case 'h': H = v; break; case 's': S = v; break;
  1253. case 'm': if(H >= 0) M = v; else m = v; break;
  1254. }
  1255. });
  1256. if(S >= 0 && M == -1 && m >= 0) { M = m; m = -1; }
  1257. var datestr = (("" + (Y>=0?Y: new Date().getFullYear())).slice(-4) + "-" + ("00" + (m>=1?m:1)).slice(-2) + "-" + ("00" + (d>=1?d:1)).slice(-2));
  1258. if(datestr.length == 7) datestr = "0" + datestr;
  1259. if(datestr.length == 8) datestr = "20" + datestr;
  1260. var timestr = (("00" + (H>=0?H:0)).slice(-2) + ":" + ("00" + (M>=0?M:0)).slice(-2) + ":" + ("00" + (S>=0?S:0)).slice(-2));
  1261. if(H == -1 && M == -1 && S == -1) return datestr;
  1262. if(Y == -1 && m == -1 && d == -1) return timestr;
  1263. return datestr + "T" + timestr;
  1264. }
  1265. /* table of bad formats written by third-party tools */
  1266. var bad_formats = {
  1267. "d.m": "d\\.m" // Issue #2571 Google Sheets writes invalid format 'd.m', correct format is 'd"."m' or 'd\\.m'
  1268. };
  1269. function SSF__load(fmt, idx) {
  1270. return SSF_load(bad_formats[fmt] || fmt, idx);
  1271. }
  1272. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  1273. /* vim: set ts=2: */
  1274. /*jshint eqnull:true */
  1275. /*exported CFB */
  1276. /*global Uint8Array:false, Uint16Array:false */
  1277. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  1278. /* vim: set ts=2: */
  1279. /*exported CRC32 */
  1280. var CRC32 = (function() {
  1281. var CRC32 = {};
  1282. CRC32.version = '1.2.0';
  1283. /* see perf/crc32table.js */
  1284. /*global Int32Array */
  1285. function signed_crc_table() {
  1286. var c = 0, table = new Array(256);
  1287. for(var n =0; n != 256; ++n){
  1288. c = n;
  1289. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1290. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1291. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1292. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1293. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1294. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1295. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1296. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1297. table[n] = c;
  1298. }
  1299. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  1300. }
  1301. var T0 = signed_crc_table();
  1302. function slice_by_16_tables(T) {
  1303. var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ;
  1304. for(n = 0; n != 256; ++n) table[n] = T[n];
  1305. for(n = 0; n != 256; ++n) {
  1306. v = T[n];
  1307. for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF];
  1308. }
  1309. var out = [];
  1310. for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);
  1311. return out;
  1312. }
  1313. var TT = slice_by_16_tables(T0);
  1314. var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
  1315. var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
  1316. var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
  1317. function crc32_bstr(bstr, seed) {
  1318. var C = seed ^ -1;
  1319. for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF];
  1320. return ~C;
  1321. }
  1322. function crc32_buf(B, seed) {
  1323. var C = seed ^ -1, L = B.length - 15, i = 0;
  1324. for(; i < L;) C =
  1325. Tf[B[i++] ^ (C & 255)] ^
  1326. Te[B[i++] ^ ((C >> 8) & 255)] ^
  1327. Td[B[i++] ^ ((C >> 16) & 255)] ^
  1328. Tc[B[i++] ^ (C >>> 24)] ^
  1329. Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^
  1330. T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^
  1331. T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
  1332. L += 15;
  1333. while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF];
  1334. return ~C;
  1335. }
  1336. function crc32_str(str, seed) {
  1337. var C = seed ^ -1;
  1338. for(var i = 0, L = str.length, c = 0, d = 0; i < L;) {
  1339. c = str.charCodeAt(i++);
  1340. if(c < 0x80) {
  1341. C = (C>>>8) ^ T0[(C^c)&0xFF];
  1342. } else if(c < 0x800) {
  1343. C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF];
  1344. C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];
  1345. } else if(c >= 0xD800 && c < 0xE000) {
  1346. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  1347. C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF];
  1348. C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF];
  1349. C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  1350. C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF];
  1351. } else {
  1352. C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF];
  1353. C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF];
  1354. C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];
  1355. }
  1356. }
  1357. return ~C;
  1358. }
  1359. CRC32.table = T0;
  1360. CRC32.bstr = crc32_bstr;
  1361. CRC32.buf = crc32_buf;
  1362. CRC32.str = crc32_str;
  1363. return CRC32;
  1364. })();
  1365. /* [MS-CFB] v20171201 */
  1366. var CFB = (function _CFB(){
  1367. var exports = {};
  1368. exports.version = '1.2.2';
  1369. /* [MS-CFB] 2.6.4 */
  1370. function namecmp(l, r) {
  1371. var L = l.split("/"), R = r.split("/");
  1372. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  1373. if((c = L[i].length - R[i].length)) return c;
  1374. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  1375. }
  1376. return L.length - R.length;
  1377. }
  1378. function dirname(p) {
  1379. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  1380. var c = p.lastIndexOf("/");
  1381. return (c === -1) ? p : p.slice(0, c+1);
  1382. }
  1383. function filename(p) {
  1384. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  1385. var c = p.lastIndexOf("/");
  1386. return (c === -1) ? p : p.slice(c+1);
  1387. }
  1388. /* -------------------------------------------------------------------------- */
  1389. /* DOS Date format:
  1390. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  1391. add 1980 to stored year
  1392. stored second should be doubled
  1393. */
  1394. /* write JS date to buf as a DOS date */
  1395. function write_dos_date(buf, date) {
  1396. if(typeof date === "string") date = new Date(date);
  1397. var hms = date.getHours();
  1398. hms = hms << 6 | date.getMinutes();
  1399. hms = hms << 5 | (date.getSeconds()>>>1);
  1400. buf.write_shift(2, hms);
  1401. var ymd = (date.getFullYear() - 1980);
  1402. ymd = ymd << 4 | (date.getMonth()+1);
  1403. ymd = ymd << 5 | date.getDate();
  1404. buf.write_shift(2, ymd);
  1405. }
  1406. /* read four bytes from buf and interpret as a DOS date */
  1407. function parse_dos_date(buf) {
  1408. var hms = buf.read_shift(2) & 0xFFFF;
  1409. var ymd = buf.read_shift(2) & 0xFFFF;
  1410. var val = new Date();
  1411. var d = ymd & 0x1F; ymd >>>= 5;
  1412. var m = ymd & 0x0F; ymd >>>= 4;
  1413. val.setMilliseconds(0);
  1414. val.setFullYear(ymd + 1980);
  1415. val.setMonth(m-1);
  1416. val.setDate(d);
  1417. var S = hms & 0x1F; hms >>>= 5;
  1418. var M = hms & 0x3F; hms >>>= 6;
  1419. val.setHours(hms);
  1420. val.setMinutes(M);
  1421. val.setSeconds(S<<1);
  1422. return val;
  1423. }
  1424. function parse_extra_field(blob) {
  1425. prep_blob(blob, 0);
  1426. var o = {};
  1427. var flags = 0;
  1428. while(blob.l <= blob.length - 4) {
  1429. var type = blob.read_shift(2);
  1430. var sz = blob.read_shift(2), tgt = blob.l + sz;
  1431. var p = {};
  1432. switch(type) {
  1433. /* UNIX-style Timestamps */
  1434. case 0x5455: {
  1435. flags = blob.read_shift(1);
  1436. if(flags & 1) p.mtime = blob.read_shift(4);
  1437. /* for some reason, CD flag corresponds to LFH */
  1438. if(sz > 5) {
  1439. if(flags & 2) p.atime = blob.read_shift(4);
  1440. if(flags & 4) p.ctime = blob.read_shift(4);
  1441. }
  1442. if(p.mtime) p.mt = new Date(p.mtime*1000);
  1443. } break;
  1444. /* ZIP64 Extended Information Field */
  1445. case 0x0001: {
  1446. var sz1 = blob.read_shift(4), sz2 = blob.read_shift(4);
  1447. p.usz = (sz2 * Math.pow(2,32) + sz1);
  1448. sz1 = blob.read_shift(4); sz2 = blob.read_shift(4);
  1449. p.csz = (sz2 * Math.pow(2,32) + sz1);
  1450. // NOTE: volume fields are skipped
  1451. } break;
  1452. }
  1453. blob.l = tgt;
  1454. o[type] = p;
  1455. }
  1456. return o;
  1457. }
  1458. var fs;
  1459. function get_fs() { return fs || (fs = _fs); }
  1460. function parse(file, options) {
  1461. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  1462. if((file[0] | 0x20) == 0x6d && (file[1]|0x20) == 0x69) return parse_mad(file, options);
  1463. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  1464. var mver = 3;
  1465. var ssz = 512;
  1466. var nmfs = 0; // number of mini FAT sectors
  1467. var difat_sec_cnt = 0;
  1468. var dir_start = 0;
  1469. var minifat_start = 0;
  1470. var difat_start = 0;
  1471. var fat_addrs = []; // locations of FAT sectors
  1472. /* [MS-CFB] 2.2 Compound File Header */
  1473. var blob = file.slice(0,512);
  1474. prep_blob(blob, 0);
  1475. /* major version */
  1476. var mv = check_get_mver(blob);
  1477. mver = mv[0];
  1478. switch(mver) {
  1479. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  1480. case 0: if(mv[1] == 0) return parse_zip(file, options);
  1481. /* falls through */
  1482. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  1483. }
  1484. /* reprocess header */
  1485. if(ssz !== 512) { blob = file.slice(0,ssz); prep_blob(blob, 28 /* blob.l */); }
  1486. /* Save header for final object */
  1487. var header = file.slice(0,ssz);
  1488. check_shifts(blob, mver);
  1489. // Number of Directory Sectors
  1490. var dir_cnt = blob.read_shift(4, 'i');
  1491. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  1492. // Number of FAT Sectors
  1493. blob.l += 4;
  1494. // First Directory Sector Location
  1495. dir_start = blob.read_shift(4, 'i');
  1496. // Transaction Signature
  1497. blob.l += 4;
  1498. // Mini Stream Cutoff Size
  1499. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  1500. // First Mini FAT Sector Location
  1501. minifat_start = blob.read_shift(4, 'i');
  1502. // Number of Mini FAT Sectors
  1503. nmfs = blob.read_shift(4, 'i');
  1504. // First DIFAT sector location
  1505. difat_start = blob.read_shift(4, 'i');
  1506. // Number of DIFAT Sectors
  1507. difat_sec_cnt = blob.read_shift(4, 'i');
  1508. // Grab FAT Sector Locations
  1509. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  1510. q = blob.read_shift(4, 'i');
  1511. if(q<0) break;
  1512. fat_addrs[j] = q;
  1513. }
  1514. /** Break the file up into sectors */
  1515. var sectors = sectorify(file, ssz);
  1516. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  1517. /** Chains */
  1518. var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  1519. sector_list[dir_start].name = "!Directory";
  1520. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  1521. sector_list[fat_addrs[0]].name = "!FAT";
  1522. sector_list.fat_addrs = fat_addrs;
  1523. sector_list.ssz = ssz;
  1524. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  1525. var files = {}, Paths = [], FileIndex = [], FullPaths = [];
  1526. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  1527. build_full_paths(FileIndex, FullPaths, Paths);
  1528. Paths.shift();
  1529. var o = {
  1530. FileIndex: FileIndex,
  1531. FullPaths: FullPaths
  1532. };
  1533. // $FlowIgnore
  1534. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  1535. return o;
  1536. } // parse
  1537. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  1538. function check_get_mver(blob) {
  1539. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  1540. // header signature 8
  1541. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  1542. // clsid 16
  1543. //blob.chk(HEADER_CLSID, 'CLSID: ');
  1544. blob.l += 16;
  1545. // minor version 2
  1546. var mver = blob.read_shift(2, 'u');
  1547. return [blob.read_shift(2,'u'), mver];
  1548. }
  1549. function check_shifts(blob, mver) {
  1550. var shift = 0x09;
  1551. // Byte Order
  1552. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  1553. blob.l += 2;
  1554. // Sector Shift
  1555. switch((shift = blob.read_shift(2))) {
  1556. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  1557. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  1558. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  1559. }
  1560. // Mini Sector Shift
  1561. blob.chk('0600', 'Mini Sector Shift: ');
  1562. // Reserved
  1563. blob.chk('000000000000', 'Reserved: ');
  1564. }
  1565. /** Break the file up into sectors */
  1566. function sectorify(file, ssz) {
  1567. var nsectors = Math.ceil(file.length/ssz)-1;
  1568. var sectors = [];
  1569. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  1570. sectors[nsectors-1] = file.slice(nsectors*ssz);
  1571. return sectors;
  1572. }
  1573. /* [MS-CFB] 2.6.4 Red-Black Tree */
  1574. function build_full_paths(FI, FP, Paths) {
  1575. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  1576. var dad = [], q = [];
  1577. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  1578. for(; j < q.length; ++j) {
  1579. i = q[j];
  1580. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  1581. if(dad[i] === i) {
  1582. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  1583. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  1584. }
  1585. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  1586. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  1587. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  1588. }
  1589. for(i=1; i < pl; ++i) if(dad[i] === i) {
  1590. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  1591. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  1592. }
  1593. for(i=1; i < pl; ++i) {
  1594. if(FI[i].type === 0 /* unknown */) continue;
  1595. j = i;
  1596. if(j != dad[j]) do {
  1597. j = dad[j];
  1598. FP[i] = FP[j] + "/" + FP[i];
  1599. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  1600. dad[i] = -1;
  1601. }
  1602. FP[0] += "/";
  1603. for(i=1; i < pl; ++i) {
  1604. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  1605. }
  1606. }
  1607. function get_mfat_entry(entry, payload, mini) {
  1608. var start = entry.start, size = entry.size;
  1609. //return (payload.slice(start*MSSZ, start*MSSZ + size));
  1610. var o = [];
  1611. var idx = start;
  1612. while(mini && size > 0 && idx >= 0) {
  1613. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  1614. size -= MSSZ;
  1615. idx = __readInt32LE(mini, idx * 4);
  1616. }
  1617. if(o.length === 0) return (new_buf(0));
  1618. return (bconcat(o).slice(0, entry.size));
  1619. }
  1620. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  1621. DIFAT chains by storing the next sector number as the last 32 bits */
  1622. function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
  1623. var q = ENDOFCHAIN;
  1624. if(idx === ENDOFCHAIN) {
  1625. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  1626. } else if(idx !== -1 /*FREESECT*/) {
  1627. var sector = sectors[idx], m = (ssz>>>2)-1;
  1628. if(!sector) return;
  1629. for(var i = 0; i < m; ++i) {
  1630. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  1631. fat_addrs.push(q);
  1632. }
  1633. if(cnt >= 1) sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  1634. }
  1635. }
  1636. /** Follow the linked list of sectors for a given starting point */
  1637. function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
  1638. var buf = [], buf_chain = [];
  1639. if(!chkd) chkd = [];
  1640. var modulus = ssz - 1, j = 0, jj = 0;
  1641. for(j=start; j>=0;) {
  1642. chkd[j] = true;
  1643. buf[buf.length] = j;
  1644. buf_chain.push(sectors[j]);
  1645. var addr = fat_addrs[Math.floor(j*4/ssz)];
  1646. jj = ((j*4) & modulus);
  1647. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  1648. if(!sectors[addr]) break;
  1649. j = __readInt32LE(sectors[addr], jj);
  1650. }
  1651. return {nodes: buf, data:__toBuffer([buf_chain])};
  1652. }
  1653. /** Chase down the sector linked lists */
  1654. function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
  1655. var sl = sectors.length, sector_list = ([]);
  1656. var chkd = [], buf = [], buf_chain = [];
  1657. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  1658. for(i=0; i < sl; ++i) {
  1659. buf = ([]);
  1660. k = (i + dir_start); if(k >= sl) k-=sl;
  1661. if(chkd[k]) continue;
  1662. buf_chain = [];
  1663. var seen = [];
  1664. for(j=k; j>=0;) {
  1665. seen[j] = true;
  1666. chkd[j] = true;
  1667. buf[buf.length] = j;
  1668. buf_chain.push(sectors[j]);
  1669. var addr = fat_addrs[Math.floor(j*4/ssz)];
  1670. jj = ((j*4) & modulus);
  1671. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  1672. if(!sectors[addr]) break;
  1673. j = __readInt32LE(sectors[addr], jj);
  1674. if(seen[j]) break;
  1675. }
  1676. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])});
  1677. }
  1678. return sector_list;
  1679. }
  1680. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  1681. function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
  1682. var minifat_store = 0, pl = (Paths.length?2:0);
  1683. var sector = sector_list[dir_start].data;
  1684. var i = 0, namelen = 0, name;
  1685. for(; i < sector.length; i+= 128) {
  1686. var blob = sector.slice(i, i+128);
  1687. prep_blob(blob, 64);
  1688. namelen = blob.read_shift(2);
  1689. name = __utf16le(blob,0,namelen-pl);
  1690. Paths.push(name);
  1691. var o = ({
  1692. name: name,
  1693. type: blob.read_shift(1),
  1694. color: blob.read_shift(1),
  1695. L: blob.read_shift(4, 'i'),
  1696. R: blob.read_shift(4, 'i'),
  1697. C: blob.read_shift(4, 'i'),
  1698. clsid: blob.read_shift(16),
  1699. state: blob.read_shift(4, 'i'),
  1700. start: 0,
  1701. size: 0
  1702. });
  1703. var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  1704. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  1705. var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  1706. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  1707. o.start = blob.read_shift(4, 'i');
  1708. o.size = blob.read_shift(4, 'i');
  1709. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  1710. if(o.type === 5) { /* root */
  1711. minifat_store = o.start;
  1712. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  1713. /*minifat_size = o.size;*/
  1714. } else if(o.size >= 4096 /* MSCSZ */) {
  1715. o.storage = 'fat';
  1716. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  1717. sector_list[o.start].name = o.name;
  1718. o.content = (sector_list[o.start].data.slice(0,o.size));
  1719. } else {
  1720. o.storage = 'minifat';
  1721. if(o.size < 0) o.size = 0;
  1722. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  1723. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  1724. }
  1725. }
  1726. if(o.content) prep_blob(o.content, 0);
  1727. files[name] = o;
  1728. FileIndex.push(o);
  1729. }
  1730. }
  1731. function read_date(blob, offset) {
  1732. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  1733. }
  1734. function read_file(filename, options) {
  1735. get_fs();
  1736. return parse(fs.readFileSync(filename), options);
  1737. }
  1738. function read(blob, options) {
  1739. var type = options && options.type;
  1740. if(!type) {
  1741. if(has_buf && Buffer.isBuffer(blob)) type = "buffer";
  1742. }
  1743. switch(type || "base64") {
  1744. case "file": return read_file(blob, options);
  1745. case "base64": return parse(s2a(Base64_decode(blob)), options);
  1746. case "binary": return parse(s2a(blob), options);
  1747. }
  1748. return parse(blob, options);
  1749. }
  1750. function init_cfb(cfb, opts) {
  1751. var o = opts || {}, root = o.root || "Root Entry";
  1752. if(!cfb.FullPaths) cfb.FullPaths = [];
  1753. if(!cfb.FileIndex) cfb.FileIndex = [];
  1754. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  1755. if(cfb.FullPaths.length === 0) {
  1756. cfb.FullPaths[0] = root + "/";
  1757. cfb.FileIndex[0] = ({ name: root, type: 5 });
  1758. }
  1759. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  1760. seed_cfb(cfb);
  1761. }
  1762. function seed_cfb(cfb) {
  1763. var nm = "\u0001Sh33tJ5";
  1764. if(CFB.find(cfb, "/" + nm)) return;
  1765. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  1766. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }));
  1767. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  1768. rebuild_cfb(cfb);
  1769. }
  1770. function rebuild_cfb(cfb, f) {
  1771. init_cfb(cfb);
  1772. var gc = false, s = false;
  1773. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  1774. var _file = cfb.FileIndex[i];
  1775. switch(_file.type) {
  1776. case 0:
  1777. if(s) gc = true;
  1778. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  1779. break;
  1780. case 1: case 2: case 5:
  1781. s = true;
  1782. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  1783. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  1784. break;
  1785. default: gc = true; break;
  1786. }
  1787. }
  1788. if(!gc && !f) return;
  1789. var now = new Date(1987, 1, 19), j = 0;
  1790. // Track which names exist
  1791. var fullPaths = Object.create ? Object.create(null) : {};
  1792. var data = [];
  1793. for(i = 0; i < cfb.FullPaths.length; ++i) {
  1794. fullPaths[cfb.FullPaths[i]] = true;
  1795. if(cfb.FileIndex[i].type === 0) continue;
  1796. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  1797. }
  1798. for(i = 0; i < data.length; ++i) {
  1799. var dad = dirname(data[i][0]);
  1800. s = fullPaths[dad];
  1801. while(!s) {
  1802. while(dirname(dad) && !fullPaths[dirname(dad)]) dad = dirname(dad);
  1803. data.push([dad, ({
  1804. name: filename(dad).replace("/",""),
  1805. type: 1,
  1806. clsid: HEADER_CLSID,
  1807. ct: now, mt: now,
  1808. content: null
  1809. })]);
  1810. // Add name to set
  1811. fullPaths[dad] = true;
  1812. dad = dirname(data[i][0]);
  1813. s = fullPaths[dad];
  1814. }
  1815. }
  1816. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  1817. cfb.FullPaths = []; cfb.FileIndex = [];
  1818. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  1819. for(i = 0; i < data.length; ++i) {
  1820. var elt = cfb.FileIndex[i];
  1821. var nm = cfb.FullPaths[i];
  1822. elt.name = filename(nm).replace("/","");
  1823. elt.L = elt.R = elt.C = -(elt.color = 1);
  1824. elt.size = elt.content ? elt.content.length : 0;
  1825. elt.start = 0;
  1826. elt.clsid = (elt.clsid || HEADER_CLSID);
  1827. if(i === 0) {
  1828. elt.C = data.length > 1 ? 1 : -1;
  1829. elt.size = 0;
  1830. elt.type = 5;
  1831. } else if(nm.slice(-1) == "/") {
  1832. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  1833. elt.C = j >= data.length ? -1 : j;
  1834. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  1835. elt.R = j >= data.length ? -1 : j;
  1836. elt.type = 1;
  1837. } else {
  1838. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  1839. elt.type = 2;
  1840. }
  1841. }
  1842. }
  1843. function _write(cfb, options) {
  1844. var _opts = options || {};
  1845. /* MAD is order-sensitive, skip rebuild and sort */
  1846. if(_opts.fileType == 'mad') return write_mad(cfb, _opts);
  1847. rebuild_cfb(cfb);
  1848. switch(_opts.fileType) {
  1849. case 'zip': return write_zip(cfb, _opts);
  1850. //case 'mad': return write_mad(cfb, _opts);
  1851. }
  1852. var L = (function(cfb){
  1853. var mini_size = 0, fat_size = 0;
  1854. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  1855. var file = cfb.FileIndex[i];
  1856. if(!file.content) continue;
  1857. var flen = file.content.length;
  1858. if(flen > 0){
  1859. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  1860. else fat_size += (flen + 0x01FF) >> 9;
  1861. }
  1862. }
  1863. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  1864. var mini_cnt = (mini_size + 7) >> 3;
  1865. var mfat_cnt = (mini_size + 0x7F) >> 7;
  1866. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  1867. var fat_cnt = (fat_base + 0x7F) >> 7;
  1868. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  1869. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  1870. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  1871. cfb.FileIndex[0].size = mini_size << 6;
  1872. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  1873. return L;
  1874. })(cfb);
  1875. var o = new_buf(L[7] << 9);
  1876. var i = 0, T = 0;
  1877. {
  1878. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  1879. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  1880. o.write_shift(2, 0x003E);
  1881. o.write_shift(2, 0x0003);
  1882. o.write_shift(2, 0xFFFE);
  1883. o.write_shift(2, 0x0009);
  1884. o.write_shift(2, 0x0006);
  1885. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  1886. o.write_shift(4, 0);
  1887. o.write_shift(4, L[2]);
  1888. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  1889. o.write_shift(4, 0);
  1890. o.write_shift(4, 1<<12);
  1891. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  1892. o.write_shift(4, L[3]);
  1893. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  1894. o.write_shift(4, L[1]);
  1895. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  1896. }
  1897. if(L[1]) {
  1898. for(T = 0; T < L[1]; ++T) {
  1899. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  1900. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  1901. }
  1902. }
  1903. var chainit = function(w) {
  1904. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  1905. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  1906. };
  1907. T = i = 0;
  1908. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  1909. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  1910. chainit(L[3]);
  1911. chainit(L[4]);
  1912. var j = 0, flen = 0;
  1913. var file = cfb.FileIndex[0];
  1914. for(; j < cfb.FileIndex.length; ++j) {
  1915. file = cfb.FileIndex[j];
  1916. if(!file.content) continue;
  1917. flen = file.content.length;
  1918. if(flen < 0x1000) continue;
  1919. file.start = T;
  1920. chainit((flen + 0x01FF) >> 9);
  1921. }
  1922. chainit((L[6] + 7) >> 3);
  1923. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  1924. T = i = 0;
  1925. for(j = 0; j < cfb.FileIndex.length; ++j) {
  1926. file = cfb.FileIndex[j];
  1927. if(!file.content) continue;
  1928. flen = file.content.length;
  1929. if(!flen || flen >= 0x1000) continue;
  1930. file.start = T;
  1931. chainit((flen + 0x3F) >> 6);
  1932. }
  1933. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  1934. for(i = 0; i < L[4]<<2; ++i) {
  1935. var nm = cfb.FullPaths[i];
  1936. if(!nm || nm.length === 0) {
  1937. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  1938. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  1939. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  1940. continue;
  1941. }
  1942. file = cfb.FileIndex[i];
  1943. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  1944. var _nm = (i === 0 && _opts.root) || file.name;
  1945. if(_nm.length > 32) {
  1946. console.error("Name " + _nm + " will be truncated to " + _nm.slice(0,32));
  1947. _nm = _nm.slice(0, 32);
  1948. }
  1949. flen = 2*(_nm.length+1);
  1950. o.write_shift(64, _nm, "utf16le");
  1951. o.write_shift(2, flen);
  1952. o.write_shift(1, file.type);
  1953. o.write_shift(1, file.color);
  1954. o.write_shift(-4, file.L);
  1955. o.write_shift(-4, file.R);
  1956. o.write_shift(-4, file.C);
  1957. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  1958. else o.write_shift(16, file.clsid, "hex");
  1959. o.write_shift(4, file.state || 0);
  1960. o.write_shift(4, 0); o.write_shift(4, 0);
  1961. o.write_shift(4, 0); o.write_shift(4, 0);
  1962. o.write_shift(4, file.start);
  1963. o.write_shift(4, file.size); o.write_shift(4, 0);
  1964. }
  1965. for(i = 1; i < cfb.FileIndex.length; ++i) {
  1966. file = cfb.FileIndex[i];
  1967. if(file.size >= 0x1000) {
  1968. o.l = (file.start+1) << 9;
  1969. if (has_buf && Buffer.isBuffer(file.content)) {
  1970. file.content.copy(o, o.l, 0, file.size);
  1971. // o is a 0-filled Buffer so just set next offset
  1972. o.l += (file.size + 511) & -512;
  1973. } else {
  1974. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  1975. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  1976. }
  1977. }
  1978. }
  1979. for(i = 1; i < cfb.FileIndex.length; ++i) {
  1980. file = cfb.FileIndex[i];
  1981. if(file.size > 0 && file.size < 0x1000) {
  1982. if (has_buf && Buffer.isBuffer(file.content)) {
  1983. file.content.copy(o, o.l, 0, file.size);
  1984. // o is a 0-filled Buffer so just set next offset
  1985. o.l += (file.size + 63) & -64;
  1986. } else {
  1987. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  1988. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  1989. }
  1990. }
  1991. }
  1992. if (has_buf) {
  1993. o.l = o.length;
  1994. } else {
  1995. // When using Buffer, already 0-filled
  1996. while(o.l < o.length) o.write_shift(1, 0);
  1997. }
  1998. return o;
  1999. }
  2000. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  2001. function find(cfb, path) {
  2002. var UCFullPaths = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  2003. var UCPaths = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  2004. var k = false;
  2005. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  2006. else k = path.indexOf("/") !== -1;
  2007. var UCPath = path.toUpperCase();
  2008. var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  2009. if(w !== -1) return cfb.FileIndex[w];
  2010. var m = !UCPath.match(chr1);
  2011. UCPath = UCPath.replace(chr0,'');
  2012. if(m) UCPath = UCPath.replace(chr1,'!');
  2013. for(w = 0; w < UCFullPaths.length; ++w) {
  2014. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  2015. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  2016. }
  2017. return null;
  2018. }
  2019. /** CFB Constants */
  2020. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  2021. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  2022. /* 2.1 Compound File Sector Numbers and Types */
  2023. var ENDOFCHAIN = -2;
  2024. /* 2.2 Compound File Header */
  2025. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  2026. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  2027. var HEADER_CLSID = '00000000000000000000000000000000';
  2028. var consts = {
  2029. /* 2.1 Compund File Sector Numbers and Types */
  2030. MAXREGSECT: -6,
  2031. DIFSECT: -4,
  2032. FATSECT: -3,
  2033. ENDOFCHAIN: ENDOFCHAIN,
  2034. FREESECT: -1,
  2035. /* 2.2 Compound File Header */
  2036. HEADER_SIGNATURE: HEADER_SIGNATURE,
  2037. HEADER_MINOR_VERSION: '3e00',
  2038. MAXREGSID: -6,
  2039. NOSTREAM: -1,
  2040. HEADER_CLSID: HEADER_CLSID,
  2041. /* 2.6.1 Compound File Directory Entry */
  2042. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  2043. };
  2044. function write_file(cfb, filename, options) {
  2045. get_fs();
  2046. var o = _write(cfb, options);
  2047. fs.writeFileSync(filename, o);
  2048. }
  2049. function a2s(o) {
  2050. var out = new Array(o.length);
  2051. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  2052. return out.join("");
  2053. }
  2054. function write(cfb, options) {
  2055. var o = _write(cfb, options);
  2056. switch(options && options.type || "buffer") {
  2057. case "file": get_fs(); fs.writeFileSync(options.filename, (o)); return o;
  2058. case "binary": return typeof o == "string" ? o : a2s(o);
  2059. case "base64": return Base64_encode(typeof o == "string" ? o : a2s(o));
  2060. case "buffer": if(has_buf) return Buffer.isBuffer(o) ? o : Buffer_from(o);
  2061. /* falls through */
  2062. case "array": return typeof o == "string" ? s2a(o) : o;
  2063. }
  2064. return o;
  2065. }
  2066. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  2067. var _zlib;
  2068. function use_zlib(zlib) { try {
  2069. var InflateRaw = zlib.InflateRaw;
  2070. var InflRaw = new InflateRaw();
  2071. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  2072. if(InflRaw.bytesRead) _zlib = zlib;
  2073. else throw new Error("zlib does not expose bytesRead");
  2074. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  2075. function _inflateRawSync(payload, usz) {
  2076. if(!_zlib) return _inflate(payload, usz);
  2077. var InflateRaw = _zlib.InflateRaw;
  2078. var InflRaw = new InflateRaw();
  2079. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  2080. payload.l += InflRaw.bytesRead;
  2081. return out;
  2082. }
  2083. function _deflateRawSync(payload) {
  2084. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  2085. }
  2086. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  2087. /* 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 ]; */
  2088. 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 ];
  2089. /* 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 ]; */
  2090. 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 ];
  2091. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  2092. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  2093. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  2094. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  2095. function bit_swap_n(n, b) {
  2096. var rev = bitswap8[n & 0xFF];
  2097. if(b <= 8) return rev >>> (8-b);
  2098. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  2099. if(b <= 16) return rev >>> (16-b);
  2100. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  2101. return rev >>> (24-b);
  2102. }
  2103. /* helpers for unaligned bit reads */
  2104. 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; }
  2105. 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; }
  2106. 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; }
  2107. 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; }
  2108. 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; }
  2109. /* works up to n = 3 * 8 + 1 = 25 */
  2110. function read_bits_n(buf, bl, n) {
  2111. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  2112. var v = buf[h] >>> w;
  2113. if(n < 8 - w) return v & f;
  2114. v |= buf[h+1]<<(8-w);
  2115. if(n < 16 - w) return v & f;
  2116. v |= buf[h+2]<<(16-w);
  2117. if(n < 24 - w) return v & f;
  2118. v |= buf[h+3]<<(24-w);
  2119. return v & f;
  2120. }
  2121. /* helpers for unaligned bit writes */
  2122. function write_bits_3(buf, bl, v) { var w = bl & 7, h = bl >>> 3;
  2123. if(w <= 5) buf[h] |= (v & 7) << w;
  2124. else {
  2125. buf[h] |= (v << w) & 0xFF;
  2126. buf[h+1] = (v&7) >> (8-w);
  2127. }
  2128. return bl + 3;
  2129. }
  2130. function write_bits_1(buf, bl, v) {
  2131. var w = bl & 7, h = bl >>> 3;
  2132. v = (v&1) << w;
  2133. buf[h] |= v;
  2134. return bl + 1;
  2135. }
  2136. function write_bits_8(buf, bl, v) {
  2137. var w = bl & 7, h = bl >>> 3;
  2138. v <<= w;
  2139. buf[h] |= v & 0xFF; v >>>= 8;
  2140. buf[h+1] = v;
  2141. return bl + 8;
  2142. }
  2143. function write_bits_16(buf, bl, v) {
  2144. var w = bl & 7, h = bl >>> 3;
  2145. v <<= w;
  2146. buf[h] |= v & 0xFF; v >>>= 8;
  2147. buf[h+1] = v & 0xFF;
  2148. buf[h+2] = v >>> 8;
  2149. return bl + 16;
  2150. }
  2151. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  2152. function realloc(b, sz) {
  2153. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  2154. if(L >= sz) return b;
  2155. if(has_buf) {
  2156. var o = new_unsafe_buf(M);
  2157. // $FlowIgnore
  2158. if(b.copy) b.copy(o);
  2159. else for(; i < b.length; ++i) o[i] = b[i];
  2160. return o;
  2161. } else if(use_typed_arrays) {
  2162. var a = new Uint8Array(M);
  2163. if(a.set) a.set(b);
  2164. else for(; i < L; ++i) a[i] = b[i];
  2165. return a;
  2166. }
  2167. b.length = M;
  2168. return b;
  2169. }
  2170. /* zero-filled arrays for older browsers */
  2171. function zero_fill_array(n) {
  2172. var o = new Array(n);
  2173. for(var i = 0; i < n; ++i) o[i] = 0;
  2174. return o;
  2175. }
  2176. /* build tree (used for literals and lengths) */
  2177. function build_tree(clens, cmap, MAX) {
  2178. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  2179. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  2180. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  2181. for(i = L; i < MAX; ++i) clens[i] = 0;
  2182. L = clens.length;
  2183. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  2184. /* build code tree */
  2185. for(i = 0; i < L; ++i) {
  2186. bl_count[(w = clens[i])]++;
  2187. if(maxlen < w) maxlen = w;
  2188. ctree[i] = 0;
  2189. }
  2190. bl_count[0] = 0;
  2191. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  2192. for(i = 0; i < L; ++i) {
  2193. ccode = clens[i];
  2194. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  2195. }
  2196. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  2197. var cleni = 0;
  2198. for(i = 0; i < L; ++i) {
  2199. cleni = clens[i];
  2200. if(cleni != 0) {
  2201. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  2202. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  2203. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  2204. }
  2205. }
  2206. return maxlen;
  2207. }
  2208. /* Fixed Huffman */
  2209. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  2210. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  2211. if(!use_typed_arrays) {
  2212. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  2213. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  2214. }
  2215. (function() {
  2216. var dlens = [];
  2217. var i = 0;
  2218. for(;i<32; i++) dlens.push(5);
  2219. build_tree(dlens, fix_dmap, 32);
  2220. var clens = [];
  2221. i = 0;
  2222. for(; i<=143; i++) clens.push(8);
  2223. for(; i<=255; i++) clens.push(9);
  2224. for(; i<=279; i++) clens.push(7);
  2225. for(; i<=287; i++) clens.push(8);
  2226. build_tree(clens, fix_lmap, 288);
  2227. })();var _deflateRaw = (function _deflateRawIIFE() {
  2228. var DST_LN_RE = use_typed_arrays ? new Uint8Array(0x8000) : [];
  2229. var j = 0, k = 0;
  2230. for(; j < DST_LN.length - 1; ++j) {
  2231. for(; k < DST_LN[j+1]; ++k) DST_LN_RE[k] = j;
  2232. }
  2233. for(;k < 32768; ++k) DST_LN_RE[k] = 29;
  2234. var LEN_LN_RE = use_typed_arrays ? new Uint8Array(0x103) : [];
  2235. for(j = 0, k = 0; j < LEN_LN.length - 1; ++j) {
  2236. for(; k < LEN_LN[j+1]; ++k) LEN_LN_RE[k] = j;
  2237. }
  2238. function write_stored(data, out) {
  2239. var boff = 0;
  2240. while(boff < data.length) {
  2241. var L = Math.min(0xFFFF, data.length - boff);
  2242. var h = boff + L == data.length;
  2243. out.write_shift(1, +h);
  2244. out.write_shift(2, L);
  2245. out.write_shift(2, (~L) & 0xFFFF);
  2246. while(L-- > 0) out[out.l++] = data[boff++];
  2247. }
  2248. return out.l;
  2249. }
  2250. /* Fixed Huffman */
  2251. function write_huff_fixed(data, out) {
  2252. var bl = 0;
  2253. var boff = 0;
  2254. var addrs = use_typed_arrays ? new Uint16Array(0x8000) : [];
  2255. while(boff < data.length) {
  2256. var L = /* data.length - boff; */ Math.min(0xFFFF, data.length - boff);
  2257. /* write a stored block for short data */
  2258. if(L < 10) {
  2259. bl = write_bits_3(out, bl, +!!(boff + L == data.length)); // jshint ignore:line
  2260. if(bl & 7) bl += 8 - (bl & 7);
  2261. out.l = (bl / 8) | 0;
  2262. out.write_shift(2, L);
  2263. out.write_shift(2, (~L) & 0xFFFF);
  2264. while(L-- > 0) out[out.l++] = data[boff++];
  2265. bl = out.l * 8;
  2266. continue;
  2267. }
  2268. bl = write_bits_3(out, bl, +!!(boff + L == data.length) + 2); // jshint ignore:line
  2269. var hash = 0;
  2270. while(L-- > 0) {
  2271. var d = data[boff];
  2272. hash = ((hash << 5) ^ d) & 0x7FFF;
  2273. var match = -1, mlen = 0;
  2274. if((match = addrs[hash])) {
  2275. match |= boff & ~0x7FFF;
  2276. if(match > boff) match -= 0x8000;
  2277. if(match < boff) while(data[match + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
  2278. }
  2279. if(mlen > 2) {
  2280. /* Copy Token */
  2281. d = LEN_LN_RE[mlen];
  2282. if(d <= 22) bl = write_bits_8(out, bl, bitswap8[d+1]>>1) - 1;
  2283. else {
  2284. write_bits_8(out, bl, 3);
  2285. bl += 5;
  2286. write_bits_8(out, bl, bitswap8[d-23]>>5);
  2287. bl += 3;
  2288. }
  2289. var len_eb = (d < 8) ? 0 : ((d - 4)>>2);
  2290. if(len_eb > 0) {
  2291. write_bits_16(out, bl, mlen - LEN_LN[d]);
  2292. bl += len_eb;
  2293. }
  2294. d = DST_LN_RE[boff - match];
  2295. bl = write_bits_8(out, bl, bitswap8[d]>>3);
  2296. bl -= 3;
  2297. var dst_eb = d < 4 ? 0 : (d-2)>>1;
  2298. if(dst_eb > 0) {
  2299. write_bits_16(out, bl, boff - match - DST_LN[d]);
  2300. bl += dst_eb;
  2301. }
  2302. for(var q = 0; q < mlen; ++q) {
  2303. addrs[hash] = boff & 0x7FFF;
  2304. hash = ((hash << 5) ^ data[boff]) & 0x7FFF;
  2305. ++boff;
  2306. }
  2307. L-= mlen - 1;
  2308. } else {
  2309. /* Literal Token */
  2310. if(d <= 143) d = d + 48;
  2311. else bl = write_bits_1(out, bl, 1);
  2312. bl = write_bits_8(out, bl, bitswap8[d]);
  2313. addrs[hash] = boff & 0x7FFF;
  2314. ++boff;
  2315. }
  2316. }
  2317. bl = write_bits_8(out, bl, 0) - 1;
  2318. }
  2319. out.l = ((bl + 7)/8)|0;
  2320. return out.l;
  2321. }
  2322. return function _deflateRaw(data, out) {
  2323. if(data.length < 8) return write_stored(data, out);
  2324. return write_huff_fixed(data, out);
  2325. };
  2326. })();
  2327. function _deflate(data) {
  2328. var buf = new_buf(50+Math.floor(data.length*1.1));
  2329. var off = _deflateRaw(data, buf);
  2330. return buf.slice(0, off);
  2331. }
  2332. /* modified inflate function also moves original read head */
  2333. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  2334. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  2335. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  2336. var dyn_len_1 = 1, dyn_len_2 = 1;
  2337. /* 5.5.3 Expanding Huffman Codes */
  2338. function dyn(data, boff) {
  2339. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  2340. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  2341. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  2342. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  2343. var w = 0;
  2344. /* grab and store code lengths */
  2345. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  2346. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  2347. var maxlen = 1;
  2348. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  2349. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  2350. var L = clens.length; /* 19 */
  2351. for(var i = 0; i < _HCLEN; ++i) {
  2352. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  2353. if(maxlen < w) maxlen = w;
  2354. bl_count[w]++;
  2355. boff += 3;
  2356. }
  2357. /* build code tree */
  2358. var ccode = 0;
  2359. bl_count[0] = 0;
  2360. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  2361. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  2362. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  2363. var cleni = 0;
  2364. for(i = 0; i < L; ++i) {
  2365. cleni = clens[i];
  2366. if(cleni != 0) {
  2367. ccode = bitswap8[ctree[i]]>>(8-cleni);
  2368. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  2369. }
  2370. }
  2371. /* read literal and dist codes at once */
  2372. var hcodes = [];
  2373. maxlen = 1;
  2374. for(; hcodes.length < _HLIT + _HDIST;) {
  2375. ccode = dyn_cmap[read_bits_7(data, boff)];
  2376. boff += ccode & 7;
  2377. switch((ccode >>>= 3)) {
  2378. case 16:
  2379. w = 3 + read_bits_2(data, boff); boff += 2;
  2380. ccode = hcodes[hcodes.length - 1];
  2381. while(w-- > 0) hcodes.push(ccode);
  2382. break;
  2383. case 17:
  2384. w = 3 + read_bits_3(data, boff); boff += 3;
  2385. while(w-- > 0) hcodes.push(0);
  2386. break;
  2387. case 18:
  2388. w = 11 + read_bits_7(data, boff); boff += 7;
  2389. while(w -- > 0) hcodes.push(0);
  2390. break;
  2391. default:
  2392. hcodes.push(ccode);
  2393. if(maxlen < ccode) maxlen = ccode;
  2394. break;
  2395. }
  2396. }
  2397. /* build literal / length trees */
  2398. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  2399. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  2400. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  2401. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  2402. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  2403. return boff;
  2404. }
  2405. /* return [ data, bytesRead ] */
  2406. function inflate(data, usz) {
  2407. /* shortcircuit for empty buffer [0x03, 0x00] */
  2408. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  2409. /* bit offset */
  2410. var boff = 0;
  2411. /* header includes final bit and type bits */
  2412. var header = 0;
  2413. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  2414. var woff = 0;
  2415. var OL = outbuf.length>>>0;
  2416. var max_len_1 = 0, max_len_2 = 0;
  2417. while((header&1) == 0) {
  2418. header = read_bits_3(data, boff); boff += 3;
  2419. if((header >>> 1) == 0) {
  2420. /* Stored block */
  2421. if(boff & 7) boff += 8 - (boff&7);
  2422. /* 2 bytes sz, 2 bytes bit inverse */
  2423. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  2424. boff += 32;
  2425. /* push sz bytes */
  2426. if(sz > 0) {
  2427. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  2428. while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  2429. }
  2430. continue;
  2431. } else if((header >> 1) == 1) {
  2432. /* Fixed Huffman */
  2433. max_len_1 = 9; max_len_2 = 5;
  2434. } else {
  2435. /* Dynamic Huffman */
  2436. boff = dyn(data, boff);
  2437. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  2438. }
  2439. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  2440. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  2441. /* ingest code and move read head */
  2442. var bits = read_bits_n(data, boff, max_len_1);
  2443. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  2444. boff += code & 15; code >>>= 4;
  2445. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  2446. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  2447. else if(code == 256) break;
  2448. else {
  2449. code -= 257;
  2450. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  2451. var tgt = woff + LEN_LN[code];
  2452. /* length extra bits */
  2453. if(len_eb > 0) {
  2454. tgt += read_bits_n(data, boff, len_eb);
  2455. boff += len_eb;
  2456. }
  2457. /* dist code */
  2458. bits = read_bits_n(data, boff, max_len_2);
  2459. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  2460. boff += code & 15; code >>>= 4;
  2461. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  2462. var dst = DST_LN[code];
  2463. /* dist extra bits */
  2464. if(dst_eb > 0) {
  2465. dst += read_bits_n(data, boff, dst_eb);
  2466. boff += dst_eb;
  2467. }
  2468. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  2469. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt + 100); OL = outbuf.length; }
  2470. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  2471. }
  2472. }
  2473. }
  2474. if(usz) return [outbuf, (boff+7)>>>3];
  2475. return [outbuf.slice(0, woff), (boff+7)>>>3];
  2476. }
  2477. function _inflate(payload, usz) {
  2478. var data = payload.slice(payload.l||0);
  2479. var out = inflate(data, usz);
  2480. payload.l += out[1];
  2481. return out[0];
  2482. }
  2483. function warn_or_throw(wrn, msg) {
  2484. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  2485. else throw new Error(msg);
  2486. }
  2487. function parse_zip(file, options) {
  2488. var blob = file;
  2489. prep_blob(blob, 0);
  2490. var FileIndex = [], FullPaths = [];
  2491. var o = {
  2492. FileIndex: FileIndex,
  2493. FullPaths: FullPaths
  2494. };
  2495. init_cfb(o, { root: options.root });
  2496. /* find end of central directory, start just after signature */
  2497. var i = blob.length - 4;
  2498. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  2499. blob.l = i + 4;
  2500. /* parse end of central directory */
  2501. blob.l += 4;
  2502. var fcnt = blob.read_shift(2);
  2503. blob.l += 6;
  2504. var start_cd = blob.read_shift(4);
  2505. /* parse central directory */
  2506. blob.l = start_cd;
  2507. for(i = 0; i < fcnt; ++i) {
  2508. /* trust local file header instead of CD entry */
  2509. blob.l += 20;
  2510. var csz = blob.read_shift(4);
  2511. var usz = blob.read_shift(4);
  2512. var namelen = blob.read_shift(2);
  2513. var efsz = blob.read_shift(2);
  2514. var fcsz = blob.read_shift(2);
  2515. blob.l += 8;
  2516. var offset = blob.read_shift(4);
  2517. var EF = parse_extra_field(blob.slice(blob.l+namelen, blob.l+namelen+efsz));
  2518. blob.l += namelen + efsz + fcsz;
  2519. var L = blob.l;
  2520. blob.l = offset + 4;
  2521. /* ZIP64 lengths */
  2522. if(EF && EF[0x0001]) {
  2523. if((EF[0x0001]||{}).usz) usz = EF[0x0001].usz;
  2524. if((EF[0x0001]||{}).csz) csz = EF[0x0001].csz;
  2525. }
  2526. parse_local_file(blob, csz, usz, o, EF);
  2527. blob.l = L;
  2528. }
  2529. return o;
  2530. }
  2531. /* head starts just after local file header signature */
  2532. function parse_local_file(blob, csz, usz, o, EF) {
  2533. /* [local file header] */
  2534. blob.l += 2;
  2535. var flags = blob.read_shift(2);
  2536. var meth = blob.read_shift(2);
  2537. var date = parse_dos_date(blob);
  2538. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  2539. var crc32 = blob.read_shift(4);
  2540. var _csz = blob.read_shift(4);
  2541. var _usz = blob.read_shift(4);
  2542. var namelen = blob.read_shift(2);
  2543. var efsz = blob.read_shift(2);
  2544. // TODO: flags & (1<<11) // UTF8
  2545. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  2546. if(efsz) {
  2547. var ef = parse_extra_field(blob.slice(blob.l, blob.l + efsz));
  2548. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  2549. if((ef[0x0001]||{}).usz) _usz = ef[0x0001].usz;
  2550. if((ef[0x0001]||{}).csz) _csz = ef[0x0001].csz;
  2551. if(EF) {
  2552. if((EF[0x5455]||{}).mt) date = EF[0x5455].mt;
  2553. if((EF[0x0001]||{}).usz) _usz = ef[0x0001].usz;
  2554. if((EF[0x0001]||{}).csz) _csz = ef[0x0001].csz;
  2555. }
  2556. }
  2557. blob.l += efsz;
  2558. /* [encryption header] */
  2559. /* [file data] */
  2560. var data = blob.slice(blob.l, blob.l + _csz);
  2561. switch(meth) {
  2562. case 8: data = _inflateRawSync(blob, _usz); break;
  2563. case 0: break; // TODO: scan for magic number
  2564. default: throw new Error("Unsupported ZIP Compression method " + meth);
  2565. }
  2566. /* [data descriptor] */
  2567. var wrn = false;
  2568. if(flags & 8) {
  2569. crc32 = blob.read_shift(4);
  2570. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  2571. _csz = blob.read_shift(4);
  2572. _usz = blob.read_shift(4);
  2573. }
  2574. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  2575. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  2576. //var _crc32 = CRC32.buf(data, 0);
  2577. //if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  2578. cfb_add(o, name, data, {unsafe: true, mt: date});
  2579. }
  2580. function write_zip(cfb, options) {
  2581. var _opts = options || {};
  2582. var out = [], cdirs = [];
  2583. var o = new_buf(1);
  2584. var method = (_opts.compression ? 8 : 0), flags = 0;
  2585. var desc = false;
  2586. if(desc) flags |= 8;
  2587. var i = 0, j = 0;
  2588. var start_cd = 0, fcnt = 0;
  2589. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  2590. var crcs = [];
  2591. var sz_cd = 0;
  2592. for(i = 1; i < cfb.FullPaths.length; ++i) {
  2593. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  2594. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  2595. var start = start_cd;
  2596. /* TODO: CP437 filename */
  2597. var namebuf = new_buf(fp.length);
  2598. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  2599. namebuf = namebuf.slice(0, namebuf.l);
  2600. crcs[fcnt] = typeof fi.content == "string" ? CRC32.bstr(fi.content, 0) : CRC32.buf(fi.content, 0);
  2601. var outbuf = typeof fi.content == "string" ? s2a(fi.content) : fi.content;
  2602. if(method == 8) outbuf = _deflateRawSync(outbuf);
  2603. /* local file header */
  2604. o = new_buf(30);
  2605. o.write_shift(4, 0x04034b50);
  2606. o.write_shift(2, 20);
  2607. o.write_shift(2, flags);
  2608. o.write_shift(2, method);
  2609. /* TODO: last mod file time/date */
  2610. if(fi.mt) write_dos_date(o, fi.mt);
  2611. else o.write_shift(4, 0);
  2612. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  2613. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  2614. o.write_shift(4, (flags & 8) ? 0 : fi.content.length);
  2615. o.write_shift(2, namebuf.length);
  2616. o.write_shift(2, 0);
  2617. start_cd += o.length;
  2618. out.push(o);
  2619. start_cd += namebuf.length;
  2620. out.push(namebuf);
  2621. /* TODO: extra fields? */
  2622. /* TODO: encryption header ? */
  2623. start_cd += outbuf.length;
  2624. out.push(outbuf);
  2625. /* data descriptor */
  2626. if(flags & 8) {
  2627. o = new_buf(12);
  2628. o.write_shift(-4, crcs[fcnt]);
  2629. o.write_shift(4, outbuf.length);
  2630. o.write_shift(4, fi.content.length);
  2631. start_cd += o.l;
  2632. out.push(o);
  2633. }
  2634. /* central directory */
  2635. o = new_buf(46);
  2636. o.write_shift(4, 0x02014b50);
  2637. o.write_shift(2, 0);
  2638. o.write_shift(2, 20);
  2639. o.write_shift(2, flags);
  2640. o.write_shift(2, method);
  2641. o.write_shift(4, 0); /* TODO: last mod file time/date */
  2642. o.write_shift(-4, crcs[fcnt]);
  2643. o.write_shift(4, outbuf.length);
  2644. o.write_shift(4, fi.content.length);
  2645. o.write_shift(2, namebuf.length);
  2646. o.write_shift(2, 0);
  2647. o.write_shift(2, 0);
  2648. o.write_shift(2, 0);
  2649. o.write_shift(2, 0);
  2650. o.write_shift(4, 0);
  2651. o.write_shift(4, start);
  2652. sz_cd += o.l;
  2653. cdirs.push(o);
  2654. sz_cd += namebuf.length;
  2655. cdirs.push(namebuf);
  2656. ++fcnt;
  2657. }
  2658. /* end of central directory */
  2659. o = new_buf(22);
  2660. o.write_shift(4, 0x06054b50);
  2661. o.write_shift(2, 0);
  2662. o.write_shift(2, 0);
  2663. o.write_shift(2, fcnt);
  2664. o.write_shift(2, fcnt);
  2665. o.write_shift(4, sz_cd);
  2666. o.write_shift(4, start_cd);
  2667. o.write_shift(2, 0);
  2668. return bconcat(([bconcat((out)), bconcat(cdirs), o]));
  2669. }
  2670. var ContentTypeMap = ({
  2671. "htm": "text/html",
  2672. "xml": "text/xml",
  2673. "gif": "image/gif",
  2674. "jpg": "image/jpeg",
  2675. "png": "image/png",
  2676. "mso": "application/x-mso",
  2677. "thmx": "application/vnd.ms-officetheme",
  2678. "sh33tj5": "application/octet-stream"
  2679. });
  2680. function get_content_type(fi, fp) {
  2681. if(fi.ctype) return fi.ctype;
  2682. var ext = fi.name || "", m = ext.match(/\.([^\.]+)$/);
  2683. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  2684. if(fp) {
  2685. m = (ext = fp).match(/[\.\\]([^\.\\])+$/);
  2686. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  2687. }
  2688. return "application/octet-stream";
  2689. }
  2690. /* 76 character chunks TODO: intertwine encoding */
  2691. function write_base64_76(bstr) {
  2692. var data = Base64_encode(bstr);
  2693. var o = [];
  2694. for(var i = 0; i < data.length; i+= 76) o.push(data.slice(i, i+76));
  2695. return o.join("\r\n") + "\r\n";
  2696. }
  2697. /*
  2698. Rules for QP:
  2699. - escape =## applies for all non-display characters and literal "="
  2700. - space or tab at end of line must be encoded
  2701. - \r\n newlines can be preserved, but bare \r and \n must be escaped
  2702. - lines must not exceed 76 characters, use soft breaks =\r\n
  2703. TODO: Some files from word appear to write line extensions with bare equals:
  2704. ```
  2705. <table class=3DMsoTableGrid border=3D1 cellspacing=3D0 cellpadding=3D0 width=
  2706. ="70%"
  2707. ```
  2708. */
  2709. function write_quoted_printable(text) {
  2710. var encoded = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c) {
  2711. var w = c.charCodeAt(0).toString(16).toUpperCase();
  2712. return "=" + (w.length == 1 ? "0" + w : w);
  2713. });
  2714. encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
  2715. if(encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
  2716. encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
  2717. var o = [], split = encoded.split("\r\n");
  2718. for(var si = 0; si < split.length; ++si) {
  2719. var str = split[si];
  2720. if(str.length == 0) { o.push(""); continue; }
  2721. for(var i = 0; i < str.length;) {
  2722. var end = 76;
  2723. var tmp = str.slice(i, i + end);
  2724. if(tmp.charAt(end - 1) == "=") end --;
  2725. else if(tmp.charAt(end - 2) == "=") end -= 2;
  2726. else if(tmp.charAt(end - 3) == "=") end -= 3;
  2727. tmp = str.slice(i, i + end);
  2728. i += end;
  2729. if(i < str.length) tmp += "=";
  2730. o.push(tmp);
  2731. }
  2732. }
  2733. return o.join("\r\n");
  2734. }
  2735. function parse_quoted_printable(data) {
  2736. var o = [];
  2737. /* unify long lines */
  2738. for(var di = 0; di < data.length; ++di) {
  2739. var line = data[di];
  2740. while(di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
  2741. o.push(line);
  2742. }
  2743. /* decode */
  2744. for(var oi = 0; oi < o.length; ++oi) o[oi] = o[oi].replace(/[=][0-9A-Fa-f]{2}/g, function($$) { return String.fromCharCode(parseInt($$.slice(1), 16)); });
  2745. return s2a(o.join("\r\n"));
  2746. }
  2747. function parse_mime(cfb, data, root) {
  2748. var fname = "", cte = "", ctype = "", fdata;
  2749. var di = 0;
  2750. for(;di < 10; ++di) {
  2751. var line = data[di];
  2752. if(!line || line.match(/^\s*$/)) break;
  2753. var m = line.match(/^(.*?):\s*([^\s].*)$/);
  2754. if(m) switch(m[1].toLowerCase()) {
  2755. case "content-location": fname = m[2].trim(); break;
  2756. case "content-type": ctype = m[2].trim(); break;
  2757. case "content-transfer-encoding": cte = m[2].trim(); break;
  2758. }
  2759. }
  2760. ++di;
  2761. switch(cte.toLowerCase()) {
  2762. case 'base64': fdata = s2a(Base64_decode(data.slice(di).join(""))); break;
  2763. case 'quoted-printable': fdata = parse_quoted_printable(data.slice(di)); break;
  2764. default: throw new Error("Unsupported Content-Transfer-Encoding " + cte);
  2765. }
  2766. var file = cfb_add(cfb, fname.slice(root.length), fdata, {unsafe: true});
  2767. if(ctype) file.ctype = ctype;
  2768. }
  2769. function parse_mad(file, options) {
  2770. if(a2s(file.slice(0,13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
  2771. var root = (options && options.root || "");
  2772. // $FlowIgnore
  2773. var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s(file)).split("\r\n");
  2774. var di = 0, row = "";
  2775. /* if root is not specified, scan for the common prefix */
  2776. for(di = 0; di < data.length; ++di) {
  2777. row = data[di];
  2778. if(!/^Content-Location:/i.test(row)) continue;
  2779. row = row.slice(row.indexOf("file"));
  2780. if(!root) root = row.slice(0, row.lastIndexOf("/") + 1);
  2781. if(row.slice(0, root.length) == root) continue;
  2782. while(root.length > 0) {
  2783. root = root.slice(0, root.length - 1);
  2784. root = root.slice(0, root.lastIndexOf("/") + 1);
  2785. if(row.slice(0,root.length) == root) break;
  2786. }
  2787. }
  2788. var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
  2789. if(!mboundary) throw new Error("MAD cannot find boundary");
  2790. var boundary = "--" + (mboundary[1] || "");
  2791. var FileIndex = [], FullPaths = [];
  2792. var o = {
  2793. FileIndex: FileIndex,
  2794. FullPaths: FullPaths
  2795. };
  2796. init_cfb(o);
  2797. var start_di, fcnt = 0;
  2798. for(di = 0; di < data.length; ++di) {
  2799. var line = data[di];
  2800. if(line !== boundary && line !== boundary + "--") continue;
  2801. if(fcnt++) parse_mime(o, data.slice(start_di, di), root);
  2802. start_di = di;
  2803. }
  2804. return o;
  2805. }
  2806. function write_mad(cfb, options) {
  2807. var opts = options || {};
  2808. var boundary = opts.boundary || "SheetJS";
  2809. boundary = '------=' + boundary;
  2810. var out = [
  2811. 'MIME-Version: 1.0',
  2812. 'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
  2813. '',
  2814. '',
  2815. ''
  2816. ];
  2817. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  2818. for(var i = 1; i < cfb.FullPaths.length; ++i) {
  2819. fp = cfb.FullPaths[i].slice(root.length);
  2820. fi = cfb.FileIndex[i];
  2821. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  2822. /* Normalize filename */
  2823. fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c) {
  2824. return "_x" + c.charCodeAt(0).toString(16) + "_";
  2825. }).replace(/[\u0080-\uFFFF]/g, function(u) {
  2826. return "_u" + u.charCodeAt(0).toString(16) + "_";
  2827. });
  2828. /* Extract content as binary string */
  2829. var ca = fi.content;
  2830. // $FlowIgnore
  2831. var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s(ca);
  2832. /* 4/5 of first 1024 chars ascii -> quoted printable, else base64 */
  2833. var dispcnt = 0, L = Math.min(1024, cstr.length), cc = 0;
  2834. for(var csl = 0; csl <= L; ++csl) if((cc=cstr.charCodeAt(csl)) >= 0x20 && cc < 0x80) ++dispcnt;
  2835. var qp = dispcnt >= L * 4 / 5;
  2836. out.push(boundary);
  2837. out.push('Content-Location: ' + (opts.root || 'file:///C:/SheetJS/') + fp);
  2838. out.push('Content-Transfer-Encoding: ' + (qp ? 'quoted-printable' : 'base64'));
  2839. out.push('Content-Type: ' + get_content_type(fi, fp));
  2840. out.push('');
  2841. out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
  2842. }
  2843. out.push(boundary + '--\r\n');
  2844. return out.join("\r\n");
  2845. }
  2846. function cfb_new(opts) {
  2847. var o = ({});
  2848. init_cfb(o, opts);
  2849. return o;
  2850. }
  2851. function cfb_add(cfb, name, content, opts) {
  2852. var unsafe = opts && opts.unsafe;
  2853. if(!unsafe) init_cfb(cfb);
  2854. var file = !unsafe && CFB.find(cfb, name);
  2855. if(!file) {
  2856. var fpath = cfb.FullPaths[0];
  2857. if(name.slice(0, fpath.length) == fpath) fpath = name;
  2858. else {
  2859. if(fpath.slice(-1) != "/") fpath += "/";
  2860. fpath = (fpath + name).replace("//","/");
  2861. }
  2862. file = ({name: filename(name), type: 2});
  2863. cfb.FileIndex.push(file);
  2864. cfb.FullPaths.push(fpath);
  2865. if(!unsafe) CFB.utils.cfb_gc(cfb);
  2866. }
  2867. file.content = (content);
  2868. file.size = content ? content.length : 0;
  2869. if(opts) {
  2870. if(opts.CLSID) file.clsid = opts.CLSID;
  2871. if(opts.mt) file.mt = opts.mt;
  2872. if(opts.ct) file.ct = opts.ct;
  2873. }
  2874. return file;
  2875. }
  2876. function cfb_del(cfb, name) {
  2877. init_cfb(cfb);
  2878. var file = CFB.find(cfb, name);
  2879. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  2880. cfb.FileIndex.splice(j, 1);
  2881. cfb.FullPaths.splice(j, 1);
  2882. return true;
  2883. }
  2884. return false;
  2885. }
  2886. function cfb_mov(cfb, old_name, new_name) {
  2887. init_cfb(cfb);
  2888. var file = CFB.find(cfb, old_name);
  2889. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  2890. cfb.FileIndex[j].name = filename(new_name);
  2891. cfb.FullPaths[j] = new_name;
  2892. return true;
  2893. }
  2894. return false;
  2895. }
  2896. function cfb_gc(cfb) { rebuild_cfb(cfb, true); }
  2897. exports.find = find;
  2898. exports.read = read;
  2899. exports.parse = parse;
  2900. exports.write = write;
  2901. exports.writeFile = write_file;
  2902. exports.utils = {
  2903. cfb_new: cfb_new,
  2904. cfb_add: cfb_add,
  2905. cfb_del: cfb_del,
  2906. cfb_mov: cfb_mov,
  2907. cfb_gc: cfb_gc,
  2908. ReadShift: ReadShift,
  2909. CheckField: CheckField,
  2910. prep_blob: prep_blob,
  2911. bconcat: bconcat,
  2912. use_zlib: use_zlib,
  2913. _deflateRaw: _deflate,
  2914. _inflateRaw: _inflate,
  2915. consts: consts
  2916. };
  2917. return exports;
  2918. })();
  2919. var _fs;
  2920. function set_fs(fs) { _fs = fs; }
  2921. /* normalize data for blob ctor */
  2922. function blobify(data) {
  2923. if(typeof data === "string") return s2ab(data);
  2924. if(Array.isArray(data)) return a2u(data);
  2925. return data;
  2926. }
  2927. /* write or download file */
  2928. function write_dl(fname, payload, enc) {
  2929. /*global IE_SaveFile, Blob, navigator, saveAs, document, File, chrome */
  2930. if(typeof _fs !== 'undefined' && _fs.writeFileSync) return enc ? _fs.writeFileSync(fname, payload, enc) : _fs.writeFileSync(fname, payload);
  2931. if(typeof Deno !== 'undefined') {
  2932. /* in this spot, it's safe to assume typed arrays and TextEncoder/TextDecoder exist */
  2933. if(enc && typeof payload == "string") switch(enc) {
  2934. case "utf8": payload = new TextEncoder(enc).encode(payload); break;
  2935. case "binary": payload = s2ab(payload); break;
  2936. /* TODO: binary equivalent */
  2937. default: throw new Error("Unsupported encoding " + enc);
  2938. }
  2939. return Deno.writeFileSync(fname, payload);
  2940. }
  2941. var data = (enc == "utf8") ? utf8write(payload) : payload;
  2942. if(typeof IE_SaveFile !== 'undefined') return IE_SaveFile(data, fname);
  2943. if(typeof Blob !== 'undefined') {
  2944. var blob = new Blob([blobify(data)], {type:"application/octet-stream"});
  2945. if(typeof navigator !== 'undefined' && navigator.msSaveBlob) return navigator.msSaveBlob(blob, fname);
  2946. if(typeof saveAs !== 'undefined') return saveAs(blob, fname);
  2947. if(typeof URL !== 'undefined' && typeof document !== 'undefined' && document.createElement && URL.createObjectURL) {
  2948. var url = URL.createObjectURL(blob);
  2949. if(typeof chrome === 'object' && typeof (chrome.downloads||{}).download == "function") {
  2950. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  2951. return chrome.downloads.download({ url: url, filename: fname, saveAs: true});
  2952. }
  2953. var a = document.createElement("a");
  2954. if(a.download != null) {
  2955. a.download = fname; a.href = url; document.body.appendChild(a); a.click();
  2956. document.body.removeChild(a);
  2957. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  2958. return url;
  2959. }
  2960. }
  2961. }
  2962. // $FlowIgnore
  2963. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  2964. // $FlowIgnore
  2965. var out = File(fname); out.open("w"); out.encoding = "binary";
  2966. if(Array.isArray(payload)) payload = a2s(payload);
  2967. out.write(payload); out.close(); return payload;
  2968. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  2969. throw new Error("cannot save file " + fname);
  2970. }
  2971. /* read binary data from file */
  2972. function read_binary(path) {
  2973. if(typeof _fs !== 'undefined') return _fs.readFileSync(path);
  2974. if(typeof Deno !== 'undefined') return Deno.readFileSync(path);
  2975. // $FlowIgnore
  2976. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  2977. // $FlowIgnore
  2978. var infile = File(path); infile.open("r"); infile.encoding = "binary";
  2979. var data = infile.read(); infile.close();
  2980. return data;
  2981. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  2982. throw new Error("Cannot access file " + path);
  2983. }
  2984. function keys(o) {
  2985. var ks = Object.keys(o), o2 = [];
  2986. for(var i = 0; i < ks.length; ++i) if(Object.prototype.hasOwnProperty.call(o, ks[i])) o2.push(ks[i]);
  2987. return o2;
  2988. }
  2989. function evert_key(obj, key) {
  2990. var o = ([]), K = keys(obj);
  2991. for(var i = 0; i !== K.length; ++i) if(o[obj[K[i]][key]] == null) o[obj[K[i]][key]] = K[i];
  2992. return o;
  2993. }
  2994. function evert(obj) {
  2995. var o = ([]), K = keys(obj);
  2996. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
  2997. return o;
  2998. }
  2999. function evert_num(obj) {
  3000. var o = ([]), K = keys(obj);
  3001. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
  3002. return o;
  3003. }
  3004. function evert_arr(obj) {
  3005. var o = ([]), K = keys(obj);
  3006. for(var i = 0; i !== K.length; ++i) {
  3007. if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
  3008. o[obj[K[i]]].push(K[i]);
  3009. }
  3010. return o;
  3011. }
  3012. var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
  3013. function datenum(v, date1904) {
  3014. var epoch = v.getTime();
  3015. if(date1904) epoch -= 1462*24*60*60*1000;
  3016. var dnthresh = basedate.getTime() + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  3017. return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
  3018. }
  3019. var refdate = new Date();
  3020. var dnthresh = basedate.getTime() + (refdate.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  3021. var refoffset = refdate.getTimezoneOffset();
  3022. function numdate(v) {
  3023. var out = new Date();
  3024. out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  3025. if (out.getTimezoneOffset() !== refoffset) {
  3026. out.setTime(out.getTime() + (out.getTimezoneOffset() - refoffset) * 60000);
  3027. }
  3028. return out;
  3029. }
  3030. /* ISO 8601 Duration */
  3031. function parse_isodur(s) {
  3032. var sec = 0, mt = 0, time = false;
  3033. var m = s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
  3034. if(!m) throw new Error("|" + s + "| is not an ISO8601 Duration");
  3035. for(var i = 1; i != m.length; ++i) {
  3036. if(!m[i]) continue;
  3037. mt = 1;
  3038. if(i > 3) time = true;
  3039. switch(m[i].slice(m[i].length-1)) {
  3040. case 'Y':
  3041. throw new Error("Unsupported ISO Duration Field: " + m[i].slice(m[i].length-1));
  3042. case 'D': mt *= 24;
  3043. /* falls through */
  3044. case 'H': mt *= 60;
  3045. /* falls through */
  3046. case 'M':
  3047. if(!time) throw new Error("Unsupported ISO Duration Field: M");
  3048. else mt *= 60;
  3049. /* falls through */
  3050. case 'S': break;
  3051. }
  3052. sec += mt * parseInt(m[i], 10);
  3053. }
  3054. return sec;
  3055. }
  3056. var good_pd_date_1 = new Date('2017-02-19T19:06:09.000Z');
  3057. var good_pd_date = isNaN(good_pd_date_1.getFullYear()) ? new Date('2/19/17') : good_pd_date_1;
  3058. var good_pd = good_pd_date.getFullYear() == 2017;
  3059. /* parses a date as a local date */
  3060. function parseDate(str, fixdate) {
  3061. var d = new Date(str);
  3062. if(good_pd) {
  3063. if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
  3064. else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
  3065. return d;
  3066. }
  3067. if(str instanceof Date) return str;
  3068. if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
  3069. var s = d.getFullYear();
  3070. if(str.indexOf("" + s) > -1) return d;
  3071. d.setFullYear(d.getFullYear() + 100); return d;
  3072. }
  3073. var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
  3074. var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
  3075. if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
  3076. return out;
  3077. }
  3078. function cc2str(arr, debomit) {
  3079. if(has_buf && Buffer.isBuffer(arr)) {
  3080. if(debomit && buf_utf16le) {
  3081. // TODO: temporary patch
  3082. if(arr[0] == 0xFF && arr[1] == 0xFE) return utf8write(arr.slice(2).toString("utf16le"));
  3083. if(arr[1] == 0xFE && arr[2] == 0xFF) return utf8write(utf16beread(arr.slice(2).toString("binary")));
  3084. }
  3085. return arr.toString("binary");
  3086. }
  3087. if(typeof TextDecoder !== "undefined") try {
  3088. if(debomit) {
  3089. if(arr[0] == 0xFF && arr[1] == 0xFE) return utf8write(new TextDecoder("utf-16le").decode(arr.slice(2)));
  3090. if(arr[0] == 0xFE && arr[1] == 0xFF) return utf8write(new TextDecoder("utf-16be").decode(arr.slice(2)));
  3091. }
  3092. var rev = {
  3093. "\u20ac": "\x80", "\u201a": "\x82", "\u0192": "\x83", "\u201e": "\x84",
  3094. "\u2026": "\x85", "\u2020": "\x86", "\u2021": "\x87", "\u02c6": "\x88",
  3095. "\u2030": "\x89", "\u0160": "\x8a", "\u2039": "\x8b", "\u0152": "\x8c",
  3096. "\u017d": "\x8e", "\u2018": "\x91", "\u2019": "\x92", "\u201c": "\x93",
  3097. "\u201d": "\x94", "\u2022": "\x95", "\u2013": "\x96", "\u2014": "\x97",
  3098. "\u02dc": "\x98", "\u2122": "\x99", "\u0161": "\x9a", "\u203a": "\x9b",
  3099. "\u0153": "\x9c", "\u017e": "\x9e", "\u0178": "\x9f"
  3100. };
  3101. if(Array.isArray(arr)) arr = new Uint8Array(arr);
  3102. return new TextDecoder("latin1").decode(arr).replace(/[€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ]/g, function(c) { return rev[c] || c; });
  3103. } catch(e) {}
  3104. var o = [];
  3105. for(var i = 0; i != arr.length; ++i) o.push(String.fromCharCode(arr[i]));
  3106. return o.join("");
  3107. }
  3108. function dup(o) {
  3109. if(typeof JSON != 'undefined' && !Array.isArray(o)) return JSON.parse(JSON.stringify(o));
  3110. if(typeof o != 'object' || o == null) return o;
  3111. if(o instanceof Date) return new Date(o.getTime());
  3112. var out = {};
  3113. for(var k in o) if(Object.prototype.hasOwnProperty.call(o, k)) out[k] = dup(o[k]);
  3114. return out;
  3115. }
  3116. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  3117. /* TODO: stress test */
  3118. function fuzzynum(s) {
  3119. var v = Number(s);
  3120. if(!isNaN(v)) return isFinite(v) ? v : NaN;
  3121. if(!/\d/.test(s)) return v;
  3122. var wt = 1;
  3123. var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
  3124. if(!isNaN(v = Number(ss))) return v / wt;
  3125. ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
  3126. if(!isNaN(v = Number(ss))) return v / wt;
  3127. return v;
  3128. }
  3129. /* NOTE: Chrome rejects bare times like 1:23 PM */
  3130. var FDRE1 = /^(0?\d|1[0-2])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))\s+([ap])m?$/;
  3131. function fuzzytime1(M) {
  3132. /* TODO: 1904 adjustment, keep in sync with base date */
  3133. if(!M[2]) return new Date(1899,11,30,(+M[1]%12) + (M[7] == "p" ? 12 : 0), 0, 0, 0);
  3134. if(M[3]) {
  3135. if(M[4]) return new Date(1899,11,30,(+M[1]%12) + (M[7] == "p" ? 12 : 0), +M[2], +M[4], parseFloat(M[3])*1000);
  3136. else return new Date(1899,11,30,(M[7] == "p" ? 12 : 0), +M[1], +M[2], parseFloat(M[3])*1000);
  3137. }
  3138. else if(M[5]) return new Date(1899,11,30, (+M[1]%12) + (M[7] == "p" ? 12 : 0), +M[2], +M[5], M[6] ? parseFloat(M[6]) * 1000 : 0);
  3139. else return new Date(1899,11,30,(+M[1]%12) + (M[7] == "p" ? 12 : 0), +M[2], 0, 0);
  3140. }
  3141. var lower_months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
  3142. function fuzzydate(s) {
  3143. var lower = s.toLowerCase();
  3144. var lnos = lower.replace(/\s+/g, " ").trim();
  3145. var M = lnos.match(FDRE1);
  3146. if(M) return fuzzytime1(M);
  3147. var o = new Date(s), n = new Date(NaN);
  3148. var y = o.getYear(), m = o.getMonth(), d = o.getDate();
  3149. if(isNaN(d)) return n;
  3150. if(lower.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) {
  3151. lower = lower.replace(/[^a-z]/g,"").replace(/([^a-z]|^)[ap]m?([^a-z]|$)/,"");
  3152. if(lower.length > 3 && lower_months.indexOf(lower) == -1) return n;
  3153. } else if(lower.replace(/[ap]m?/, "").match(/[a-z]/)) return n;
  3154. if(y < 0 || y > 8099 || s.match(/[^-0-9:,\/\\]/)) return n;
  3155. return o;
  3156. }
  3157. var split_regex = (function() {
  3158. var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  3159. return function split_regex(str, re, def) {
  3160. if(safe_split_regex || typeof re == "string") return str.split(re);
  3161. var p = str.split(re), o = [p[0]];
  3162. for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
  3163. return o;
  3164. };
  3165. })();
  3166. function getdatastr(data) {
  3167. if(!data) return null;
  3168. if(data.content && data.type) return cc2str(data.content, true);
  3169. if(data.data) return debom(data.data);
  3170. if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
  3171. if(data.asBinary) return debom(data.asBinary());
  3172. if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
  3173. return null;
  3174. }
  3175. function getdatabin(data) {
  3176. if(!data) return null;
  3177. if(data.data) return char_codes(data.data);
  3178. if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  3179. if(data._data && data._data.getContent) {
  3180. var o = data._data.getContent();
  3181. if(typeof o == "string") return char_codes(o);
  3182. return Array.prototype.slice.call(o);
  3183. }
  3184. if(data.content && data.type) return data.content;
  3185. return null;
  3186. }
  3187. function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }
  3188. /* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
  3189. /* OASIS does not comment on filename case sensitivity */
  3190. function safegetzipfile(zip, file) {
  3191. var k = zip.FullPaths || keys(zip.files);
  3192. var f = file.toLowerCase().replace(/[\/]/g, '\\'), g = f.replace(/\\/g,'\/');
  3193. for(var i=0; i<k.length; ++i) {
  3194. var n = k[i].replace(/^Root Entry[\/]/,"").toLowerCase();
  3195. if(f == n || g == n) return zip.files ? zip.files[k[i]] : zip.FileIndex[i];
  3196. }
  3197. return null;
  3198. }
  3199. function getzipfile(zip, file) {
  3200. var o = safegetzipfile(zip, file);
  3201. if(o == null) throw new Error("Cannot find file " + file + " in zip");
  3202. return o;
  3203. }
  3204. function getzipdata(zip, file, safe) {
  3205. if(!safe) return getdata(getzipfile(zip, file));
  3206. if(!file) return null;
  3207. try { return getzipdata(zip, file); } catch(e) { return null; }
  3208. }
  3209. function getzipstr(zip, file, safe) {
  3210. if(!safe) return getdatastr(getzipfile(zip, file));
  3211. if(!file) return null;
  3212. try { return getzipstr(zip, file); } catch(e) { return null; }
  3213. }
  3214. function getzipbin(zip, file, safe) {
  3215. if(!safe) return getdatabin(getzipfile(zip, file));
  3216. if(!file) return null;
  3217. try { return getzipbin(zip, file); } catch(e) { return null; }
  3218. }
  3219. function zipentries(zip) {
  3220. var k = zip.FullPaths || keys(zip.files), o = [];
  3221. for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i].replace(/^Root Entry[\/]/, ""));
  3222. return o.sort();
  3223. }
  3224. function zip_add_file(zip, path, content) {
  3225. if(zip.FullPaths) {
  3226. if(typeof content == "string") {
  3227. var res;
  3228. if(has_buf) res = Buffer_from(content);
  3229. /* TODO: investigate performance in Edge 13 */
  3230. //else if(typeof TextEncoder !== "undefined") res = new TextEncoder().encode(content);
  3231. else res = utf8decode(content);
  3232. return CFB.utils.cfb_add(zip, path, res);
  3233. }
  3234. CFB.utils.cfb_add(zip, path, content);
  3235. }
  3236. else zip.file(path, content);
  3237. }
  3238. function zip_new() { return CFB.utils.cfb_new(); }
  3239. function zip_read(d, o) {
  3240. switch(o.type) {
  3241. case "base64": return CFB.read(d, { type: "base64" });
  3242. case "binary": return CFB.read(d, { type: "binary" });
  3243. case "buffer": case "array": return CFB.read(d, { type: "buffer" });
  3244. }
  3245. throw new Error("Unrecognized type " + o.type);
  3246. }
  3247. function resolve_path(path, base) {
  3248. if(path.charAt(0) == "/") return path.slice(1);
  3249. var result = base.split('/');
  3250. if(base.slice(-1) != "/") result.pop(); // folder path
  3251. var target = path.split('/');
  3252. while (target.length !== 0) {
  3253. var step = target.shift();
  3254. if (step === '..') result.pop();
  3255. else if (step !== '.') result.push(step);
  3256. }
  3257. return result.join('/');
  3258. }
  3259. var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
  3260. var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
  3261. var tagregex1=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s*[\/\?]?>/mg, tagregex2 = /<[^>]*>/g;
  3262. var tagregex = XML_HEADER.match(tagregex1) ? tagregex1 : tagregex2;
  3263. var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
  3264. function parsexmltag(tag, skip_root, skip_LC) {
  3265. var z = ({});
  3266. var eq = 0, c = 0;
  3267. for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
  3268. if(!skip_root) z[0] = tag.slice(0, eq);
  3269. if(eq === tag.length) return z;
  3270. var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
  3271. if(m) for(i = 0; i != m.length; ++i) {
  3272. cc = m[i];
  3273. for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
  3274. q = cc.slice(0,c).trim();
  3275. while(cc.charCodeAt(c+1) == 32) ++c;
  3276. quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
  3277. v = cc.slice(c+1+quot, cc.length-quot);
  3278. for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
  3279. if(j===q.length) {
  3280. if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
  3281. z[q] = v;
  3282. if(!skip_LC) z[q.toLowerCase()] = v;
  3283. }
  3284. else {
  3285. var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
  3286. if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
  3287. z[k] = v;
  3288. if(!skip_LC) z[k.toLowerCase()] = v;
  3289. }
  3290. }
  3291. return z;
  3292. }
  3293. function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
  3294. var encodings = {
  3295. '&quot;': '"',
  3296. '&apos;': "'",
  3297. '&gt;': '>',
  3298. '&lt;': '<',
  3299. '&amp;': '&'
  3300. };
  3301. var rencoding = evert(encodings);
  3302. //var rencstr = "&<>'\"".split("");
  3303. // TODO: CP remap (need to read file version to determine OS)
  3304. var unescapexml = (function() {
  3305. /* 22.4.2.4 bstr (Basic String) */
  3306. var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  3307. function raw_unescapexml(text) {
  3308. var s = text + '', i = s.indexOf("<![CDATA[");
  3309. 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));});
  3310. var j = s.indexOf("]]>");
  3311. return raw_unescapexml(s.slice(0, i)) + s.slice(i+9,j) + raw_unescapexml(s.slice(j+3));
  3312. }
  3313. return function unescapexml(text, xlsx) {
  3314. var out = raw_unescapexml(text);
  3315. return xlsx ? out.replace(/\r\n/g, "\n") : out;
  3316. };
  3317. })();
  3318. var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f\uFFFE-\uFFFF]/g;
  3319. function escapexml(text){
  3320. var s = text + '';
  3321. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
  3322. }
  3323. function escapexmltag(text){ return escapexml(text).replace(/ /g,"_x0020_"); }
  3324. var htmlcharegex = /[\u0000-\u001f]/g;
  3325. function escapehtml(text){
  3326. var s = text + '';
  3327. 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) + ";"; });
  3328. }
  3329. function escapexlml(text){
  3330. var s = text + '';
  3331. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
  3332. }
  3333. /* TODO: handle codepages */
  3334. var xlml_fixstr = (function() {
  3335. var entregex = /&#(\d+);/g;
  3336. function entrepl($$,$1) { return String.fromCharCode(parseInt($1,10)); }
  3337. return function xlml_fixstr(str) { return str.replace(entregex,entrepl); };
  3338. })();
  3339. function xlml_unfixstr(str) { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); }
  3340. /* note: xsd:boolean valid values: true / 1 / false / 0 */
  3341. function parsexmlbool(value) {
  3342. switch(value) {
  3343. case 1: case true: case '1': case 'true': return true;
  3344. case 0: case false: case '0': case 'false': return false;
  3345. //default: throw new Error("Invalid xsd:boolean " + value);
  3346. }
  3347. return false;
  3348. }
  3349. function utf8reada(orig) {
  3350. var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
  3351. while (i < orig.length) {
  3352. c = orig.charCodeAt(i++);
  3353. if (c < 128) { out += String.fromCharCode(c); continue; }
  3354. d = orig.charCodeAt(i++);
  3355. if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
  3356. e = orig.charCodeAt(i++);
  3357. if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
  3358. f = orig.charCodeAt(i++);
  3359. w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
  3360. out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
  3361. out += String.fromCharCode(0xDC00 + (w&1023));
  3362. }
  3363. return out;
  3364. }
  3365. function utf8readb(data) {
  3366. var out = new_raw_buf(2*data.length), w, i, j = 1, k = 0, ww=0, c;
  3367. for(i = 0; i < data.length; i+=j) {
  3368. j = 1;
  3369. if((c=data.charCodeAt(i)) < 128) w = c;
  3370. else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
  3371. else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
  3372. else { j = 4;
  3373. w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
  3374. w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
  3375. }
  3376. if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
  3377. out[k++] = w%256; out[k++] = w>>>8;
  3378. }
  3379. return out.slice(0,k).toString('ucs2');
  3380. }
  3381. function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); }
  3382. var utf8corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
  3383. var utf8read = has_buf && (utf8readc(utf8corpus) == utf8reada(utf8corpus) && utf8readc || utf8readb(utf8corpus) == utf8reada(utf8corpus) && utf8readb) || utf8reada;
  3384. var utf8write = has_buf ? function(data) { return Buffer_from(data, 'utf8').toString("binary"); } : function(orig) {
  3385. var out = [], i = 0, c = 0, d = 0;
  3386. while(i < orig.length) {
  3387. c = orig.charCodeAt(i++);
  3388. switch(true) {
  3389. case c < 128: out.push(String.fromCharCode(c)); break;
  3390. case c < 2048:
  3391. out.push(String.fromCharCode(192 + (c >> 6)));
  3392. out.push(String.fromCharCode(128 + (c & 63)));
  3393. break;
  3394. case c >= 55296 && c < 57344:
  3395. c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
  3396. out.push(String.fromCharCode(240 + ((d >>18) & 7)));
  3397. out.push(String.fromCharCode(144 + ((d >>12) & 63)));
  3398. out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
  3399. out.push(String.fromCharCode(128 + (d & 63)));
  3400. break;
  3401. default:
  3402. out.push(String.fromCharCode(224 + (c >> 12)));
  3403. out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
  3404. out.push(String.fromCharCode(128 + (c & 63)));
  3405. }
  3406. }
  3407. return out.join("");
  3408. };
  3409. // matches <foo>...</foo> extracts content
  3410. var matchtag = (function() {
  3411. var mtcache = ({});
  3412. return function matchtag(f,g) {
  3413. var t = f+"|"+(g||"");
  3414. if(mtcache[t]) return mtcache[t];
  3415. return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||""))));
  3416. };
  3417. })();
  3418. var htmldecode = (function() {
  3419. var entities = [
  3420. ['nbsp', ' '], ['middot', '·'],
  3421. ['quot', '"'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['amp', '&']
  3422. ].map(function(x) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
  3423. return function htmldecode(str) {
  3424. var o = str
  3425. // Remove new lines and spaces from start of content
  3426. .replace(/^[\t\n\r ]+/, "")
  3427. // Remove new lines and spaces from end of content
  3428. .replace(/[\t\n\r ]+$/,"")
  3429. // Added line which removes any white space characters after and before html tags
  3430. .replace(/>\s+/g,">").replace(/\s+</g,"<")
  3431. // Replace remaining new lines and spaces with space
  3432. .replace(/[\t\n\r ]+/g, " ")
  3433. // Replace <br> tags with new lines
  3434. .replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
  3435. // Strip HTML elements
  3436. .replace(/<[^>]*>/g,"");
  3437. for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
  3438. return o;
  3439. };
  3440. })();
  3441. var vtregex = (function(){ var vt_cache = {};
  3442. return function vt_regex(bt) {
  3443. if(vt_cache[bt] !== undefined) return vt_cache[bt];
  3444. return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
  3445. };})();
  3446. var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
  3447. function parseVector(data, opts) {
  3448. var h = parsexmltag(data);
  3449. var matches = data.match(vtregex(h.baseType))||[];
  3450. var res = [];
  3451. if(matches.length != h.size) {
  3452. if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
  3453. return res;
  3454. }
  3455. matches.forEach(function(x) {
  3456. var v = x.replace(vtvregex,"").match(vtmregex);
  3457. if(v) res.push({v:utf8read(v[2]), t:v[1]});
  3458. });
  3459. return res;
  3460. }
  3461. var wtregex = /(^\s|\s$|\n)/;
  3462. function writetag(f,g) { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }
  3463. function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
  3464. function writextag(f,g,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
  3465. function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
  3466. function write_vt(s, xlsx) {
  3467. switch(typeof s) {
  3468. case 'string':
  3469. var o = writextag('vt:lpwstr', escapexml(s));
  3470. if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
  3471. return o;
  3472. case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
  3473. case 'boolean': return writextag('vt:bool',s?'true':'false');
  3474. }
  3475. if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
  3476. throw new Error("Unable to serialize " + s);
  3477. }
  3478. function xlml_normalize(d) {
  3479. if(has_buf && Buffer.isBuffer(d)) return d.toString('utf8');
  3480. if(typeof d === 'string') return d;
  3481. /* duktape */
  3482. if(typeof Uint8Array !== 'undefined' && d instanceof Uint8Array) return utf8read(a2s(ab2a(d)));
  3483. throw new Error("Bad input format: expected Buffer or string");
  3484. }
  3485. /* UOS uses CJK in tags */
  3486. var xlmlregex = /<(\/?)([^\s?><!\/:]*:|)([^\s?<>:\/]+)(?:[\s?:\/](?:[^>=]|="[^"]*?")*)?>/mg;
  3487. //var xlmlregex = /<(\/?)([a-z0-9]*:|)(\w+)[^>]*>/mg;
  3488. var XMLNS = ({
  3489. CORE_PROPS: 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
  3490. CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
  3491. EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
  3492. CT: 'http://schemas.openxmlformats.org/package/2006/content-types',
  3493. RELS: 'http://schemas.openxmlformats.org/package/2006/relationships',
  3494. TCMNT: 'http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments',
  3495. 'dc': 'http://purl.org/dc/elements/1.1/',
  3496. 'dcterms': 'http://purl.org/dc/terms/',
  3497. 'dcmitype': 'http://purl.org/dc/dcmitype/',
  3498. 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
  3499. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  3500. 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
  3501. 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
  3502. 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
  3503. 'xsd': 'http://www.w3.org/2001/XMLSchema'
  3504. });
  3505. var XMLNS_main = [
  3506. 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  3507. 'http://purl.oclc.org/ooxml/spreadsheetml/main',
  3508. 'http://schemas.microsoft.com/office/excel/2006/main',
  3509. 'http://schemas.microsoft.com/office/excel/2006/2'
  3510. ];
  3511. var XLMLNS = ({
  3512. 'o': 'urn:schemas-microsoft-com:office:office',
  3513. 'x': 'urn:schemas-microsoft-com:office:excel',
  3514. 'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
  3515. 'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
  3516. 'mv': 'http://macVmlSchemaUri',
  3517. 'v': 'urn:schemas-microsoft-com:vml',
  3518. 'html': 'http://www.w3.org/TR/REC-html40'
  3519. });
  3520. function read_double_le(b, idx) {
  3521. var s = 1 - 2 * (b[idx + 7] >>> 7);
  3522. var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
  3523. var m = (b[idx+6]&0x0f);
  3524. for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
  3525. if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
  3526. if(e == 0) e = -1022;
  3527. else { e -= 1023; m += Math.pow(2,52); }
  3528. return s * Math.pow(2, e - 52) * m;
  3529. }
  3530. function write_double_le(b, v, idx) {
  3531. var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
  3532. var av = bs ? (-v) : v;
  3533. if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
  3534. else if(av == 0) e = m = 0;
  3535. else {
  3536. e = Math.floor(Math.log(av) / Math.LN2);
  3537. m = av * Math.pow(2, 52 - e);
  3538. if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
  3539. else { m -= Math.pow(2,52); e+=1023; }
  3540. }
  3541. for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
  3542. b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
  3543. b[idx + 7] = (e >> 4) | bs;
  3544. }
  3545. 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; };
  3546. var __toBuffer = has_buf ? function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0].map(function(x) { return Buffer.isBuffer(x) ? x : Buffer_from(x); })) : ___toBuffer(bufs);} : ___toBuffer;
  3547. 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,''); };
  3548. var __utf16le = has_buf ? function(b,s,e) { if(!Buffer.isBuffer(b) || !buf_utf16le) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; } : ___utf16le;
  3549. 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(""); };
  3550. var __hexlify = has_buf ? function(b,s,l) { return Buffer.isBuffer(b) ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); } : ___hexlify;
  3551. 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(""); };
  3552. var __utf8 = has_buf ? function utf8_b(b, s, e) { return (Buffer.isBuffer(b)) ? b.toString('utf8',s,e) : ___utf8(b,s,e); } : ___utf8;
  3553. var ___lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3554. var __lpstr = ___lpstr;
  3555. var ___cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3556. var __cpstr = ___cpstr;
  3557. var ___lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3558. var __lpwstr = ___lpwstr;
  3559. var ___lpp4 = function lpp4_(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
  3560. var __lpp4 = ___lpp4;
  3561. var ___8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
  3562. var __8lpp4 = ___8lpp4;
  3563. var ___double = function(b, idx) { return read_double_le(b, idx);};
  3564. var __double = ___double;
  3565. var is_buf = function is_buf_a(a) { return Array.isArray(a) || (typeof Uint8Array !== "undefined" && a instanceof Uint8Array); };
  3566. if(has_buf) {
  3567. __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) : "";};
  3568. __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) : "";};
  3569. __lpwstr = function lpwstr_b(b, i) { if(!Buffer.isBuffer(b) || !buf_utf16le) return ___lpwstr(b, i); var len = 2*b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len-1);};
  3570. __lpp4 = function lpp4_b(b, i) { if(!Buffer.isBuffer(b) || !buf_utf16le) return ___lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len);};
  3571. __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);};
  3572. __double = function double_(b, i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
  3573. is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a) || (typeof Uint8Array !== "undefined" && a instanceof Uint8Array); };
  3574. }
  3575. /* from js-xls */
  3576. function cpdoit() {
  3577. __utf16le = function(b,s,e) { return $cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
  3578. __utf8 = function(b,s,e) { return $cptable.utils.decode(65001, b.slice(s,e)); };
  3579. __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)) : "";};
  3580. __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)) : "";};
  3581. __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)) : "";};
  3582. __lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
  3583. __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
  3584. }
  3585. if(typeof $cptable !== 'undefined') cpdoit();
  3586. var __readUInt8 = function(b, idx) { return b[idx]; };
  3587. var __readUInt16LE = function(b, idx) { return (b[idx+1]*(1<<8))+b[idx]; };
  3588. var __readInt16LE = function(b, idx) { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
  3589. var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
  3590. var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
  3591. var __readInt32BE = function(b, idx) { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };
  3592. function ReadShift(size, t) {
  3593. var o="", oI, oR, oo=[], w, vv, i, loc;
  3594. switch(t) {
  3595. case 'dbcs':
  3596. loc = this.l;
  3597. if(has_buf && Buffer.isBuffer(this) && buf_utf16le) o = this.slice(this.l, this.l+2*size).toString("utf16le");
  3598. else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
  3599. size *= 2;
  3600. break;
  3601. case 'utf8': o = __utf8(this, this.l, this.l + size); break;
  3602. case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;
  3603. case 'wstr':
  3604. if(typeof $cptable !== 'undefined') o = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
  3605. else return ReadShift.call(this, size, 'dbcs');
  3606. size = 2 * size; break;
  3607. /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
  3608. case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3609. case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3610. /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
  3611. case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
  3612. /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
  3613. case 'lpp4': size = 4 + __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
  3614. /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
  3615. case '8lpp4': size = 4 + __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;
  3616. case 'cstr': size = 0; o = "";
  3617. while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
  3618. o = oo.join(""); break;
  3619. case '_wstr': size = 0; o = "";
  3620. while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
  3621. size+=2; o = oo.join(""); break;
  3622. /* sbcs and dbcs support continue records in the SST way TODO codepages */
  3623. case 'dbcs-cont': o = ""; loc = this.l;
  3624. for(i = 0; i < size; ++i) {
  3625. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3626. w = __readUInt8(this, loc);
  3627. this.l = loc + 1;
  3628. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3629. return oo.join("") + vv;
  3630. }
  3631. oo.push(_getchar(__readUInt16LE(this, loc)));
  3632. loc+=2;
  3633. } o = oo.join(""); size *= 2; break;
  3634. case 'cpstr':
  3635. if(typeof $cptable !== 'undefined') {
  3636. o = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
  3637. break;
  3638. }
  3639. /* falls through */
  3640. case 'sbcs-cont': o = ""; loc = this.l;
  3641. for(i = 0; i != size; ++i) {
  3642. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3643. w = __readUInt8(this, loc);
  3644. this.l = loc + 1;
  3645. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3646. return oo.join("") + vv;
  3647. }
  3648. oo.push(_getchar(__readUInt8(this, loc)));
  3649. loc+=1;
  3650. } o = oo.join(""); break;
  3651. default:
  3652. switch(size) {
  3653. case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
  3654. case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
  3655. case 4: case -4:
  3656. if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
  3657. else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
  3658. case 8: case -8:
  3659. if(t === 'f') {
  3660. if(size == 8) oR = __double(this, this.l);
  3661. 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);
  3662. this.l += 8; return oR;
  3663. } else size = 8;
  3664. /* falls through */
  3665. case 16: o = __hexlify(this, this.l, size); break;
  3666. }}
  3667. this.l+=size; return o;
  3668. }
  3669. 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); };
  3670. 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); };
  3671. var __writeUInt16LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };
  3672. function WriteShift(t, val, f) {
  3673. var size = 0, i = 0;
  3674. if(f === 'dbcs') {
  3675. for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
  3676. size = 2 * val.length;
  3677. } else if(f === 'sbcs' || f == 'cpstr') {
  3678. if(typeof $cptable !== 'undefined' && current_ansi == 874) {
  3679. /* TODO: use tables directly, don't encode */
  3680. for(i = 0; i != val.length; ++i) {
  3681. var cpp = $cptable.utils.encode(current_ansi, val.charAt(i));
  3682. this[this.l + i] = cpp[0];
  3683. }
  3684. size = val.length;
  3685. } else if(typeof $cptable !== 'undefined' && f == 'cpstr') {
  3686. cpp = $cptable.utils.encode(current_codepage, val);
  3687. /* replace null bytes with _ when relevant */
  3688. if(cpp.length == val.length) for(i = 0; i < val.length; ++i) if(cpp[i] == 0 && val.charCodeAt(i) != 0) cpp[i] = 0x5F;
  3689. if(cpp.length == 2 * val.length) for(i = 0; i < val.length; ++i) if(cpp[2*i] == 0 && cpp[2*i+1] == 0 && val.charCodeAt(i) != 0) cpp[2*i] = 0x5F;
  3690. for(i = 0; i < cpp.length; ++i) this[this.l + i] = cpp[i];
  3691. size = cpp.length;
  3692. } else {
  3693. val = val.replace(/[^\x00-\x7F]/g, "_");
  3694. for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
  3695. size = val.length;
  3696. }
  3697. } else if(f === 'hex') {
  3698. for(; i < t; ++i) {
  3699. this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
  3700. } return this;
  3701. } else if(f === 'utf16le') {
  3702. var end = Math.min(this.l + t, this.length);
  3703. for(i = 0; i < Math.min(val.length, t); ++i) {
  3704. var cc = val.charCodeAt(i);
  3705. this[this.l++] = (cc & 0xff);
  3706. this[this.l++] = (cc >> 8);
  3707. }
  3708. while(this.l < end) this[this.l++] = 0;
  3709. return this;
  3710. } else switch(t) {
  3711. case 1: size = 1; this[this.l] = val&0xFF; break;
  3712. case 2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
  3713. 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;
  3714. case 4: size = 4; __writeUInt32LE(this, val, this.l); break;
  3715. case 8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
  3716. /* falls through */
  3717. case 16: break;
  3718. case -4: size = 4; __writeInt32LE(this, val, this.l); break;
  3719. }
  3720. this.l += size; return this;
  3721. }
  3722. function CheckField(hexstr, fld) {
  3723. var m = __hexlify(this,this.l,hexstr.length>>1);
  3724. if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
  3725. this.l += hexstr.length>>1;
  3726. }
  3727. function prep_blob(blob, pos) {
  3728. blob.l = pos;
  3729. blob.read_shift = ReadShift;
  3730. blob.chk = CheckField;
  3731. blob.write_shift = WriteShift;
  3732. }
  3733. function parsenoop(blob, length) { blob.l += length; }
  3734. function new_buf(sz) {
  3735. var o = new_raw_buf(sz);
  3736. prep_blob(o, 0);
  3737. return o;
  3738. }
  3739. /* [MS-XLSB] 2.1.4 Record */
  3740. function recordhopper(data, cb, opts) {
  3741. if(!data) return;
  3742. var tmpbyte, cntbyte, length;
  3743. prep_blob(data, data.l || 0);
  3744. var L = data.length, RT = 0, tgt = 0;
  3745. while(data.l < L) {
  3746. RT = data.read_shift(1);
  3747. if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
  3748. var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
  3749. tmpbyte = data.read_shift(1);
  3750. length = tmpbyte & 0x7F;
  3751. for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
  3752. tgt = data.l + length;
  3753. var d = R.f && R.f(data, length, opts);
  3754. data.l = tgt;
  3755. if(cb(d, R, RT)) return;
  3756. }
  3757. }
  3758. /* control buffer usage for fixed-length buffers */
  3759. function buf_array() {
  3760. var bufs = [], blksz = has_buf ? 256 : 2048;
  3761. var newblk = function ba_newblk(sz) {
  3762. var o = (new_buf(sz));
  3763. prep_blob(o, 0);
  3764. return o;
  3765. };
  3766. var curbuf = newblk(blksz);
  3767. var endbuf = function ba_endbuf() {
  3768. if(!curbuf) return;
  3769. // workaround for new Buffer(3).slice(0,0) bug in bun 0.1.3
  3770. if(curbuf.l) {
  3771. if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
  3772. if(curbuf.length > 0) bufs.push(curbuf);
  3773. }
  3774. curbuf = null;
  3775. };
  3776. var next = function ba_next(sz) {
  3777. if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
  3778. endbuf();
  3779. return (curbuf = newblk(Math.max(sz+1, blksz)));
  3780. };
  3781. var end = function ba_end() {
  3782. endbuf();
  3783. return bconcat(bufs);
  3784. };
  3785. var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };
  3786. return ({ next:next, push:push, end:end, _bufs:bufs });
  3787. }
  3788. function write_record(ba, type, payload, length) {
  3789. var t = +type, l;
  3790. if(isNaN(t)) return; // TODO: throw something here?
  3791. if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
  3792. l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
  3793. if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
  3794. var o = ba.next(l);
  3795. if(t <= 0x7F) o.write_shift(1, t);
  3796. else {
  3797. o.write_shift(1, (t & 0x7F) + 0x80);
  3798. o.write_shift(1, (t >> 7));
  3799. }
  3800. for(var i = 0; i != 4; ++i) {
  3801. if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
  3802. else { o.write_shift(1, length); break; }
  3803. }
  3804. if(length > 0 && is_buf(payload)) ba.push(payload);
  3805. }
  3806. /* XLS ranges enforced */
  3807. function shift_cell_xls(cell, tgt, opts) {
  3808. var out = dup(cell);
  3809. if(tgt.s) {
  3810. if(out.cRel) out.c += tgt.s.c;
  3811. if(out.rRel) out.r += tgt.s.r;
  3812. } else {
  3813. if(out.cRel) out.c += tgt.c;
  3814. if(out.rRel) out.r += tgt.r;
  3815. }
  3816. if(!opts || opts.biff < 12) {
  3817. while(out.c >= 0x100) out.c -= 0x100;
  3818. while(out.r >= 0x10000) out.r -= 0x10000;
  3819. }
  3820. return out;
  3821. }
  3822. function shift_range_xls(cell, range, opts) {
  3823. var out = dup(cell);
  3824. out.s = shift_cell_xls(out.s, range.s, opts);
  3825. out.e = shift_cell_xls(out.e, range.s, opts);
  3826. return out;
  3827. }
  3828. function encode_cell_xls(c, biff) {
  3829. if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
  3830. if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
  3831. var s = encode_cell(c);
  3832. if(!c.cRel && c.cRel != null) s = fix_col(s);
  3833. if(!c.rRel && c.rRel != null) s = fix_row(s);
  3834. return s;
  3835. }
  3836. function encode_range_xls(r, opts) {
  3837. if(r.s.r == 0 && !r.s.rRel) {
  3838. if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
  3839. return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
  3840. }
  3841. }
  3842. if(r.s.c == 0 && !r.s.cRel) {
  3843. if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
  3844. return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
  3845. }
  3846. }
  3847. return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
  3848. }
  3849. if(typeof cptable !== 'undefined') set_cptable(cptable);
  3850. else if(typeof module !== "undefined" && typeof require !== 'undefined') {
  3851. set_cptable(require('./dist/cpexcel.js'));
  3852. }
  3853. function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
  3854. function encode_row(row) { return "" + (row + 1); }
  3855. function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
  3856. function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
  3857. 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; }
  3858. 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; }
  3859. function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
  3860. function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
  3861. function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
  3862. //function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
  3863. function decode_cell(cstr) {
  3864. var R = 0, C = 0;
  3865. for(var i = 0; i < cstr.length; ++i) {
  3866. var cc = cstr.charCodeAt(i);
  3867. if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
  3868. else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
  3869. }
  3870. return { c: C - 1, r:R - 1 };
  3871. }
  3872. //function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
  3873. function encode_cell(cell) {
  3874. var col = cell.c + 1;
  3875. var s="";
  3876. for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
  3877. return s + (cell.r + 1);
  3878. }
  3879. function decode_range(range) {
  3880. var idx = range.indexOf(":");
  3881. if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
  3882. return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
  3883. }
  3884. function encode_range(cs,ce) {
  3885. if(typeof ce === 'undefined' || typeof ce === 'number') {
  3886. return encode_range(cs.s, cs.e);
  3887. }
  3888. if(typeof cs !== 'string') cs = encode_cell((cs));
  3889. if(typeof ce !== 'string') ce = encode_cell((ce));
  3890. return cs == ce ? cs : cs + ":" + ce;
  3891. }
  3892. function fix_range(a1) {
  3893. var s = decode_range(a1);
  3894. return "$" + encode_col(s.s.c) + "$" + encode_row(s.s.r) + ":$" + encode_col(s.e.c) + "$" + encode_row(s.e.r);
  3895. }
  3896. // List of invalid characters needs to be tested further
  3897. function formula_quote_sheet_name(sname, opts) {
  3898. if(!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
  3899. if (/[^\w\u4E00-\u9FFF\u3040-\u30FF]/.test(sname)) return "'" + sname.replace(/'/g, "''") + "'";
  3900. return sname;
  3901. }
  3902. function safe_decode_range(range) {
  3903. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  3904. var idx = 0, i = 0, cc = 0;
  3905. var len = range.length;
  3906. for(idx = 0; i < len; ++i) {
  3907. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3908. idx = 26*idx + cc;
  3909. }
  3910. o.s.c = --idx;
  3911. for(idx = 0; i < len; ++i) {
  3912. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3913. idx = 10*idx + cc;
  3914. }
  3915. o.s.r = --idx;
  3916. if(i === len || cc != 10) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
  3917. ++i;
  3918. for(idx = 0; i != len; ++i) {
  3919. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3920. idx = 26*idx + cc;
  3921. }
  3922. o.e.c = --idx;
  3923. for(idx = 0; i != len; ++i) {
  3924. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3925. idx = 10*idx + cc;
  3926. }
  3927. o.e.r = --idx;
  3928. return o;
  3929. }
  3930. function safe_format_cell(cell, v) {
  3931. var q = (cell.t == 'd' && v instanceof Date);
  3932. if(cell.z != null) try { return (cell.w = SSF_format(cell.z, q ? datenum(v) : v)); } catch(e) { }
  3933. try { return (cell.w = SSF_format((cell.XF||{}).numFmtId||(q ? 14 : 0), q ? datenum(v) : v)); } catch(e) { return ''+v; }
  3934. }
  3935. function format_cell(cell, v, o) {
  3936. if(cell == null || cell.t == null || cell.t == 'z') return "";
  3937. if(cell.w !== undefined) return cell.w;
  3938. if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
  3939. if(cell.t == "e") return BErr[cell.v] || cell.v;
  3940. if(v == undefined) return safe_format_cell(cell, cell.v);
  3941. return safe_format_cell(cell, v);
  3942. }
  3943. function sheet_to_workbook(sheet, opts) {
  3944. var n = opts && opts.sheet ? opts.sheet : "Sheet1";
  3945. var sheets = {}; sheets[n] = sheet;
  3946. return { SheetNames: [n], Sheets: sheets };
  3947. }
  3948. function sheet_add_aoa(_ws, data, opts) {
  3949. var o = opts || {};
  3950. var dense = _ws ? Array.isArray(_ws) : o.dense;
  3951. if(DENSE != null && dense == null) dense = DENSE;
  3952. var ws = _ws || (dense ? ([]) : ({}));
  3953. var _R = 0, _C = 0;
  3954. if(ws && o.origin != null) {
  3955. if(typeof o.origin == 'number') _R = o.origin;
  3956. else {
  3957. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  3958. _R = _origin.r; _C = _origin.c;
  3959. }
  3960. if(!ws["!ref"]) ws["!ref"] = "A1:A1";
  3961. }
  3962. var range = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}});
  3963. if(ws['!ref']) {
  3964. var _range = safe_decode_range(ws['!ref']);
  3965. range.s.c = _range.s.c;
  3966. range.s.r = _range.s.r;
  3967. range.e.c = Math.max(range.e.c, _range.e.c);
  3968. range.e.r = Math.max(range.e.r, _range.e.r);
  3969. if(_R == -1) range.e.r = _R = _range.e.r + 1;
  3970. }
  3971. for(var R = 0; R != data.length; ++R) {
  3972. if(!data[R]) continue;
  3973. if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
  3974. for(var C = 0; C != data[R].length; ++C) {
  3975. if(typeof data[R][C] === 'undefined') continue;
  3976. var cell = ({v: data[R][C] });
  3977. var __R = _R + R, __C = _C + C;
  3978. if(range.s.r > __R) range.s.r = __R;
  3979. if(range.s.c > __C) range.s.c = __C;
  3980. if(range.e.r < __R) range.e.r = __R;
  3981. if(range.e.c < __C) range.e.c = __C;
  3982. if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
  3983. else {
  3984. if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
  3985. if(cell.v === null) {
  3986. if(cell.f) cell.t = 'n';
  3987. else if(o.nullError) { cell.t = 'e'; cell.v = 0; }
  3988. else if(!o.sheetStubs) continue;
  3989. else cell.t = 'z';
  3990. }
  3991. else if(typeof cell.v === 'number') cell.t = 'n';
  3992. else if(typeof cell.v === 'boolean') cell.t = 'b';
  3993. else if(cell.v instanceof Date) {
  3994. cell.z = o.dateNF || table_fmt[14];
  3995. if(o.cellDates) { cell.t = 'd'; cell.w = SSF_format(cell.z, datenum(cell.v, o.date1904)); }
  3996. else { cell.t = 'n'; cell.v = datenum(cell.v, o.date1904); cell.w = SSF_format(cell.z, cell.v); }
  3997. }
  3998. else cell.t = 's';
  3999. }
  4000. if(dense) {
  4001. if(!ws[__R]) ws[__R] = [];
  4002. if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
  4003. ws[__R][__C] = cell;
  4004. } else {
  4005. var cell_ref = encode_cell(({c:__C,r:__R}));
  4006. if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
  4007. ws[cell_ref] = cell;
  4008. }
  4009. }
  4010. }
  4011. if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
  4012. return ws;
  4013. }
  4014. function aoa_to_sheet(data, opts) { return sheet_add_aoa(null, data, opts); }
  4015. function parse_Int32LE(data) {
  4016. return data.read_shift(4, 'i');
  4017. }
  4018. function write_UInt32LE(x, o) {
  4019. if (!o) o = new_buf(4);
  4020. o.write_shift(4, x);
  4021. return o;
  4022. }
  4023. /* [MS-XLSB] 2.5.168 */
  4024. function parse_XLWideString(data) {
  4025. var cchCharacters = data.read_shift(4);
  4026. return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, 'dbcs');
  4027. }
  4028. function write_XLWideString(data, o) {
  4029. var _null = false; if (o == null) { _null = true; o = new_buf(4 + 2 * data.length); }
  4030. o.write_shift(4, data.length);
  4031. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  4032. return _null ? o.slice(0, o.l) : o;
  4033. }
  4034. /* [MS-XLSB] 2.5.91 */
  4035. //function parse_LPWideString(data) {
  4036. // var cchCharacters = data.read_shift(2);
  4037. // return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "utf16le");
  4038. //}
  4039. /* [MS-XLSB] 2.5.143 */
  4040. function parse_StrRun(data) {
  4041. return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
  4042. }
  4043. function write_StrRun(run, o) {
  4044. if (!o) o = new_buf(4);
  4045. o.write_shift(2, run.ich || 0);
  4046. o.write_shift(2, run.ifnt || 0);
  4047. return o;
  4048. }
  4049. /* [MS-XLSB] 2.5.121 */
  4050. function parse_RichStr(data, length) {
  4051. var start = data.l;
  4052. var flags = data.read_shift(1);
  4053. var str = parse_XLWideString(data);
  4054. var rgsStrRun = [];
  4055. var z = ({ t: str, h: str });
  4056. if ((flags & 1) !== 0) { /* fRichStr */
  4057. /* TODO: formatted string */
  4058. var dwSizeStrRun = data.read_shift(4);
  4059. for (var i = 0; i != dwSizeStrRun; ++i) rgsStrRun.push(parse_StrRun(data));
  4060. z.r = rgsStrRun;
  4061. }
  4062. else z.r = [{ ich: 0, ifnt: 0 }];
  4063. //if((flags & 2) !== 0) { /* fExtStr */
  4064. // /* TODO: phonetic string */
  4065. //}
  4066. data.l = start + length;
  4067. return z;
  4068. }
  4069. function write_RichStr(str, o) {
  4070. /* TODO: formatted string */
  4071. var _null = false; if (o == null) { _null = true; o = new_buf(15 + 4 * str.t.length); }
  4072. o.write_shift(1, 0);
  4073. write_XLWideString(str.t, o);
  4074. return _null ? o.slice(0, o.l) : o;
  4075. }
  4076. /* [MS-XLSB] 2.4.328 BrtCommentText (RichStr w/1 run) */
  4077. var parse_BrtCommentText = parse_RichStr;
  4078. function write_BrtCommentText(str, o) {
  4079. /* TODO: formatted string */
  4080. var _null = false; if (o == null) { _null = true; o = new_buf(23 + 4 * str.t.length); }
  4081. o.write_shift(1, 1);
  4082. write_XLWideString(str.t, o);
  4083. o.write_shift(4, 1);
  4084. write_StrRun({ ich: 0, ifnt: 0 }, o);
  4085. return _null ? o.slice(0, o.l) : o;
  4086. }
  4087. /* [MS-XLSB] 2.5.9 */
  4088. function parse_XLSBCell(data) {
  4089. var col = data.read_shift(4);
  4090. var iStyleRef = data.read_shift(2);
  4091. iStyleRef += data.read_shift(1) << 16;
  4092. data.l++; //var fPhShow = data.read_shift(1);
  4093. return { c: col, iStyleRef: iStyleRef };
  4094. }
  4095. function write_XLSBCell(cell, o) {
  4096. if (o == null) o = new_buf(8);
  4097. o.write_shift(-4, cell.c);
  4098. o.write_shift(3, cell.iStyleRef || cell.s);
  4099. o.write_shift(1, 0); /* fPhShow */
  4100. return o;
  4101. }
  4102. /* Short XLSB Cell does not include column */
  4103. function parse_XLSBShortCell(data) {
  4104. var iStyleRef = data.read_shift(2);
  4105. iStyleRef += data.read_shift(1) <<16;
  4106. data.l++; //var fPhShow = data.read_shift(1);
  4107. return { c:-1, iStyleRef: iStyleRef };
  4108. }
  4109. function write_XLSBShortCell(cell, o) {
  4110. if(o == null) o = new_buf(4);
  4111. o.write_shift(3, cell.iStyleRef || cell.s);
  4112. o.write_shift(1, 0); /* fPhShow */
  4113. return o;
  4114. }
  4115. /* [MS-XLSB] 2.5.21 */
  4116. var parse_XLSBCodeName = parse_XLWideString;
  4117. var write_XLSBCodeName = write_XLWideString;
  4118. /* [MS-XLSB] 2.5.166 */
  4119. function parse_XLNullableWideString(data) {
  4120. var cchCharacters = data.read_shift(4);
  4121. return cchCharacters === 0 || cchCharacters === 0xFFFFFFFF ? "" : data.read_shift(cchCharacters, 'dbcs');
  4122. }
  4123. function write_XLNullableWideString(data, o) {
  4124. var _null = false; if (o == null) { _null = true; o = new_buf(127); }
  4125. o.write_shift(4, data.length > 0 ? data.length : 0xFFFFFFFF);
  4126. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  4127. return _null ? o.slice(0, o.l) : o;
  4128. }
  4129. /* [MS-XLSB] 2.5.165 */
  4130. var parse_XLNameWideString = parse_XLWideString;
  4131. //var write_XLNameWideString = write_XLWideString;
  4132. /* [MS-XLSB] 2.5.114 */
  4133. var parse_RelID = parse_XLNullableWideString;
  4134. var write_RelID = write_XLNullableWideString;
  4135. /* [MS-XLS] 2.5.217 ; [MS-XLSB] 2.5.122 */
  4136. function parse_RkNumber(data) {
  4137. var b = data.slice(data.l, data.l + 4);
  4138. var fX100 = (b[0] & 1), fInt = (b[0] & 2);
  4139. data.l += 4;
  4140. var RK = fInt === 0 ? __double([0, 0, 0, 0, (b[0] & 0xFC), b[1], b[2], b[3]], 0) : __readInt32LE(b, 0) >> 2;
  4141. return fX100 ? (RK / 100) : RK;
  4142. }
  4143. function write_RkNumber(data, o) {
  4144. if (o == null) o = new_buf(4);
  4145. var fX100 = 0, fInt = 0, d100 = data * 100;
  4146. if ((data == (data | 0)) && (data >= -(1 << 29)) && (data < (1 << 29))) { fInt = 1; }
  4147. else if ((d100 == (d100 | 0)) && (d100 >= -(1 << 29)) && (d100 < (1 << 29))) { fInt = 1; fX100 = 1; }
  4148. if (fInt) o.write_shift(-4, ((fX100 ? d100 : data) << 2) + (fX100 + 2));
  4149. else throw new Error("unsupported RkNumber " + data); // TODO
  4150. }
  4151. /* [MS-XLSB] 2.5.117 RfX */
  4152. function parse_RfX(data ) {
  4153. var cell = ({ s: {}, e: {} });
  4154. cell.s.r = data.read_shift(4);
  4155. cell.e.r = data.read_shift(4);
  4156. cell.s.c = data.read_shift(4);
  4157. cell.e.c = data.read_shift(4);
  4158. return cell;
  4159. }
  4160. function write_RfX(r, o) {
  4161. if (!o) o = new_buf(16);
  4162. o.write_shift(4, r.s.r);
  4163. o.write_shift(4, r.e.r);
  4164. o.write_shift(4, r.s.c);
  4165. o.write_shift(4, r.e.c);
  4166. return o;
  4167. }
  4168. /* [MS-XLSB] 2.5.153 UncheckedRfX */
  4169. var parse_UncheckedRfX = parse_RfX;
  4170. var write_UncheckedRfX = write_RfX;
  4171. /* [MS-XLSB] 2.5.155 UncheckedSqRfX */
  4172. //function parse_UncheckedSqRfX(data) {
  4173. // var cnt = data.read_shift(4);
  4174. // var out = [];
  4175. // for(var i = 0; i < cnt; ++i) {
  4176. // var rng = parse_UncheckedRfX(data);
  4177. // out.push(encode_range(rng));
  4178. // }
  4179. // return out.join(",");
  4180. //}
  4181. //function write_UncheckedSqRfX(sqrfx) {
  4182. // var parts = sqrfx.split(/\s*,\s*/);
  4183. // var o = new_buf(4); o.write_shift(4, parts.length);
  4184. // var out = [o];
  4185. // parts.forEach(function(rng) {
  4186. // out.push(write_UncheckedRfX(safe_decode_range(rng)));
  4187. // });
  4188. // return bconcat(out);
  4189. //}
  4190. /* [MS-XLS] 2.5.342 ; [MS-XLSB] 2.5.171 */
  4191. /* TODO: error checking, NaN and Infinity values are not valid Xnum */
  4192. function parse_Xnum(data) {
  4193. if(data.length - data.l < 8) throw "XLS Xnum Buffer underflow";
  4194. return data.read_shift(8, 'f');
  4195. }
  4196. function write_Xnum(data, o) { return (o || new_buf(8)).write_shift(8, data, 'f'); }
  4197. /* [MS-XLSB] 2.4.324 BrtColor */
  4198. function parse_BrtColor(data) {
  4199. var out = {};
  4200. var d = data.read_shift(1);
  4201. //var fValidRGB = d & 1;
  4202. var xColorType = d >>> 1;
  4203. var index = data.read_shift(1);
  4204. var nTS = data.read_shift(2, 'i');
  4205. var bR = data.read_shift(1);
  4206. var bG = data.read_shift(1);
  4207. var bB = data.read_shift(1);
  4208. data.l++; //var bAlpha = data.read_shift(1);
  4209. switch (xColorType) {
  4210. case 0: out.auto = 1; break;
  4211. case 1:
  4212. out.index = index;
  4213. var icv = XLSIcv[index];
  4214. /* automatic pseudo index 81 */
  4215. if (icv) out.rgb = rgb2Hex(icv);
  4216. break;
  4217. case 2:
  4218. /* if(!fValidRGB) throw new Error("invalid"); */
  4219. out.rgb = rgb2Hex([bR, bG, bB]);
  4220. break;
  4221. case 3: out.theme = index; break;
  4222. }
  4223. if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;
  4224. return out;
  4225. }
  4226. function write_BrtColor(color, o) {
  4227. if (!o) o = new_buf(8);
  4228. if (!color || color.auto) { o.write_shift(4, 0); o.write_shift(4, 0); return o; }
  4229. if (color.index != null) {
  4230. o.write_shift(1, 0x02);
  4231. o.write_shift(1, color.index);
  4232. } else if (color.theme != null) {
  4233. o.write_shift(1, 0x06);
  4234. o.write_shift(1, color.theme);
  4235. } else {
  4236. o.write_shift(1, 0x05);
  4237. o.write_shift(1, 0);
  4238. }
  4239. var nTS = color.tint || 0;
  4240. if (nTS > 0) nTS *= 32767;
  4241. else if (nTS < 0) nTS *= 32768;
  4242. o.write_shift(2, nTS);
  4243. if (!color.rgb || color.theme != null) {
  4244. o.write_shift(2, 0);
  4245. o.write_shift(1, 0);
  4246. o.write_shift(1, 0);
  4247. } else {
  4248. var rgb = (color.rgb || 'FFFFFF');
  4249. if (typeof rgb == 'number') rgb = ("000000" + rgb.toString(16)).slice(-6);
  4250. o.write_shift(1, parseInt(rgb.slice(0, 2), 16));
  4251. o.write_shift(1, parseInt(rgb.slice(2, 4), 16));
  4252. o.write_shift(1, parseInt(rgb.slice(4, 6), 16));
  4253. o.write_shift(1, 0xFF);
  4254. }
  4255. return o;
  4256. }
  4257. /* [MS-XLSB] 2.5.52 */
  4258. function parse_FontFlags(data) {
  4259. var d = data.read_shift(1);
  4260. data.l++;
  4261. var out = {
  4262. fBold: d & 0x01,
  4263. fItalic: d & 0x02,
  4264. fUnderline: d & 0x04,
  4265. fStrikeout: d & 0x08,
  4266. fOutline: d & 0x10,
  4267. fShadow: d & 0x20,
  4268. fCondense: d & 0x40,
  4269. fExtend: d & 0x80
  4270. };
  4271. return out;
  4272. }
  4273. function write_FontFlags(font, o) {
  4274. if (!o) o = new_buf(2);
  4275. var grbit =
  4276. (font.italic ? 0x02 : 0) |
  4277. (font.strike ? 0x08 : 0) |
  4278. (font.outline ? 0x10 : 0) |
  4279. (font.shadow ? 0x20 : 0) |
  4280. (font.condense ? 0x40 : 0) |
  4281. (font.extend ? 0x80 : 0);
  4282. o.write_shift(1, grbit);
  4283. o.write_shift(1, 0);
  4284. return o;
  4285. }
  4286. /* [MS-OLEDS] 2.3.1 and 2.3.2 */
  4287. function parse_ClipboardFormatOrString(o, w) {
  4288. // $FlowIgnore
  4289. var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
  4290. var m = o.read_shift(4);
  4291. switch (m) {
  4292. case 0x00000000: return "";
  4293. case 0xffffffff: case 0xfffffffe: return ClipFmt[o.read_shift(4)] || "";
  4294. }
  4295. if (m > 0x190) throw new Error("Unsupported Clipboard: " + m.toString(16));
  4296. o.l -= 4;
  4297. return o.read_shift(0, w == 1 ? "lpstr" : "lpwstr");
  4298. }
  4299. function parse_ClipboardFormatOrAnsiString(o) { return parse_ClipboardFormatOrString(o, 1); }
  4300. function parse_ClipboardFormatOrUnicodeString(o) { return parse_ClipboardFormatOrString(o, 2); }
  4301. /* [MS-OLEPS] 2.2 PropertyType */
  4302. // Note: some tree shakers cannot handle VT_VECTOR | $CONST, hence extra vars
  4303. //var VT_EMPTY = 0x0000;
  4304. //var VT_NULL = 0x0001;
  4305. var VT_I2 = 0x0002;
  4306. var VT_I4 = 0x0003;
  4307. //var VT_R4 = 0x0004;
  4308. //var VT_R8 = 0x0005;
  4309. //var VT_CY = 0x0006;
  4310. //var VT_DATE = 0x0007;
  4311. //var VT_BSTR = 0x0008;
  4312. //var VT_ERROR = 0x000A;
  4313. var VT_BOOL = 0x000B;
  4314. var VT_VARIANT = 0x000C;
  4315. //var VT_DECIMAL = 0x000E;
  4316. //var VT_I1 = 0x0010;
  4317. //var VT_UI1 = 0x0011;
  4318. //var VT_UI2 = 0x0012;
  4319. var VT_UI4 = 0x0013;
  4320. //var VT_I8 = 0x0014;
  4321. //var VT_UI8 = 0x0015;
  4322. //var VT_INT = 0x0016;
  4323. //var VT_UINT = 0x0017;
  4324. //var VT_LPSTR = 0x001E;
  4325. //var VT_LPWSTR = 0x001F;
  4326. var VT_FILETIME = 0x0040;
  4327. var VT_BLOB = 0x0041;
  4328. //var VT_STREAM = 0x0042;
  4329. //var VT_STORAGE = 0x0043;
  4330. //var VT_STREAMED_Object = 0x0044;
  4331. //var VT_STORED_Object = 0x0045;
  4332. //var VT_BLOB_Object = 0x0046;
  4333. var VT_CF = 0x0047;
  4334. //var VT_CLSID = 0x0048;
  4335. //var VT_VERSIONED_STREAM = 0x0049;
  4336. //var VT_VECTOR = 0x1000;
  4337. var VT_VECTOR_VARIANT = 0x100C;
  4338. var VT_VECTOR_LPSTR = 0x101E;
  4339. //var VT_ARRAY = 0x2000;
  4340. var VT_STRING = 0x0050; // 2.3.3.1.11 VtString
  4341. var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString
  4342. var VT_CUSTOM = [VT_STRING, VT_USTR];
  4343. /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
  4344. var DocSummaryPIDDSI = {
  4345. 0x01: { n: 'CodePage', t: VT_I2 },
  4346. 0x02: { n: 'Category', t: VT_STRING },
  4347. 0x03: { n: 'PresentationFormat', t: VT_STRING },
  4348. 0x04: { n: 'ByteCount', t: VT_I4 },
  4349. 0x05: { n: 'LineCount', t: VT_I4 },
  4350. 0x06: { n: 'ParagraphCount', t: VT_I4 },
  4351. 0x07: { n: 'SlideCount', t: VT_I4 },
  4352. 0x08: { n: 'NoteCount', t: VT_I4 },
  4353. 0x09: { n: 'HiddenCount', t: VT_I4 },
  4354. 0x0a: { n: 'MultimediaClipCount', t: VT_I4 },
  4355. 0x0b: { n: 'ScaleCrop', t: VT_BOOL },
  4356. 0x0c: { n: 'HeadingPairs', t: VT_VECTOR_VARIANT /* VT_VECTOR | VT_VARIANT */ },
  4357. 0x0d: { n: 'TitlesOfParts', t: VT_VECTOR_LPSTR /* VT_VECTOR | VT_LPSTR */ },
  4358. 0x0e: { n: 'Manager', t: VT_STRING },
  4359. 0x0f: { n: 'Company', t: VT_STRING },
  4360. 0x10: { n: 'LinksUpToDate', t: VT_BOOL },
  4361. 0x11: { n: 'CharacterCount', t: VT_I4 },
  4362. 0x13: { n: 'SharedDoc', t: VT_BOOL },
  4363. 0x16: { n: 'HyperlinksChanged', t: VT_BOOL },
  4364. 0x17: { n: 'AppVersion', t: VT_I4, p: 'version' },
  4365. 0x18: { n: 'DigSig', t: VT_BLOB },
  4366. 0x1A: { n: 'ContentType', t: VT_STRING },
  4367. 0x1B: { n: 'ContentStatus', t: VT_STRING },
  4368. 0x1C: { n: 'Language', t: VT_STRING },
  4369. 0x1D: { n: 'Version', t: VT_STRING },
  4370. 0xFF: {},
  4371. /* [MS-OLEPS] 2.18 */
  4372. 0x80000000: { n: 'Locale', t: VT_UI4 },
  4373. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  4374. 0x72627262: {}
  4375. };
  4376. /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
  4377. var SummaryPIDSI = {
  4378. 0x01: { n: 'CodePage', t: VT_I2 },
  4379. 0x02: { n: 'Title', t: VT_STRING },
  4380. 0x03: { n: 'Subject', t: VT_STRING },
  4381. 0x04: { n: 'Author', t: VT_STRING },
  4382. 0x05: { n: 'Keywords', t: VT_STRING },
  4383. 0x06: { n: 'Comments', t: VT_STRING },
  4384. 0x07: { n: 'Template', t: VT_STRING },
  4385. 0x08: { n: 'LastAuthor', t: VT_STRING },
  4386. 0x09: { n: 'RevNumber', t: VT_STRING },
  4387. 0x0A: { n: 'EditTime', t: VT_FILETIME },
  4388. 0x0B: { n: 'LastPrinted', t: VT_FILETIME },
  4389. 0x0C: { n: 'CreatedDate', t: VT_FILETIME },
  4390. 0x0D: { n: 'ModifiedDate', t: VT_FILETIME },
  4391. 0x0E: { n: 'PageCount', t: VT_I4 },
  4392. 0x0F: { n: 'WordCount', t: VT_I4 },
  4393. 0x10: { n: 'CharCount', t: VT_I4 },
  4394. 0x11: { n: 'Thumbnail', t: VT_CF },
  4395. 0x12: { n: 'Application', t: VT_STRING },
  4396. 0x13: { n: 'DocSecurity', t: VT_I4 },
  4397. 0xFF: {},
  4398. /* [MS-OLEPS] 2.18 */
  4399. 0x80000000: { n: 'Locale', t: VT_UI4 },
  4400. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  4401. 0x72627262: {}
  4402. };
  4403. /* [MS-XLS] 2.4.63 Country/Region codes */
  4404. var CountryEnum = {
  4405. 0x0001: "US", // United States
  4406. 0x0002: "CA", // Canada
  4407. 0x0003: "", // Latin America (except Brazil)
  4408. 0x0007: "RU", // Russia
  4409. 0x0014: "EG", // Egypt
  4410. 0x001E: "GR", // Greece
  4411. 0x001F: "NL", // Netherlands
  4412. 0x0020: "BE", // Belgium
  4413. 0x0021: "FR", // France
  4414. 0x0022: "ES", // Spain
  4415. 0x0024: "HU", // Hungary
  4416. 0x0027: "IT", // Italy
  4417. 0x0029: "CH", // Switzerland
  4418. 0x002B: "AT", // Austria
  4419. 0x002C: "GB", // United Kingdom
  4420. 0x002D: "DK", // Denmark
  4421. 0x002E: "SE", // Sweden
  4422. 0x002F: "NO", // Norway
  4423. 0x0030: "PL", // Poland
  4424. 0x0031: "DE", // Germany
  4425. 0x0034: "MX", // Mexico
  4426. 0x0037: "BR", // Brazil
  4427. 0x003d: "AU", // Australia
  4428. 0x0040: "NZ", // New Zealand
  4429. 0x0042: "TH", // Thailand
  4430. 0x0051: "JP", // Japan
  4431. 0x0052: "KR", // Korea
  4432. 0x0054: "VN", // Viet Nam
  4433. 0x0056: "CN", // China
  4434. 0x005A: "TR", // Turkey
  4435. 0x0069: "JS", // Ramastan
  4436. 0x00D5: "DZ", // Algeria
  4437. 0x00D8: "MA", // Morocco
  4438. 0x00DA: "LY", // Libya
  4439. 0x015F: "PT", // Portugal
  4440. 0x0162: "IS", // Iceland
  4441. 0x0166: "FI", // Finland
  4442. 0x01A4: "CZ", // Czech Republic
  4443. 0x0376: "TW", // Taiwan
  4444. 0x03C1: "LB", // Lebanon
  4445. 0x03C2: "JO", // Jordan
  4446. 0x03C3: "SY", // Syria
  4447. 0x03C4: "IQ", // Iraq
  4448. 0x03C5: "KW", // Kuwait
  4449. 0x03C6: "SA", // Saudi Arabia
  4450. 0x03CB: "AE", // United Arab Emirates
  4451. 0x03CC: "IL", // Israel
  4452. 0x03CE: "QA", // Qatar
  4453. 0x03D5: "IR", // Iran
  4454. 0xFFFF: "US" // United States
  4455. };
  4456. /* [MS-XLS] 2.5.127 */
  4457. var XLSFillPattern = [
  4458. null,
  4459. 'solid',
  4460. 'mediumGray',
  4461. 'darkGray',
  4462. 'lightGray',
  4463. 'darkHorizontal',
  4464. 'darkVertical',
  4465. 'darkDown',
  4466. 'darkUp',
  4467. 'darkGrid',
  4468. 'darkTrellis',
  4469. 'lightHorizontal',
  4470. 'lightVertical',
  4471. 'lightDown',
  4472. 'lightUp',
  4473. 'lightGrid',
  4474. 'lightTrellis',
  4475. 'gray125',
  4476. 'gray0625'
  4477. ];
  4478. function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }
  4479. /* [MS-XLS] 2.5.161 */
  4480. /* [MS-XLSB] 2.5.75 Icv */
  4481. var _XLSIcv = rgbify([
  4482. /* Color Constants */
  4483. 0x000000,
  4484. 0xFFFFFF,
  4485. 0xFF0000,
  4486. 0x00FF00,
  4487. 0x0000FF,
  4488. 0xFFFF00,
  4489. 0xFF00FF,
  4490. 0x00FFFF,
  4491. /* Overridable Defaults */
  4492. 0x000000,
  4493. 0xFFFFFF,
  4494. 0xFF0000,
  4495. 0x00FF00,
  4496. 0x0000FF,
  4497. 0xFFFF00,
  4498. 0xFF00FF,
  4499. 0x00FFFF,
  4500. 0x800000,
  4501. 0x008000,
  4502. 0x000080,
  4503. 0x808000,
  4504. 0x800080,
  4505. 0x008080,
  4506. 0xC0C0C0,
  4507. 0x808080,
  4508. 0x9999FF,
  4509. 0x993366,
  4510. 0xFFFFCC,
  4511. 0xCCFFFF,
  4512. 0x660066,
  4513. 0xFF8080,
  4514. 0x0066CC,
  4515. 0xCCCCFF,
  4516. 0x000080,
  4517. 0xFF00FF,
  4518. 0xFFFF00,
  4519. 0x00FFFF,
  4520. 0x800080,
  4521. 0x800000,
  4522. 0x008080,
  4523. 0x0000FF,
  4524. 0x00CCFF,
  4525. 0xCCFFFF,
  4526. 0xCCFFCC,
  4527. 0xFFFF99,
  4528. 0x99CCFF,
  4529. 0xFF99CC,
  4530. 0xCC99FF,
  4531. 0xFFCC99,
  4532. 0x3366FF,
  4533. 0x33CCCC,
  4534. 0x99CC00,
  4535. 0xFFCC00,
  4536. 0xFF9900,
  4537. 0xFF6600,
  4538. 0x666699,
  4539. 0x969696,
  4540. 0x003366,
  4541. 0x339966,
  4542. 0x003300,
  4543. 0x333300,
  4544. 0x993300,
  4545. 0x993366,
  4546. 0x333399,
  4547. 0x333333,
  4548. /* Other entries to appease BIFF8/12 */
  4549. 0x000000, /* 0x40 icvForeground ?? */
  4550. 0xFFFFFF, /* 0x41 icvBackground ?? */
  4551. 0x000000, /* 0x42 icvFrame ?? */
  4552. 0x000000, /* 0x43 icv3D ?? */
  4553. 0x000000, /* 0x44 icv3DText ?? */
  4554. 0x000000, /* 0x45 icv3DHilite ?? */
  4555. 0x000000, /* 0x46 icv3DShadow ?? */
  4556. 0x000000, /* 0x47 icvHilite ?? */
  4557. 0x000000, /* 0x48 icvCtlText ?? */
  4558. 0x000000, /* 0x49 icvCtlScrl ?? */
  4559. 0x000000, /* 0x4A icvCtlInv ?? */
  4560. 0x000000, /* 0x4B icvCtlBody ?? */
  4561. 0x000000, /* 0x4C icvCtlFrame ?? */
  4562. 0x000000, /* 0x4D icvCtlFore ?? */
  4563. 0x000000, /* 0x4E icvCtlBack ?? */
  4564. 0x000000, /* 0x4F icvCtlNeutral */
  4565. 0x000000, /* 0x50 icvInfoBk ?? */
  4566. 0x000000 /* 0x51 icvInfoText ?? */
  4567. ]);
  4568. var XLSIcv = dup(_XLSIcv);
  4569. /* [MS-XLSB] 2.5.97.2 */
  4570. var BErr = {
  4571. 0x00: "#NULL!",
  4572. 0x07: "#DIV/0!",
  4573. 0x0F: "#VALUE!",
  4574. 0x17: "#REF!",
  4575. 0x1D: "#NAME?",
  4576. 0x24: "#NUM!",
  4577. 0x2A: "#N/A",
  4578. 0x2B: "#GETTING_DATA",
  4579. 0xFF: "#WTF?"
  4580. };
  4581. //var RBErr = evert_num(BErr);
  4582. var RBErr = {
  4583. "#NULL!": 0x00,
  4584. "#DIV/0!": 0x07,
  4585. "#VALUE!": 0x0F,
  4586. "#REF!": 0x17,
  4587. "#NAME?": 0x1D,
  4588. "#NUM!": 0x24,
  4589. "#N/A": 0x2A,
  4590. "#GETTING_DATA": 0x2B,
  4591. "#WTF?": 0xFF
  4592. };
  4593. var XLSLblBuiltIn = [
  4594. "_xlnm.Consolidate_Area",
  4595. "_xlnm.Auto_Open",
  4596. "_xlnm.Auto_Close",
  4597. "_xlnm.Extract",
  4598. "_xlnm.Database",
  4599. "_xlnm.Criteria",
  4600. "_xlnm.Print_Area",
  4601. "_xlnm.Print_Titles",
  4602. "_xlnm.Recorder",
  4603. "_xlnm.Data_Form",
  4604. "_xlnm.Auto_Activate",
  4605. "_xlnm.Auto_Deactivate",
  4606. "_xlnm.Sheet_Title",
  4607. "_xlnm._FilterDatabase"
  4608. ];
  4609. /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
  4610. /* 12.3 Part Summary <SpreadsheetML> */
  4611. /* 14.2 Part Summary <DrawingML> */
  4612. /* [MS-XLSX] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
  4613. var ct2type/*{[string]:string}*/ = ({
  4614. /* Workbook */
  4615. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  4616. "application/vnd.ms-excel.sheet.macroEnabled.main+xml": "workbooks",
  4617. "application/vnd.ms-excel.sheet.binary.macroEnabled.main": "workbooks",
  4618. "application/vnd.ms-excel.addin.macroEnabled.main+xml": "workbooks",
  4619. "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": "workbooks",
  4620. /* Worksheet */
  4621. "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": "sheets",
  4622. "application/vnd.ms-excel.worksheet": "sheets",
  4623. "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
  4624. /* Chartsheet */
  4625. "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "charts",
  4626. "application/vnd.ms-excel.chartsheet": "charts",
  4627. /* Macrosheet */
  4628. "application/vnd.ms-excel.macrosheet+xml": "macros",
  4629. "application/vnd.ms-excel.macrosheet": "macros",
  4630. "application/vnd.ms-excel.intlmacrosheet": "TODO",
  4631. "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
  4632. /* Dialogsheet */
  4633. "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "dialogs",
  4634. "application/vnd.ms-excel.dialogsheet": "dialogs",
  4635. /* Shared Strings */
  4636. "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs",
  4637. "application/vnd.ms-excel.sharedStrings": "strs",
  4638. /* Styles */
  4639. "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": "styles",
  4640. "application/vnd.ms-excel.styles": "styles",
  4641. /* File Properties */
  4642. "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  4643. "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  4644. "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  4645. /* Custom Data Properties */
  4646. "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  4647. "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  4648. /* Comments */
  4649. "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments",
  4650. "application/vnd.ms-excel.comments": "comments",
  4651. "application/vnd.ms-excel.threadedcomments+xml": "threadedcomments",
  4652. "application/vnd.ms-excel.person+xml": "people",
  4653. /* Metadata (Stock/Geography and Dynamic Array) */
  4654. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "metadata",
  4655. "application/vnd.ms-excel.sheetMetadata": "metadata",
  4656. /* PivotTable */
  4657. "application/vnd.ms-excel.pivotTable": "TODO",
  4658. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  4659. /* Chart Objects */
  4660. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  4661. /* Chart Colors */
  4662. "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  4663. /* Chart Style */
  4664. "application/vnd.ms-office.chartstyle+xml": "TODO",
  4665. /* Chart Advanced */
  4666. "application/vnd.ms-office.chartex+xml": "TODO",
  4667. /* Calculation Chain */
  4668. "application/vnd.ms-excel.calcChain": "calcchains",
  4669. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  4670. /* Printer Settings */
  4671. "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  4672. /* ActiveX */
  4673. "application/vnd.ms-office.activeX": "TODO",
  4674. "application/vnd.ms-office.activeX+xml": "TODO",
  4675. /* Custom Toolbars */
  4676. "application/vnd.ms-excel.attachedToolbars": "TODO",
  4677. /* External Data Connections */
  4678. "application/vnd.ms-excel.connections": "TODO",
  4679. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  4680. /* External Links */
  4681. "application/vnd.ms-excel.externalLink": "links",
  4682. "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  4683. /* PivotCache */
  4684. "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  4685. "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  4686. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  4687. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  4688. /* Query Table */
  4689. "application/vnd.ms-excel.queryTable": "TODO",
  4690. "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  4691. /* Shared Workbook */
  4692. "application/vnd.ms-excel.userNames": "TODO",
  4693. "application/vnd.ms-excel.revisionHeaders": "TODO",
  4694. "application/vnd.ms-excel.revisionLog": "TODO",
  4695. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  4696. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  4697. "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  4698. /* Single Cell Table */
  4699. "application/vnd.ms-excel.tableSingleCells": "TODO",
  4700. "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  4701. /* Slicer */
  4702. "application/vnd.ms-excel.slicer": "TODO",
  4703. "application/vnd.ms-excel.slicerCache": "TODO",
  4704. "application/vnd.ms-excel.slicer+xml": "TODO",
  4705. "application/vnd.ms-excel.slicerCache+xml": "TODO",
  4706. /* Sort Map */
  4707. "application/vnd.ms-excel.wsSortMap": "TODO",
  4708. /* Table */
  4709. "application/vnd.ms-excel.table": "TODO",
  4710. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  4711. /* Themes */
  4712. "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  4713. /* Theme Override */
  4714. "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  4715. /* Timeline */
  4716. "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
  4717. "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
  4718. /* VBA */
  4719. "application/vnd.ms-office.vbaProject": "vba",
  4720. "application/vnd.ms-office.vbaProjectSignature": "TODO",
  4721. /* Volatile Dependencies */
  4722. "application/vnd.ms-office.volatileDependencies": "TODO",
  4723. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  4724. /* Control Properties */
  4725. "application/vnd.ms-excel.controlproperties+xml": "TODO",
  4726. /* Data Model */
  4727. "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  4728. /* Survey */
  4729. "application/vnd.ms-excel.Survey+xml": "TODO",
  4730. /* Drawing */
  4731. "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  4732. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  4733. "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  4734. "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  4735. "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  4736. "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  4737. /* VML */
  4738. "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  4739. "application/vnd.openxmlformats-package.relationships+xml": "rels",
  4740. "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  4741. /* Image */
  4742. "image/png": "TODO",
  4743. "sheet": "js"
  4744. });
  4745. var CT_LIST = {
  4746. workbooks: {
  4747. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  4748. xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
  4749. xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
  4750. xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
  4751. xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
  4752. },
  4753. strs: { /* Shared Strings */
  4754. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
  4755. xlsb: "application/vnd.ms-excel.sharedStrings"
  4756. },
  4757. comments: { /* Comments */
  4758. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  4759. xlsb: "application/vnd.ms-excel.comments"
  4760. },
  4761. sheets: { /* Worksheet */
  4762. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  4763. xlsb: "application/vnd.ms-excel.worksheet"
  4764. },
  4765. charts: { /* Chartsheet */
  4766. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
  4767. xlsb: "application/vnd.ms-excel.chartsheet"
  4768. },
  4769. dialogs: { /* Dialogsheet */
  4770. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
  4771. xlsb: "application/vnd.ms-excel.dialogsheet"
  4772. },
  4773. macros: { /* Macrosheet (Excel 4.0 Macros) */
  4774. xlsx: "application/vnd.ms-excel.macrosheet+xml",
  4775. xlsb: "application/vnd.ms-excel.macrosheet"
  4776. },
  4777. metadata: { /* Metadata (Stock/Geography and Dynamic Array) */
  4778. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",
  4779. xlsb: "application/vnd.ms-excel.sheetMetadata"
  4780. },
  4781. styles: { /* Styles */
  4782. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
  4783. xlsb: "application/vnd.ms-excel.styles"
  4784. }
  4785. };
  4786. function new_ct() {
  4787. return ({
  4788. workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
  4789. rels:[], strs:[], comments:[], threadedcomments:[], links:[],
  4790. coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
  4791. calcchains:[], vba: [], drawings: [], metadata: [], people:[],
  4792. TODO:[], xmlns: "" });
  4793. }
  4794. function parse_ct(data) {
  4795. var ct = new_ct();
  4796. if(!data || !data.match) return ct;
  4797. var ctext = {};
  4798. (data.match(tagregex)||[]).forEach(function(x) {
  4799. var y = parsexmltag(x);
  4800. switch(y[0].replace(nsregex,"<")) {
  4801. case '<?xml': break;
  4802. case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
  4803. case '<Default': ctext[y.Extension.toLowerCase()] = y.ContentType; break;
  4804. case '<Override':
  4805. if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
  4806. break;
  4807. }
  4808. });
  4809. if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  4810. ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  4811. ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  4812. ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  4813. ct.defaults = ctext;
  4814. delete ct.calcchains;
  4815. return ct;
  4816. }
  4817. function write_ct(ct, opts, raw) {
  4818. var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);
  4819. var o = [], v;
  4820. if(!raw) {
  4821. o[o.length] = (XML_HEADER);
  4822. o[o.length] = writextag('Types', null, {
  4823. 'xmlns': XMLNS.CT,
  4824. 'xmlns:xsd': XMLNS.xsd,
  4825. 'xmlns:xsi': XMLNS.xsi
  4826. });
  4827. o = o.concat([
  4828. ['xml', 'application/xml'],
  4829. ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
  4830. ['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
  4831. ['data', 'application/vnd.openxmlformats-officedocument.model+data'],
  4832. /* from test files */
  4833. ['bmp', 'image/bmp'],
  4834. ['png', 'image/png'],
  4835. ['gif', 'image/gif'],
  4836. ['emf', 'image/x-emf'],
  4837. ['wmf', 'image/x-wmf'],
  4838. ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
  4839. ['tif', 'image/tiff'], ['tiff', 'image/tiff'],
  4840. ['pdf', 'application/pdf'],
  4841. ['rels', 'application/vnd.openxmlformats-package.relationships+xml']
  4842. ].map(function(x) {
  4843. return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
  4844. }));
  4845. }
  4846. /* only write first instance */
  4847. var f1 = function(w) {
  4848. if(ct[w] && ct[w].length > 0) {
  4849. v = ct[w][0];
  4850. o[o.length] = (writextag('Override', null, {
  4851. 'PartName': (v[0] == '/' ? "":"/") + v,
  4852. 'ContentType': CT_LIST[w][opts.bookType] || CT_LIST[w]['xlsx']
  4853. }));
  4854. }
  4855. };
  4856. /* book type-specific */
  4857. var f2 = function(w) {
  4858. (ct[w]||[]).forEach(function(v) {
  4859. o[o.length] = (writextag('Override', null, {
  4860. 'PartName': (v[0] == '/' ? "":"/") + v,
  4861. 'ContentType': CT_LIST[w][opts.bookType] || CT_LIST[w]['xlsx']
  4862. }));
  4863. });
  4864. };
  4865. /* standard type */
  4866. var f3 = function(t) {
  4867. (ct[t]||[]).forEach(function(v) {
  4868. o[o.length] = (writextag('Override', null, {
  4869. 'PartName': (v[0] == '/' ? "":"/") + v,
  4870. 'ContentType': type2ct[t][0]
  4871. }));
  4872. });
  4873. };
  4874. f1('workbooks');
  4875. f2('sheets');
  4876. f2('charts');
  4877. f3('themes');
  4878. ['strs', 'styles'].forEach(f1);
  4879. ['coreprops', 'extprops', 'custprops'].forEach(f3);
  4880. f3('vba');
  4881. f3('comments');
  4882. f3('threadedcomments');
  4883. f3('drawings');
  4884. f2('metadata');
  4885. f3('people');
  4886. if(!raw && o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
  4887. return o.join("");
  4888. }
  4889. /* 9.3 Relationships */
  4890. var RELS = ({
  4891. WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4892. SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4893. HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  4894. VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  4895. XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  4896. XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  4897. XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  4898. CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  4899. CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  4900. CMNT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
  4901. CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
  4902. EXT_PROPS: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
  4903. CUST_PROPS: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
  4904. SST: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
  4905. STY: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
  4906. THEME: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
  4907. CHART: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",
  4908. CHARTEX: "http://schemas.microsoft.com/office/2014/relationships/chartEx",
  4909. CS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet",
  4910. WS: [
  4911. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  4912. "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  4913. ],
  4914. DS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet",
  4915. MS: "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet",
  4916. IMG: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
  4917. DRAW: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",
  4918. XLMETA: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",
  4919. TCMNT: "http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",
  4920. PEOPLE: "http://schemas.microsoft.com/office/2017/10/relationships/person",
  4921. CONN: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/connections",
  4922. VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
  4923. });
  4924. /* 9.3.3 Representing Relationships */
  4925. function get_rels_path(file) {
  4926. var n = file.lastIndexOf("/");
  4927. return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
  4928. }
  4929. function parse_rels(data, currentFilePath) {
  4930. var rels = {"!id":{}};
  4931. if (!data) return rels;
  4932. if (currentFilePath.charAt(0) !== '/') {
  4933. currentFilePath = '/'+currentFilePath;
  4934. }
  4935. var hash = {};
  4936. (data.match(tagregex)||[]).forEach(function(x) {
  4937. var y = parsexmltag(x);
  4938. /* 9.3.2.2 OPC_Relationships */
  4939. if (y[0] === '<Relationship') {
  4940. var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; if(y.TargetMode) rel.TargetMode = y.TargetMode;
  4941. var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
  4942. rels[canonictarget] = rel;
  4943. hash[y.Id] = rel;
  4944. }
  4945. });
  4946. rels["!id"] = hash;
  4947. return rels;
  4948. }
  4949. /* TODO */
  4950. function write_rels(rels) {
  4951. var o = [XML_HEADER, writextag('Relationships', null, {
  4952. //'xmlns:ns0': XMLNS.RELS,
  4953. 'xmlns': XMLNS.RELS
  4954. })];
  4955. keys(rels['!id']).forEach(function(rid) {
  4956. o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
  4957. });
  4958. if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
  4959. return o.join("");
  4960. }
  4961. function add_rels(rels, rId, f, type, relobj, targetmode) {
  4962. if(!relobj) relobj = {};
  4963. if(!rels['!id']) rels['!id'] = {};
  4964. if(!rels['!idx']) rels['!idx'] = 1;
  4965. if(rId < 0) for(rId = rels['!idx']; rels['!id']['rId' + rId]; ++rId){/* empty */}
  4966. rels['!idx'] = rId + 1;
  4967. relobj.Id = 'rId' + rId;
  4968. relobj.Type = type;
  4969. relobj.Target = f;
  4970. if(targetmode) relobj.TargetMode = targetmode;
  4971. else if([RELS.HLINK, RELS.XPATH, RELS.XMISS].indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
  4972. if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
  4973. rels['!id'][relobj.Id] = relobj;
  4974. rels[('/' + relobj.Target).replace("//","/")] = relobj;
  4975. return rId;
  4976. }
  4977. /* Open Document Format for Office Applications (OpenDocument) Version 1.2 */
  4978. /* Part 3 Section 4 Manifest File */
  4979. var CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
  4980. function parse_manifest(d, opts) {
  4981. var str = xlml_normalize(d);
  4982. var Rn;
  4983. var FEtag;
  4984. while((Rn = xlmlregex.exec(str))) switch(Rn[3]) {
  4985. case 'manifest': break; // 4.2 <manifest:manifest>
  4986. case 'file-entry': // 4.3 <manifest:file-entry>
  4987. FEtag = parsexmltag(Rn[0], false);
  4988. if(FEtag.path == '/' && FEtag.type !== CT_ODS) throw new Error("This OpenDocument is not a spreadsheet");
  4989. break;
  4990. case 'encryption-data': // 4.4 <manifest:encryption-data>
  4991. case 'algorithm': // 4.5 <manifest:algorithm>
  4992. case 'start-key-generation': // 4.6 <manifest:start-key-generation>
  4993. case 'key-derivation': // 4.7 <manifest:key-derivation>
  4994. throw new Error("Unsupported ODS Encryption");
  4995. default: if(opts && opts.WTF) throw Rn;
  4996. }
  4997. }
  4998. function write_manifest(manifest) {
  4999. var o = [XML_HEADER];
  5000. o.push('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">\n');
  5001. o.push(' <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>\n');
  5002. for(var i = 0; i < manifest.length; ++i) o.push(' <manifest:file-entry manifest:full-path="' + manifest[i][0] + '" manifest:media-type="' + manifest[i][1] + '"/>\n');
  5003. o.push('</manifest:manifest>');
  5004. return o.join("");
  5005. }
  5006. /* Part 3 Section 6 Metadata Manifest File */
  5007. function write_rdf_type(file, res, tag) {
  5008. return [
  5009. ' <rdf:Description rdf:about="' + file + '">\n',
  5010. ' <rdf:type rdf:resource="http://docs.oasis-open.org/ns/office/1.2/meta/' + (tag || "odf") + '#' + res + '"/>\n',
  5011. ' </rdf:Description>\n'
  5012. ].join("");
  5013. }
  5014. function write_rdf_has(base, file) {
  5015. return [
  5016. ' <rdf:Description rdf:about="' + base + '">\n',
  5017. ' <ns0:hasPart xmlns:ns0="http://docs.oasis-open.org/ns/office/1.2/meta/pkg#" rdf:resource="' + file + '"/>\n',
  5018. ' </rdf:Description>\n'
  5019. ].join("");
  5020. }
  5021. function write_rdf(rdf) {
  5022. var o = [XML_HEADER];
  5023. o.push('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n');
  5024. for(var i = 0; i != rdf.length; ++i) {
  5025. o.push(write_rdf_type(rdf[i][0], rdf[i][1]));
  5026. o.push(write_rdf_has("",rdf[i][0]));
  5027. }
  5028. o.push(write_rdf_type("","Document", "pkg"));
  5029. o.push('</rdf:RDF>');
  5030. return o.join("");
  5031. }
  5032. /* TODO: pull properties */
  5033. function write_meta_ods() {
  5034. return '<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="http://www.w3.org/1999/xlink" office:version="1.2"><office:meta><meta:generator>Sheet' + 'JS ' + XLSX.version + '</meta:generator></office:meta></office:document-meta>';
  5035. }
  5036. /* ECMA-376 Part II 11.1 Core Properties Part */
  5037. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  5038. var CORE_PROPS = [
  5039. ["cp:category", "Category"],
  5040. ["cp:contentStatus", "ContentStatus"],
  5041. ["cp:keywords", "Keywords"],
  5042. ["cp:lastModifiedBy", "LastAuthor"],
  5043. ["cp:lastPrinted", "LastPrinted"],
  5044. ["cp:revision", "RevNumber"],
  5045. ["cp:version", "Version"],
  5046. ["dc:creator", "Author"],
  5047. ["dc:description", "Comments"],
  5048. ["dc:identifier", "Identifier"],
  5049. ["dc:language", "Language"],
  5050. ["dc:subject", "Subject"],
  5051. ["dc:title", "Title"],
  5052. ["dcterms:created", "CreatedDate", 'date'],
  5053. ["dcterms:modified", "ModifiedDate", 'date']
  5054. ];
  5055. var CORE_PROPS_REGEX = (function() {
  5056. var r = new Array(CORE_PROPS.length);
  5057. for(var i = 0; i < CORE_PROPS.length; ++i) {
  5058. var f = CORE_PROPS[i];
  5059. var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
  5060. r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
  5061. }
  5062. return r;
  5063. })();
  5064. function parse_core_props(data) {
  5065. var p = {};
  5066. data = utf8read(data);
  5067. for(var i = 0; i < CORE_PROPS.length; ++i) {
  5068. var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
  5069. if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
  5070. if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
  5071. }
  5072. return p;
  5073. }
  5074. function cp_doit(f, g, h, o, p) {
  5075. if(p[f] != null || g == null || g === "") return;
  5076. p[f] = g;
  5077. g = escapexml(g);
  5078. o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
  5079. }
  5080. function write_core_props(cp, _opts) {
  5081. var opts = _opts || {};
  5082. var o = [XML_HEADER, writextag('cp:coreProperties', null, {
  5083. //'xmlns': XMLNS.CORE_PROPS,
  5084. 'xmlns:cp': XMLNS.CORE_PROPS,
  5085. 'xmlns:dc': XMLNS.dc,
  5086. 'xmlns:dcterms': XMLNS.dcterms,
  5087. 'xmlns:dcmitype': XMLNS.dcmitype,
  5088. 'xmlns:xsi': XMLNS.xsi
  5089. })], p = {};
  5090. if(!cp && !opts.Props) return o.join("");
  5091. if(cp) {
  5092. 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);
  5093. 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);
  5094. }
  5095. for(var i = 0; i != CORE_PROPS.length; ++i) {
  5096. var f = CORE_PROPS[i];
  5097. var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
  5098. if(v === true) v = "1";
  5099. else if(v === false) v = "0";
  5100. else if(typeof v == "number") v = String(v);
  5101. if(v != null) cp_doit(f[0], v, null, o, p);
  5102. }
  5103. if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
  5104. return o.join("");
  5105. }
  5106. /* 15.2.12.3 Extended File Properties Part */
  5107. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  5108. var EXT_PROPS = [
  5109. ["Application", "Application", "string"],
  5110. ["AppVersion", "AppVersion", "string"],
  5111. ["Company", "Company", "string"],
  5112. ["DocSecurity", "DocSecurity", "string"],
  5113. ["Manager", "Manager", "string"],
  5114. ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  5115. ["SharedDoc", "SharedDoc", "bool"],
  5116. ["LinksUpToDate", "LinksUpToDate", "bool"],
  5117. ["ScaleCrop", "ScaleCrop", "bool"],
  5118. ["HeadingPairs", "HeadingPairs", "raw"],
  5119. ["TitlesOfParts", "TitlesOfParts", "raw"]
  5120. ];
  5121. var PseudoPropsPairs = [
  5122. "Worksheets", "SheetNames",
  5123. "NamedRanges", "DefinedNames",
  5124. "Chartsheets", "ChartNames"
  5125. ];
  5126. function load_props_pairs(HP, TOP, props, opts) {
  5127. var v = [];
  5128. if(typeof HP == "string") v = parseVector(HP, opts);
  5129. else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
  5130. var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
  5131. var idx = 0, len = 0;
  5132. if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
  5133. len = +(v[i+1].v);
  5134. switch(v[i].v) {
  5135. case "Worksheets":
  5136. case "工作表":
  5137. case "Листы":
  5138. case "أوراق العمل":
  5139. case "ワークシート":
  5140. case "גליונות עבודה":
  5141. case "Arbeitsblätter":
  5142. case "Çalışma Sayfaları":
  5143. case "Feuilles de calcul":
  5144. case "Fogli di lavoro":
  5145. case "Folhas de cálculo":
  5146. case "Planilhas":
  5147. case "Regneark":
  5148. case "Hojas de cálculo":
  5149. case "Werkbladen":
  5150. props.Worksheets = len;
  5151. props.SheetNames = parts.slice(idx, idx + len);
  5152. break;
  5153. case "Named Ranges":
  5154. case "Rangos con nombre":
  5155. case "名前付き一覧":
  5156. case "Benannte Bereiche":
  5157. case "Navngivne områder":
  5158. props.NamedRanges = len;
  5159. props.DefinedNames = parts.slice(idx, idx + len);
  5160. break;
  5161. case "Charts":
  5162. case "Diagramme":
  5163. props.Chartsheets = len;
  5164. props.ChartNames = parts.slice(idx, idx + len);
  5165. break;
  5166. }
  5167. idx += len;
  5168. }
  5169. }
  5170. function parse_ext_props(data, p, opts) {
  5171. var q = {}; if(!p) p = {};
  5172. data = utf8read(data);
  5173. EXT_PROPS.forEach(function(f) {
  5174. var xml = (data.match(matchtag(f[0]))||[])[1];
  5175. switch(f[2]) {
  5176. case "string": if(xml) p[f[1]] = unescapexml(xml); break;
  5177. case "bool": p[f[1]] = xml === "true"; break;
  5178. case "raw":
  5179. var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
  5180. if(cur && cur.length > 0) q[f[1]] = cur[1];
  5181. break;
  5182. }
  5183. });
  5184. if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);
  5185. return p;
  5186. }
  5187. function write_ext_props(cp) {
  5188. var o = [], W = writextag;
  5189. if(!cp) cp = {};
  5190. cp.Application = "SheetJS";
  5191. o[o.length] = (XML_HEADER);
  5192. o[o.length] = (writextag('Properties', null, {
  5193. 'xmlns': XMLNS.EXT_PROPS,
  5194. 'xmlns:vt': XMLNS.vt
  5195. }));
  5196. EXT_PROPS.forEach(function(f) {
  5197. if(cp[f[1]] === undefined) return;
  5198. var v;
  5199. switch(f[2]) {
  5200. case 'string': v = escapexml(String(cp[f[1]])); break;
  5201. case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
  5202. }
  5203. if(v !== undefined) o[o.length] = (W(f[0], v));
  5204. });
  5205. /* TODO: HeadingPairs, TitlesOfParts */
  5206. 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"})));
  5207. 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"})));
  5208. if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
  5209. return o.join("");
  5210. }
  5211. /* 15.2.12.2 Custom File Properties Part */
  5212. var custregex = /<[^>]+>[^<]*/g;
  5213. function parse_cust_props(data, opts) {
  5214. var p = {}, name = "";
  5215. var m = data.match(custregex);
  5216. if(m) for(var i = 0; i != m.length; ++i) {
  5217. var x = m[i], y = parsexmltag(x);
  5218. switch(strip_ns(y[0])) {
  5219. case '<?xml': break;
  5220. case '<Properties': break;
  5221. case '<property': name = unescapexml(y.name); break;
  5222. case '</property>': name = null; break;
  5223. default: if (x.indexOf('<vt:') === 0) {
  5224. var toks = x.split('>');
  5225. var type = toks[0].slice(4), text = toks[1];
  5226. /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
  5227. switch(type) {
  5228. case 'lpstr': case 'bstr': case 'lpwstr':
  5229. p[name] = unescapexml(text);
  5230. break;
  5231. case 'bool':
  5232. p[name] = parsexmlbool(text);
  5233. break;
  5234. case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
  5235. p[name] = parseInt(text, 10);
  5236. break;
  5237. case 'r4': case 'r8': case 'decimal':
  5238. p[name] = parseFloat(text);
  5239. break;
  5240. case 'filetime': case 'date':
  5241. p[name] = parseDate(text);
  5242. break;
  5243. case 'cy': case 'error':
  5244. p[name] = unescapexml(text);
  5245. break;
  5246. default:
  5247. if(type.slice(-1) == '/') break;
  5248. if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
  5249. }
  5250. } else if(x.slice(0,2) === "</") {/* empty */
  5251. } else if(opts.WTF) throw new Error(x);
  5252. }
  5253. }
  5254. return p;
  5255. }
  5256. function write_cust_props(cp) {
  5257. var o = [XML_HEADER, writextag('Properties', null, {
  5258. 'xmlns': XMLNS.CUST_PROPS,
  5259. 'xmlns:vt': XMLNS.vt
  5260. })];
  5261. if(!cp) return o.join("");
  5262. var pid = 1;
  5263. keys(cp).forEach(function custprop(k) { ++pid;
  5264. o[o.length] = (writextag('property', write_vt(cp[k], true), {
  5265. 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
  5266. 'pid': pid,
  5267. 'name': escapexml(k)
  5268. }));
  5269. });
  5270. if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
  5271. return o.join("");
  5272. }
  5273. /* Common Name -> XLML Name */
  5274. var XLMLDocPropsMap = {
  5275. Title: 'Title',
  5276. Subject: 'Subject',
  5277. Author: 'Author',
  5278. Keywords: 'Keywords',
  5279. Comments: 'Description',
  5280. LastAuthor: 'LastAuthor',
  5281. RevNumber: 'Revision',
  5282. Application: 'AppName',
  5283. /* TotalTime: 'TotalTime', */
  5284. LastPrinted: 'LastPrinted',
  5285. CreatedDate: 'Created',
  5286. ModifiedDate: 'LastSaved',
  5287. /* Pages */
  5288. /* Words */
  5289. /* Characters */
  5290. Category: 'Category',
  5291. /* PresentationFormat */
  5292. Manager: 'Manager',
  5293. Company: 'Company',
  5294. /* Guid */
  5295. /* HyperlinkBase */
  5296. /* Bytes */
  5297. /* Lines */
  5298. /* Paragraphs */
  5299. /* CharactersWithSpaces */
  5300. AppVersion: 'Version',
  5301. ContentStatus: 'ContentStatus', /* NOTE: missing from schema */
  5302. Identifier: 'Identifier', /* NOTE: missing from schema */
  5303. Language: 'Language' /* NOTE: missing from schema */
  5304. };
  5305. var evert_XLMLDPM;
  5306. function xlml_set_prop(Props, tag, val) {
  5307. if(!evert_XLMLDPM) evert_XLMLDPM = evert(XLMLDocPropsMap);
  5308. tag = evert_XLMLDPM[tag] || tag;
  5309. Props[tag] = val;
  5310. }
  5311. function xlml_write_docprops(Props, opts) {
  5312. var o = [];
  5313. keys(XLMLDocPropsMap).map(function(m) {
  5314. for(var i = 0; i < CORE_PROPS.length; ++i) if(CORE_PROPS[i][1] == m) return CORE_PROPS[i];
  5315. for(i = 0; i < EXT_PROPS.length; ++i) if(EXT_PROPS[i][1] == m) return EXT_PROPS[i];
  5316. throw m;
  5317. }).forEach(function(p) {
  5318. if(Props[p[1]] == null) return;
  5319. var m = opts && opts.Props && opts.Props[p[1]] != null ? opts.Props[p[1]] : Props[p[1]];
  5320. switch(p[2]) {
  5321. case 'date': m = new Date(m).toISOString().replace(/\.\d*Z/,"Z"); break;
  5322. }
  5323. if(typeof m == 'number') m = String(m);
  5324. else if(m === true || m === false) { m = m ? "1" : "0"; }
  5325. else if(m instanceof Date) m = new Date(m).toISOString().replace(/\.\d*Z/,"");
  5326. o.push(writetag(XLMLDocPropsMap[p[1]] || p[1], m));
  5327. });
  5328. return writextag('DocumentProperties', o.join(""), {xmlns:XLMLNS.o });
  5329. }
  5330. function xlml_write_custprops(Props, Custprops) {
  5331. var BLACKLIST = ["Worksheets","SheetNames"];
  5332. var T = 'CustomDocumentProperties';
  5333. var o = [];
  5334. if(Props) keys(Props).forEach(function(k) {
  5335. if(!Object.prototype.hasOwnProperty.call(Props, k)) return;
  5336. for(var i = 0; i < CORE_PROPS.length; ++i) if(k == CORE_PROPS[i][1]) return;
  5337. for(i = 0; i < EXT_PROPS.length; ++i) if(k == EXT_PROPS[i][1]) return;
  5338. for(i = 0; i < BLACKLIST.length; ++i) if(k == BLACKLIST[i]) return;
  5339. var m = Props[k];
  5340. var t = "string";
  5341. if(typeof m == 'number') { t = "float"; m = String(m); }
  5342. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  5343. else m = String(m);
  5344. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  5345. });
  5346. if(Custprops) keys(Custprops).forEach(function(k) {
  5347. if(!Object.prototype.hasOwnProperty.call(Custprops, k)) return;
  5348. if(Props && Object.prototype.hasOwnProperty.call(Props, k)) return;
  5349. var m = Custprops[k];
  5350. var t = "string";
  5351. if(typeof m == 'number') { t = "float"; m = String(m); }
  5352. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  5353. else if(m instanceof Date) { t = "dateTime.tz"; m = m.toISOString(); }
  5354. else m = String(m);
  5355. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  5356. });
  5357. return '<' + T + ' xmlns="' + XLMLNS.o + '">' + o.join("") + '</' + T + '>';
  5358. }
  5359. /* [MS-DTYP] 2.3.3 FILETIME */
  5360. /* [MS-OLEDS] 2.1.3 FILETIME (Packet Version) */
  5361. /* [MS-OLEPS] 2.8 FILETIME (Packet Version) */
  5362. function parse_FILETIME(blob) {
  5363. var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
  5364. return new Date(((dwHighDateTime/1e7*Math.pow(2,32) + dwLowDateTime/1e7) - 11644473600)*1000).toISOString().replace(/\.000/,"");
  5365. }
  5366. function write_FILETIME(time) {
  5367. var date = (typeof time == "string") ? new Date(Date.parse(time)) : time;
  5368. var t = date.getTime() / 1000 + 11644473600;
  5369. var l = t % Math.pow(2,32), h = (t - l) / Math.pow(2,32);
  5370. l *= 1e7; h *= 1e7;
  5371. var w = (l / Math.pow(2,32)) | 0;
  5372. if(w > 0) { l = l % Math.pow(2,32); h += w; }
  5373. var o = new_buf(8); o.write_shift(4, l); o.write_shift(4, h); return o;
  5374. }
  5375. /* [MS-OSHARED] 2.3.3.1.4 Lpstr */
  5376. function parse_lpstr(blob, type, pad) {
  5377. var start = blob.l;
  5378. var str = blob.read_shift(0, 'lpstr-cp');
  5379. if(pad) while((blob.l - start) & 3) ++blob.l;
  5380. return str;
  5381. }
  5382. /* [MS-OSHARED] 2.3.3.1.6 Lpwstr */
  5383. function parse_lpwstr(blob, type, pad) {
  5384. var str = blob.read_shift(0, 'lpwstr');
  5385. if(pad) blob.l += (4 - ((str.length+1) & 3)) & 3;
  5386. return str;
  5387. }
  5388. /* [MS-OSHARED] 2.3.3.1.11 VtString */
  5389. /* [MS-OSHARED] 2.3.3.1.12 VtUnalignedString */
  5390. function parse_VtStringBase(blob, stringType, pad) {
  5391. if(stringType === 0x1F /*VT_LPWSTR*/) return parse_lpwstr(blob);
  5392. return parse_lpstr(blob, stringType, pad);
  5393. }
  5394. function parse_VtString(blob, t, pad) { return parse_VtStringBase(blob, t, pad === false ? 0: 4); }
  5395. function parse_VtUnalignedString(blob, t) { if(!t) throw new Error("VtUnalignedString must have positive length"); return parse_VtStringBase(blob, t, 0); }
  5396. /* [MS-OSHARED] 2.3.3.1.7 VtVecLpwstrValue */
  5397. function parse_VtVecLpwstrValue(blob) {
  5398. var length = blob.read_shift(4);
  5399. var ret = [];
  5400. for(var i = 0; i != length; ++i) {
  5401. var start = blob.l;
  5402. ret[i] = blob.read_shift(0, 'lpwstr').replace(chr0,'');
  5403. if((blob.l - start) & 0x02) blob.l += 2;
  5404. }
  5405. return ret;
  5406. }
  5407. /* [MS-OSHARED] 2.3.3.1.9 VtVecUnalignedLpstrValue */
  5408. function parse_VtVecUnalignedLpstrValue(blob) {
  5409. var length = blob.read_shift(4);
  5410. var ret = [];
  5411. for(var i = 0; i != length; ++i) ret[i] = blob.read_shift(0, 'lpstr-cp').replace(chr0,'');
  5412. return ret;
  5413. }
  5414. /* [MS-OSHARED] 2.3.3.1.13 VtHeadingPair */
  5415. function parse_VtHeadingPair(blob) {
  5416. var start = blob.l;
  5417. var headingString = parse_TypedPropertyValue(blob, VT_USTR);
  5418. if(blob[blob.l] == 0x00 && blob[blob.l+1] == 0x00 && ((blob.l - start) & 0x02)) blob.l += 2;
  5419. var headerParts = parse_TypedPropertyValue(blob, VT_I4);
  5420. return [headingString, headerParts];
  5421. }
  5422. /* [MS-OSHARED] 2.3.3.1.14 VtVecHeadingPairValue */
  5423. function parse_VtVecHeadingPairValue(blob) {
  5424. var cElements = blob.read_shift(4);
  5425. var out = [];
  5426. for(var i = 0; i < cElements / 2; ++i) out.push(parse_VtHeadingPair(blob));
  5427. return out;
  5428. }
  5429. /* [MS-OLEPS] 2.18.1 Dictionary (uses 2.17, 2.16) */
  5430. function parse_dictionary(blob,CodePage) {
  5431. var cnt = blob.read_shift(4);
  5432. var dict = ({});
  5433. for(var j = 0; j != cnt; ++j) {
  5434. var pid = blob.read_shift(4);
  5435. var len = blob.read_shift(4);
  5436. dict[pid] = blob.read_shift(len, (CodePage === 0x4B0 ?'utf16le':'utf8')).replace(chr0,'').replace(chr1,'!');
  5437. if(CodePage === 0x4B0 && (len % 2)) blob.l += 2;
  5438. }
  5439. if(blob.l & 3) blob.l = (blob.l>>2+1)<<2;
  5440. return dict;
  5441. }
  5442. /* [MS-OLEPS] 2.9 BLOB */
  5443. function parse_BLOB(blob) {
  5444. var size = blob.read_shift(4);
  5445. var bytes = blob.slice(blob.l,blob.l+size);
  5446. blob.l += size;
  5447. if((size & 3) > 0) blob.l += (4 - (size & 3)) & 3;
  5448. return bytes;
  5449. }
  5450. /* [MS-OLEPS] 2.11 ClipboardData */
  5451. function parse_ClipboardData(blob) {
  5452. // TODO
  5453. var o = {};
  5454. o.Size = blob.read_shift(4);
  5455. //o.Format = blob.read_shift(4);
  5456. blob.l += o.Size + 3 - (o.Size - 1) % 4;
  5457. return o;
  5458. }
  5459. /* [MS-OLEPS] 2.15 TypedPropertyValue */
  5460. function parse_TypedPropertyValue(blob, type, _opts) {
  5461. var t = blob.read_shift(2), ret, opts = _opts||{};
  5462. blob.l += 2;
  5463. if(type !== VT_VARIANT)
  5464. if(t !== type && VT_CUSTOM.indexOf(type)===-1 && !((type & 0xFFFE) == 0x101E && (t & 0xFFFE) == 0x101E)) throw new Error('Expected type ' + type + ' saw ' + t);
  5465. switch(type === VT_VARIANT ? t : type) {
  5466. case 0x02 /*VT_I2*/: ret = blob.read_shift(2, 'i'); if(!opts.raw) blob.l += 2; return ret;
  5467. case 0x03 /*VT_I4*/: ret = blob.read_shift(4, 'i'); return ret;
  5468. case 0x0B /*VT_BOOL*/: return blob.read_shift(4) !== 0x0;
  5469. case 0x13 /*VT_UI4*/: ret = blob.read_shift(4); return ret;
  5470. case 0x1E /*VT_LPSTR*/: return parse_lpstr(blob, t, 4).replace(chr0,'');
  5471. case 0x1F /*VT_LPWSTR*/: return parse_lpwstr(blob);
  5472. case 0x40 /*VT_FILETIME*/: return parse_FILETIME(blob);
  5473. case 0x41 /*VT_BLOB*/: return parse_BLOB(blob);
  5474. case 0x47 /*VT_CF*/: return parse_ClipboardData(blob);
  5475. case 0x50 /*VT_STRING*/: return parse_VtString(blob, t, !opts.raw).replace(chr0,'');
  5476. case 0x51 /*VT_USTR*/: return parse_VtUnalignedString(blob, t/*, 4*/).replace(chr0,'');
  5477. case 0x100C /*VT_VECTOR|VT_VARIANT*/: return parse_VtVecHeadingPairValue(blob);
  5478. case 0x101E /*VT_VECTOR|VT_LPSTR*/:
  5479. case 0x101F /*VT_VECTOR|VT_LPWSTR*/:
  5480. return t == 0x101F ? parse_VtVecLpwstrValue(blob) : parse_VtVecUnalignedLpstrValue(blob);
  5481. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + t);
  5482. }
  5483. }
  5484. function write_TypedPropertyValue(type, value) {
  5485. var o = new_buf(4), p = new_buf(4);
  5486. o.write_shift(4, type == 0x50 ? 0x1F : type);
  5487. switch(type) {
  5488. case 0x03 /*VT_I4*/: p.write_shift(-4, value); break;
  5489. case 0x05 /*VT_I4*/: p = new_buf(8); p.write_shift(8, value, 'f'); break;
  5490. case 0x0B /*VT_BOOL*/: p.write_shift(4, value ? 0x01 : 0x00); break;
  5491. case 0x40 /*VT_FILETIME*/: p = write_FILETIME(value); break;
  5492. case 0x1F /*VT_LPWSTR*/:
  5493. case 0x50 /*VT_STRING*/:
  5494. p = new_buf(4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  5495. p.write_shift(4, value.length + 1);
  5496. p.write_shift(0, value, "dbcs");
  5497. while(p.l != p.length) p.write_shift(1, 0);
  5498. break;
  5499. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + value);
  5500. }
  5501. return bconcat([o, p]);
  5502. }
  5503. /* [MS-OLEPS] 2.20 PropertySet */
  5504. function parse_PropertySet(blob, PIDSI) {
  5505. var start_addr = blob.l;
  5506. var size = blob.read_shift(4);
  5507. var NumProps = blob.read_shift(4);
  5508. var Props = [], i = 0;
  5509. var CodePage = 0;
  5510. var Dictionary = -1, DictObj = ({});
  5511. for(i = 0; i != NumProps; ++i) {
  5512. var PropID = blob.read_shift(4);
  5513. var Offset = blob.read_shift(4);
  5514. Props[i] = [PropID, Offset + start_addr];
  5515. }
  5516. Props.sort(function(x,y) { return x[1] - y[1]; });
  5517. var PropH = {};
  5518. for(i = 0; i != NumProps; ++i) {
  5519. if(blob.l !== Props[i][1]) {
  5520. var fail = true;
  5521. if(i>0 && PIDSI) switch(PIDSI[Props[i-1][0]].t) {
  5522. case 0x02 /*VT_I2*/: if(blob.l+2 === Props[i][1]) { blob.l+=2; fail = false; } break;
  5523. case 0x50 /*VT_STRING*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  5524. case 0x100C /*VT_VECTOR|VT_VARIANT*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  5525. }
  5526. if((!PIDSI||i==0) && blob.l <= Props[i][1]) { fail=false; blob.l = Props[i][1]; }
  5527. if(fail) throw new Error("Read Error: Expected address " + Props[i][1] + ' at ' + blob.l + ' :' + i);
  5528. }
  5529. if(PIDSI) {
  5530. if(Props[i][0] == 0 && Props.length > i+1 && Props[i][1] == Props[i+1][1]) continue; // R9
  5531. var piddsi = PIDSI[Props[i][0]];
  5532. PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, {raw:true});
  5533. if(piddsi.p === 'version') PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 0xFFFF)).slice(-4);
  5534. if(piddsi.n == "CodePage") switch(PropH[piddsi.n]) {
  5535. case 0: PropH[piddsi.n] = 1252;
  5536. /* falls through */
  5537. case 874:
  5538. case 932:
  5539. case 936:
  5540. case 949:
  5541. case 950:
  5542. case 1250:
  5543. case 1251:
  5544. case 1253:
  5545. case 1254:
  5546. case 1255:
  5547. case 1256:
  5548. case 1257:
  5549. case 1258:
  5550. case 10000:
  5551. case 1200:
  5552. case 1201:
  5553. case 1252:
  5554. case 65000: case -536:
  5555. case 65001: case -535:
  5556. set_cp(CodePage = (PropH[piddsi.n]>>>0) & 0xFFFF); break;
  5557. default: throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
  5558. }
  5559. } else {
  5560. if(Props[i][0] === 0x1) {
  5561. CodePage = PropH.CodePage = (parse_TypedPropertyValue(blob, VT_I2));
  5562. set_cp(CodePage);
  5563. if(Dictionary !== -1) {
  5564. var oldpos = blob.l;
  5565. blob.l = Props[Dictionary][1];
  5566. DictObj = parse_dictionary(blob,CodePage);
  5567. blob.l = oldpos;
  5568. }
  5569. } else if(Props[i][0] === 0) {
  5570. if(CodePage === 0) { Dictionary = i; blob.l = Props[i+1][1]; continue; }
  5571. DictObj = parse_dictionary(blob,CodePage);
  5572. } else {
  5573. var name = DictObj[Props[i][0]];
  5574. var val;
  5575. /* [MS-OSHARED] 2.3.3.2.3.1.2 + PROPVARIANT */
  5576. switch(blob[blob.l]) {
  5577. case 0x41 /*VT_BLOB*/: blob.l += 4; val = parse_BLOB(blob); break;
  5578. case 0x1E /*VT_LPSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  5579. case 0x1F /*VT_LPWSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  5580. case 0x03 /*VT_I4*/: blob.l += 4; val = blob.read_shift(4, 'i'); break;
  5581. case 0x13 /*VT_UI4*/: blob.l += 4; val = blob.read_shift(4); break;
  5582. case 0x05 /*VT_R8*/: blob.l += 4; val = blob.read_shift(8, 'f'); break;
  5583. case 0x0B /*VT_BOOL*/: blob.l += 4; val = parsebool(blob, 4); break;
  5584. case 0x40 /*VT_FILETIME*/: blob.l += 4; val = parseDate(parse_FILETIME(blob)); break;
  5585. default: throw new Error("unparsed value: " + blob[blob.l]);
  5586. }
  5587. PropH[name] = val;
  5588. }
  5589. }
  5590. }
  5591. blob.l = start_addr + size; /* step ahead to skip padding */
  5592. return PropH;
  5593. }
  5594. var XLSPSSkip = [ "CodePage", "Thumbnail", "_PID_LINKBASE", "_PID_HLINKS", "SystemIdentifier", "FMTID" ];
  5595. function guess_property_type(val) {
  5596. switch(typeof val) {
  5597. case "boolean": return 0x0B;
  5598. case "number": return ((val|0)==val) ? 0x03 : 0x05;
  5599. case "string": return 0x1F;
  5600. case "object": if(val instanceof Date) return 0x40; break;
  5601. }
  5602. return -1;
  5603. }
  5604. function write_PropertySet(entries, RE, PIDSI) {
  5605. var hdr = new_buf(8), piao = [], prop = [];
  5606. var sz = 8, i = 0;
  5607. var pr = new_buf(8), pio = new_buf(8);
  5608. pr.write_shift(4, 0x0002);
  5609. pr.write_shift(4, 0x04B0);
  5610. pio.write_shift(4, 0x0001);
  5611. prop.push(pr); piao.push(pio);
  5612. sz += 8 + pr.length;
  5613. if(!RE) {
  5614. pio = new_buf(8);
  5615. pio.write_shift(4, 0);
  5616. piao.unshift(pio);
  5617. var bufs = [new_buf(4)];
  5618. bufs[0].write_shift(4, entries.length);
  5619. for(i = 0; i < entries.length; ++i) {
  5620. var value = entries[i][0];
  5621. pr = new_buf(4 + 4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  5622. pr.write_shift(4, i+2);
  5623. pr.write_shift(4, value.length + 1);
  5624. pr.write_shift(0, value, "dbcs");
  5625. while(pr.l != pr.length) pr.write_shift(1, 0);
  5626. bufs.push(pr);
  5627. }
  5628. pr = bconcat(bufs);
  5629. prop.unshift(pr);
  5630. sz += 8 + pr.length;
  5631. }
  5632. for(i = 0; i < entries.length; ++i) {
  5633. if(RE && !RE[entries[i][0]]) continue;
  5634. if(XLSPSSkip.indexOf(entries[i][0]) > -1 || PseudoPropsPairs.indexOf(entries[i][0]) > -1) continue;
  5635. if(entries[i][1] == null) continue;
  5636. var val = entries[i][1], idx = 0;
  5637. if(RE) {
  5638. idx = +RE[entries[i][0]];
  5639. var pinfo = (PIDSI)[idx];
  5640. if(pinfo.p == "version" && typeof val == "string") {
  5641. var arr = val.split(".");
  5642. val = ((+arr[0])<<16) + ((+arr[1])||0);
  5643. }
  5644. pr = write_TypedPropertyValue(pinfo.t, val);
  5645. } else {
  5646. var T = guess_property_type(val);
  5647. if(T == -1) { T = 0x1F; val = String(val); }
  5648. pr = write_TypedPropertyValue(T, val);
  5649. }
  5650. prop.push(pr);
  5651. pio = new_buf(8);
  5652. pio.write_shift(4, !RE ? 2+i : idx);
  5653. piao.push(pio);
  5654. sz += 8 + pr.length;
  5655. }
  5656. var w = 8 * (prop.length + 1);
  5657. for(i = 0; i < prop.length; ++i) { piao[i].write_shift(4, w); w += prop[i].length; }
  5658. hdr.write_shift(4, sz);
  5659. hdr.write_shift(4, prop.length);
  5660. return bconcat([hdr].concat(piao).concat(prop));
  5661. }
  5662. /* [MS-OLEPS] 2.21 PropertySetStream */
  5663. function parse_PropertySetStream(file, PIDSI, clsid) {
  5664. var blob = file.content;
  5665. if(!blob) return ({});
  5666. prep_blob(blob, 0);
  5667. var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
  5668. blob.chk('feff', 'Byte Order: ');
  5669. /*var vers = */blob.read_shift(2); // TODO: check version
  5670. var SystemIdentifier = blob.read_shift(4);
  5671. var CLSID = blob.read_shift(16);
  5672. if(CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
  5673. NumSets = blob.read_shift(4);
  5674. if(NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
  5675. FMTID0 = blob.read_shift(16); Offset0 = blob.read_shift(4);
  5676. if(NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
  5677. else if(NumSets === 2) { FMTID1 = blob.read_shift(16); Offset1 = blob.read_shift(4); }
  5678. var PSet0 = parse_PropertySet(blob, PIDSI);
  5679. var rval = ({ SystemIdentifier: SystemIdentifier });
  5680. for(var y in PSet0) rval[y] = PSet0[y];
  5681. //rval.blob = blob;
  5682. rval.FMTID = FMTID0;
  5683. //rval.PSet0 = PSet0;
  5684. if(NumSets === 1) return rval;
  5685. if(Offset1 - blob.l == 2) blob.l += 2;
  5686. if(blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
  5687. var PSet1;
  5688. try { PSet1 = parse_PropertySet(blob, null); } catch(e) {/* empty */}
  5689. for(y in PSet1) rval[y] = PSet1[y];
  5690. rval.FMTID = [FMTID0, FMTID1]; // TODO: verify FMTID0/1
  5691. return rval;
  5692. }
  5693. function write_PropertySetStream(entries, clsid, RE, PIDSI, entries2, clsid2) {
  5694. var hdr = new_buf(entries2 ? 68 : 48);
  5695. var bufs = [hdr];
  5696. hdr.write_shift(2, 0xFFFE);
  5697. hdr.write_shift(2, 0x0000); /* TODO: type 1 props */
  5698. hdr.write_shift(4, 0x32363237);
  5699. hdr.write_shift(16, CFB.utils.consts.HEADER_CLSID, "hex");
  5700. hdr.write_shift(4, (entries2 ? 2 : 1));
  5701. hdr.write_shift(16, clsid, "hex");
  5702. hdr.write_shift(4, (entries2 ? 68 : 48));
  5703. var ps0 = write_PropertySet(entries, RE, PIDSI);
  5704. bufs.push(ps0);
  5705. if(entries2) {
  5706. var ps1 = write_PropertySet(entries2, null, null);
  5707. hdr.write_shift(16, clsid2, "hex");
  5708. hdr.write_shift(4, 68 + ps0.length);
  5709. bufs.push(ps1);
  5710. }
  5711. return bconcat(bufs);
  5712. }
  5713. function parsenoop2(blob, length) { blob.read_shift(length); return null; }
  5714. function writezeroes(n, o) { if(!o) o=new_buf(n); for(var j=0; j<n; ++j) o.write_shift(1, 0); return o; }
  5715. function parslurp(blob, length, cb) {
  5716. var arr = [], target = blob.l + length;
  5717. while(blob.l < target) arr.push(cb(blob, target - blob.l));
  5718. if(target !== blob.l) throw new Error("Slurp error");
  5719. return arr;
  5720. }
  5721. function parsebool(blob, length) { return blob.read_shift(length) === 0x1; }
  5722. function writebool(v, o) { if(!o) o=new_buf(2); o.write_shift(2, +!!v); return o; }
  5723. function parseuint16(blob) { return blob.read_shift(2, 'u'); }
  5724. function writeuint16(v, o) { if(!o) o=new_buf(2); o.write_shift(2, v); return o; }
  5725. function parseuint16a(blob, length) { return parslurp(blob,length,parseuint16);}
  5726. /* --- 2.5 Structures --- */
  5727. /* [MS-XLS] 2.5.10 Bes (boolean or error) */
  5728. function parse_Bes(blob) {
  5729. var v = blob.read_shift(1), t = blob.read_shift(1);
  5730. return t === 0x01 ? v : v === 0x01;
  5731. }
  5732. function write_Bes(v, t, o) {
  5733. if(!o) o = new_buf(2);
  5734. o.write_shift(1, ((t == 'e') ? +v : +!!v));
  5735. o.write_shift(1, ((t == 'e') ? 1 : 0));
  5736. return o;
  5737. }
  5738. /* [MS-XLS] 2.5.240 ShortXLUnicodeString */
  5739. function parse_ShortXLUnicodeString(blob, length, opts) {
  5740. var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
  5741. var encoding = 'sbcs-cont';
  5742. var cp = current_codepage;
  5743. if(opts && opts.biff >= 8) current_codepage = 1200;
  5744. if(!opts || opts.biff == 8 ) {
  5745. var fHighByte = blob.read_shift(1);
  5746. if(fHighByte) { encoding = 'dbcs-cont'; }
  5747. } else if(opts.biff == 12) {
  5748. encoding = 'wstr';
  5749. }
  5750. if(opts.biff >= 2 && opts.biff <= 5) encoding = 'cpstr';
  5751. var o = cch ? blob.read_shift(cch, encoding) : "";
  5752. current_codepage = cp;
  5753. return o;
  5754. }
  5755. /* 2.5.293 XLUnicodeRichExtendedString */
  5756. function parse_XLUnicodeRichExtendedString(blob) {
  5757. var cp = current_codepage;
  5758. current_codepage = 1200;
  5759. var cch = blob.read_shift(2), flags = blob.read_shift(1);
  5760. var /*fHighByte = flags & 0x1,*/ fExtSt = flags & 0x4, fRichSt = flags & 0x8;
  5761. var width = 1 + (flags & 0x1); // 0x0 -> utf8, 0x1 -> dbcs
  5762. var cRun = 0, cbExtRst;
  5763. var z = {};
  5764. if(fRichSt) cRun = blob.read_shift(2);
  5765. if(fExtSt) cbExtRst = blob.read_shift(4);
  5766. var encoding = width == 2 ? 'dbcs-cont' : 'sbcs-cont';
  5767. var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
  5768. if(fRichSt) blob.l += 4 * cRun; //TODO: parse this
  5769. if(fExtSt) blob.l += cbExtRst; //TODO: parse this
  5770. z.t = msg;
  5771. if(!fRichSt) { z.raw = "<t>" + z.t + "</t>"; z.r = z.t; }
  5772. current_codepage = cp;
  5773. return z;
  5774. }
  5775. function write_XLUnicodeRichExtendedString(xlstr) {
  5776. var str = (xlstr.t||""), nfmts = 1;
  5777. var hdr = new_buf(3 + (nfmts > 1 ? 2 : 0));
  5778. hdr.write_shift(2, str.length);
  5779. hdr.write_shift(1, (nfmts > 1 ? 0x08 : 0x00) | 0x01);
  5780. if(nfmts > 1) hdr.write_shift(2, nfmts);
  5781. var otext = new_buf(2 * str.length);
  5782. otext.write_shift(2 * str.length, str, 'utf16le');
  5783. var out = [hdr, otext];
  5784. return bconcat(out);
  5785. }
  5786. /* 2.5.296 XLUnicodeStringNoCch */
  5787. function parse_XLUnicodeStringNoCch(blob, cch, opts) {
  5788. var retval;
  5789. if(opts) {
  5790. if(opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, 'cpstr');
  5791. if(opts.biff >= 12) return blob.read_shift(cch, 'dbcs-cont');
  5792. }
  5793. var fHighByte = blob.read_shift(1);
  5794. if(fHighByte===0) { retval = blob.read_shift(cch, 'sbcs-cont'); }
  5795. else { retval = blob.read_shift(cch, 'dbcs-cont'); }
  5796. return retval;
  5797. }
  5798. /* 2.5.294 XLUnicodeString */
  5799. function parse_XLUnicodeString(blob, length, opts) {
  5800. var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  5801. if(cch === 0) { blob.l++; return ""; }
  5802. return parse_XLUnicodeStringNoCch(blob, cch, opts);
  5803. }
  5804. /* BIFF5 override */
  5805. function parse_XLUnicodeString2(blob, length, opts) {
  5806. if(opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
  5807. var cch = blob.read_shift(1);
  5808. if(cch === 0) { blob.l++; return ""; }
  5809. return blob.read_shift(cch, (opts.biff <= 4 || !blob.lens ) ? 'cpstr' : 'sbcs-cont');
  5810. }
  5811. /* TODO: BIFF5 and lower, codepage awareness */
  5812. function write_XLUnicodeString(str, opts, o) {
  5813. if(!o) o = new_buf(3 + 2 * str.length);
  5814. o.write_shift(2, str.length);
  5815. o.write_shift(1, 1);
  5816. o.write_shift(31, str, 'utf16le');
  5817. return o;
  5818. }
  5819. /* [MS-XLS] 2.5.61 ControlInfo */
  5820. function parse_ControlInfo(blob) {
  5821. var flags = blob.read_shift(1);
  5822. blob.l++;
  5823. var accel = blob.read_shift(2);
  5824. blob.l += 2;
  5825. return [flags, accel];
  5826. }
  5827. /* [MS-OSHARED] 2.3.7.6 URLMoniker TODO: flags */
  5828. function parse_URLMoniker(blob) {
  5829. var len = blob.read_shift(4), start = blob.l;
  5830. var extra = false;
  5831. if(len > 24) {
  5832. /* look ahead */
  5833. blob.l += len - 24;
  5834. if(blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
  5835. blob.l = start;
  5836. }
  5837. var url = blob.read_shift((extra?len-24:len)>>1, 'utf16le').replace(chr0,"");
  5838. if(extra) blob.l += 24;
  5839. return url;
  5840. }
  5841. /* [MS-OSHARED] 2.3.7.8 FileMoniker TODO: all fields */
  5842. function parse_FileMoniker(blob) {
  5843. var cAnti = blob.read_shift(2);
  5844. var preamble = ""; while(cAnti-- > 0) preamble += "../";
  5845. var ansiPath = blob.read_shift(0, 'lpstr-ansi');
  5846. blob.l += 2; //var endServer = blob.read_shift(2);
  5847. if(blob.read_shift(2) != 0xDEAD) throw new Error("Bad FileMoniker");
  5848. var sz = blob.read_shift(4);
  5849. if(sz === 0) return preamble + ansiPath.replace(/\\/g,"/");
  5850. var bytes = blob.read_shift(4);
  5851. if(blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
  5852. var unicodePath = blob.read_shift(bytes>>1, 'utf16le').replace(chr0,"");
  5853. return preamble + unicodePath;
  5854. }
  5855. /* [MS-OSHARED] 2.3.7.2 HyperlinkMoniker TODO: all the monikers */
  5856. function parse_HyperlinkMoniker(blob, length) {
  5857. var clsid = blob.read_shift(16); length -= 16;
  5858. switch(clsid) {
  5859. case "e0c9ea79f9bace118c8200aa004ba90b": return parse_URLMoniker(blob, length);
  5860. case "0303000000000000c000000000000046": return parse_FileMoniker(blob, length);
  5861. default: throw new Error("Unsupported Moniker " + clsid);
  5862. }
  5863. }
  5864. /* [MS-OSHARED] 2.3.7.9 HyperlinkString */
  5865. function parse_HyperlinkString(blob) {
  5866. var len = blob.read_shift(4);
  5867. var o = len > 0 ? blob.read_shift(len, 'utf16le').replace(chr0, "") : "";
  5868. return o;
  5869. }
  5870. function write_HyperlinkString(str, o) {
  5871. if(!o) o = new_buf(6 + str.length * 2);
  5872. o.write_shift(4, 1 + str.length);
  5873. for(var i = 0; i < str.length; ++i) o.write_shift(2, str.charCodeAt(i));
  5874. o.write_shift(2, 0);
  5875. return o;
  5876. }
  5877. /* [MS-OSHARED] 2.3.7.1 Hyperlink Object */
  5878. function parse_Hyperlink(blob, length) {
  5879. var end = blob.l + length;
  5880. var sVer = blob.read_shift(4);
  5881. if(sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
  5882. var flags = blob.read_shift(2);
  5883. blob.l += 2;
  5884. var displayName, targetFrameName, moniker, oleMoniker, Loc="", guid, fileTime;
  5885. if(flags & 0x0010) displayName = parse_HyperlinkString(blob, end - blob.l);
  5886. if(flags & 0x0080) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
  5887. if((flags & 0x0101) === 0x0101) moniker = parse_HyperlinkString(blob, end - blob.l);
  5888. if((flags & 0x0101) === 0x0001) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
  5889. if(flags & 0x0008) Loc = parse_HyperlinkString(blob, end - blob.l);
  5890. if(flags & 0x0020) guid = blob.read_shift(16);
  5891. if(flags & 0x0040) fileTime = parse_FILETIME(blob/*, 8*/);
  5892. blob.l = end;
  5893. var target = targetFrameName||moniker||oleMoniker||"";
  5894. if(target && Loc) target+="#"+Loc;
  5895. if(!target) target = "#" + Loc;
  5896. if((flags & 0x0002) && target.charAt(0) == "/" && target.charAt(1) != "/") target = "file://" + target;
  5897. var out = ({Target:target});
  5898. if(guid) out.guid = guid;
  5899. if(fileTime) out.time = fileTime;
  5900. if(displayName) out.Tooltip = displayName;
  5901. return out;
  5902. }
  5903. function write_Hyperlink(hl) {
  5904. var out = new_buf(512), i = 0;
  5905. var Target = hl.Target;
  5906. if(Target.slice(0,7) == "file://") Target = Target.slice(7);
  5907. var hashidx = Target.indexOf("#");
  5908. var F = hashidx > -1 ? 0x1f : 0x17;
  5909. switch(Target.charAt(0)) { case "#": F=0x1c; break; case ".": F&=~2; break; }
  5910. out.write_shift(4,2); out.write_shift(4, F);
  5911. var data = [8,6815827,6619237,4849780,83]; for(i = 0; i < data.length; ++i) out.write_shift(4, data[i]);
  5912. if(F == 0x1C) {
  5913. Target = Target.slice(1);
  5914. write_HyperlinkString(Target, out);
  5915. } else if(F & 0x02) {
  5916. data = "e0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  5917. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  5918. var Pretarget = hashidx > -1 ? Target.slice(0, hashidx) : Target;
  5919. out.write_shift(4, 2*(Pretarget.length + 1));
  5920. for(i = 0; i < Pretarget.length; ++i) out.write_shift(2, Pretarget.charCodeAt(i));
  5921. out.write_shift(2, 0);
  5922. if(F & 0x08) write_HyperlinkString(hashidx > -1 ? Target.slice(hashidx+1): "", out);
  5923. } else {
  5924. data = "03 03 00 00 00 00 00 00 c0 00 00 00 00 00 00 46".split(" ");
  5925. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  5926. var P = 0;
  5927. while(Target.slice(P*3,P*3+3)=="../"||Target.slice(P*3,P*3+3)=="..\\") ++P;
  5928. out.write_shift(2, P);
  5929. out.write_shift(4, Target.length - 3 * P + 1);
  5930. for(i = 0; i < Target.length - 3 * P; ++i) out.write_shift(1, Target.charCodeAt(i + 3 * P) & 0xFF);
  5931. out.write_shift(1, 0);
  5932. out.write_shift(2, 0xFFFF);
  5933. out.write_shift(2, 0xDEAD);
  5934. for(i = 0; i < 6; ++i) out.write_shift(4, 0);
  5935. }
  5936. return out.slice(0, out.l);
  5937. }
  5938. /* 2.5.178 LongRGBA */
  5939. function parse_LongRGBA(blob) { var r = blob.read_shift(1), g = blob.read_shift(1), b = blob.read_shift(1), a = blob.read_shift(1); return [r,g,b,a]; }
  5940. /* 2.5.177 LongRGB */
  5941. function parse_LongRGB(blob, length) { var x = parse_LongRGBA(blob, length); x[3] = 0; return x; }
  5942. /* [MS-XLS] 2.5.19 */
  5943. function parse_XLSCell(blob) {
  5944. var rw = blob.read_shift(2); // 0-indexed
  5945. var col = blob.read_shift(2);
  5946. var ixfe = blob.read_shift(2);
  5947. return ({r:rw, c:col, ixfe:ixfe});
  5948. }
  5949. function write_XLSCell(R, C, ixfe, o) {
  5950. if(!o) o = new_buf(6);
  5951. o.write_shift(2, R);
  5952. o.write_shift(2, C);
  5953. o.write_shift(2, ixfe||0);
  5954. return o;
  5955. }
  5956. /* [MS-XLS] 2.5.134 */
  5957. function parse_frtHeader(blob) {
  5958. var rt = blob.read_shift(2);
  5959. var flags = blob.read_shift(2); // TODO: parse these flags
  5960. blob.l += 8;
  5961. return {type: rt, flags: flags};
  5962. }
  5963. function parse_OptXLUnicodeString(blob, length, opts) { return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts); }
  5964. /* [MS-XLS] 2.5.344 */
  5965. function parse_XTI(blob, length, opts) {
  5966. var w = opts.biff > 8 ? 4 : 2;
  5967. var iSupBook = blob.read_shift(w), itabFirst = blob.read_shift(w,'i'), itabLast = blob.read_shift(w,'i');
  5968. return [iSupBook, itabFirst, itabLast];
  5969. }
  5970. /* [MS-XLS] 2.5.218 */
  5971. function parse_RkRec(blob) {
  5972. var ixfe = blob.read_shift(2);
  5973. var RK = parse_RkNumber(blob);
  5974. return [ixfe, RK];
  5975. }
  5976. /* [MS-XLS] 2.5.1 */
  5977. function parse_AddinUdf(blob, length, opts) {
  5978. blob.l += 4; length -= 4;
  5979. var l = blob.l + length;
  5980. var udfName = parse_ShortXLUnicodeString(blob, length, opts);
  5981. var cb = blob.read_shift(2);
  5982. l -= blob.l;
  5983. if(cb !== l) throw new Error("Malformed AddinUdf: padding = " + l + " != " + cb);
  5984. blob.l += cb;
  5985. return udfName;
  5986. }
  5987. /* [MS-XLS] 2.5.209 TODO: Check sizes */
  5988. function parse_Ref8U(blob) {
  5989. var rwFirst = blob.read_shift(2);
  5990. var rwLast = blob.read_shift(2);
  5991. var colFirst = blob.read_shift(2);
  5992. var colLast = blob.read_shift(2);
  5993. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  5994. }
  5995. function write_Ref8U(r, o) {
  5996. if(!o) o = new_buf(8);
  5997. o.write_shift(2, r.s.r);
  5998. o.write_shift(2, r.e.r);
  5999. o.write_shift(2, r.s.c);
  6000. o.write_shift(2, r.e.c);
  6001. return o;
  6002. }
  6003. /* [MS-XLS] 2.5.211 */
  6004. function parse_RefU(blob) {
  6005. var rwFirst = blob.read_shift(2);
  6006. var rwLast = blob.read_shift(2);
  6007. var colFirst = blob.read_shift(1);
  6008. var colLast = blob.read_shift(1);
  6009. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  6010. }
  6011. /* [MS-XLS] 2.5.207 */
  6012. var parse_Ref = parse_RefU;
  6013. /* [MS-XLS] 2.5.143 */
  6014. function parse_FtCmo(blob) {
  6015. blob.l += 4;
  6016. var ot = blob.read_shift(2);
  6017. var id = blob.read_shift(2);
  6018. var flags = blob.read_shift(2);
  6019. blob.l+=12;
  6020. return [id, ot, flags];
  6021. }
  6022. /* [MS-XLS] 2.5.149 */
  6023. function parse_FtNts(blob) {
  6024. var out = {};
  6025. blob.l += 4;
  6026. blob.l += 16; // GUID TODO
  6027. out.fSharedNote = blob.read_shift(2);
  6028. blob.l += 4;
  6029. return out;
  6030. }
  6031. /* [MS-XLS] 2.5.142 */
  6032. function parse_FtCf(blob) {
  6033. var out = {};
  6034. blob.l += 4;
  6035. blob.cf = blob.read_shift(2);
  6036. return out;
  6037. }
  6038. /* [MS-XLS] 2.5.140 - 2.5.154 and friends */
  6039. function parse_FtSkip(blob) { blob.l += 2; blob.l += blob.read_shift(2); }
  6040. var FtTab = {
  6041. 0x00: parse_FtSkip, /* FtEnd */
  6042. 0x04: parse_FtSkip, /* FtMacro */
  6043. 0x05: parse_FtSkip, /* FtButton */
  6044. 0x06: parse_FtSkip, /* FtGmo */
  6045. 0x07: parse_FtCf, /* FtCf */
  6046. 0x08: parse_FtSkip, /* FtPioGrbit */
  6047. 0x09: parse_FtSkip, /* FtPictFmla */
  6048. 0x0A: parse_FtSkip, /* FtCbls */
  6049. 0x0B: parse_FtSkip, /* FtRbo */
  6050. 0x0C: parse_FtSkip, /* FtSbs */
  6051. 0x0D: parse_FtNts, /* FtNts */
  6052. 0x0E: parse_FtSkip, /* FtSbsFmla */
  6053. 0x0F: parse_FtSkip, /* FtGboData */
  6054. 0x10: parse_FtSkip, /* FtEdoData */
  6055. 0x11: parse_FtSkip, /* FtRboData */
  6056. 0x12: parse_FtSkip, /* FtCblsData */
  6057. 0x13: parse_FtSkip, /* FtLbsData */
  6058. 0x14: parse_FtSkip, /* FtCblsFmla */
  6059. 0x15: parse_FtCmo
  6060. };
  6061. function parse_FtArray(blob, length) {
  6062. var tgt = blob.l + length;
  6063. var fts = [];
  6064. while(blob.l < tgt) {
  6065. var ft = blob.read_shift(2);
  6066. blob.l-=2;
  6067. try {
  6068. fts.push(FtTab[ft](blob, tgt - blob.l));
  6069. } catch(e) { blob.l = tgt; return fts; }
  6070. }
  6071. if(blob.l != tgt) blob.l = tgt; //throw new Error("bad Object Ft-sequence");
  6072. return fts;
  6073. }
  6074. /* --- 2.4 Records --- */
  6075. /* [MS-XLS] 2.4.21 */
  6076. function parse_BOF(blob, length) {
  6077. var o = {BIFFVer:0, dt:0};
  6078. o.BIFFVer = blob.read_shift(2); length -= 2;
  6079. if(length >= 2) { o.dt = blob.read_shift(2); blob.l -= 2; }
  6080. switch(o.BIFFVer) {
  6081. case 0x0600: /* BIFF8 */
  6082. case 0x0500: /* BIFF5 */
  6083. case 0x0400: /* BIFF4 */
  6084. case 0x0300: /* BIFF3 */
  6085. case 0x0200: /* BIFF2 */
  6086. case 0x0002: case 0x0007: /* BIFF2 */
  6087. break;
  6088. default: if(length > 6) throw new Error("Unexpected BIFF Ver " + o.BIFFVer);
  6089. }
  6090. blob.read_shift(length);
  6091. return o;
  6092. }
  6093. function write_BOF(wb, t, o) {
  6094. var h = 0x0600, w = 16;
  6095. switch(o.bookType) {
  6096. case 'biff8': break;
  6097. case 'biff5': h = 0x0500; w = 8; break;
  6098. case 'biff4': h = 0x0004; w = 6; break;
  6099. case 'biff3': h = 0x0003; w = 6; break;
  6100. case 'biff2': h = 0x0002; w = 4; break;
  6101. case 'xla': break;
  6102. default: throw new Error("unsupported BIFF version");
  6103. }
  6104. var out = new_buf(w);
  6105. out.write_shift(2, h);
  6106. out.write_shift(2, t);
  6107. if(w > 4) out.write_shift(2, 0x7262);
  6108. if(w > 6) out.write_shift(2, 0x07CD);
  6109. if(w > 8) {
  6110. out.write_shift(2, 0xC009);
  6111. out.write_shift(2, 0x0001);
  6112. out.write_shift(2, 0x0706);
  6113. out.write_shift(2, 0x0000);
  6114. }
  6115. return out;
  6116. }
  6117. /* [MS-XLS] 2.4.146 */
  6118. function parse_InterfaceHdr(blob, length) {
  6119. if(length === 0) return 0x04b0;
  6120. if((blob.read_shift(2))!==0x04b0){/* empty */}
  6121. return 0x04b0;
  6122. }
  6123. /* [MS-XLS] 2.4.349 */
  6124. function parse_WriteAccess(blob, length, opts) {
  6125. if(opts.enc) { blob.l += length; return ""; }
  6126. var l = blob.l;
  6127. // TODO: make sure XLUnicodeString doesnt overrun
  6128. var UserName = parse_XLUnicodeString2(blob, 0, opts);
  6129. blob.read_shift(length + l - blob.l);
  6130. return UserName;
  6131. }
  6132. function write_WriteAccess(s, opts) {
  6133. var b8 = !opts || opts.biff == 8;
  6134. var o = new_buf(b8 ? 112 : 54);
  6135. o.write_shift(opts.biff == 8 ? 2 : 1, 7);
  6136. if(b8) o.write_shift(1, 0);
  6137. o.write_shift(4, 0x33336853);
  6138. o.write_shift(4, (0x00534A74 | (b8 ? 0 : 0x20000000)));
  6139. while(o.l < o.length) o.write_shift(1, (b8 ? 0 : 32));
  6140. return o;
  6141. }
  6142. /* [MS-XLS] 2.4.351 */
  6143. function parse_WsBool(blob, length, opts) {
  6144. var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
  6145. return { fDialog: flags & 0x10, fBelow: flags & 0x40, fRight: flags & 0x80 };
  6146. }
  6147. /* [MS-XLS] 2.4.28 */
  6148. function parse_BoundSheet8(blob, length, opts) {
  6149. var pos = blob.read_shift(4);
  6150. var hidden = blob.read_shift(1) & 0x03;
  6151. var dt = blob.read_shift(1);
  6152. switch(dt) {
  6153. case 0: dt = 'Worksheet'; break;
  6154. case 1: dt = 'Macrosheet'; break;
  6155. case 2: dt = 'Chartsheet'; break;
  6156. case 6: dt = 'VBAModule'; break;
  6157. }
  6158. var name = parse_ShortXLUnicodeString(blob, 0, opts);
  6159. if(name.length === 0) name = "Sheet1";
  6160. return { pos:pos, hs:hidden, dt:dt, name:name };
  6161. }
  6162. function write_BoundSheet8(data, opts) {
  6163. var w = (!opts || opts.biff >= 8 ? 2 : 1);
  6164. var o = new_buf(8 + w * data.name.length);
  6165. o.write_shift(4, data.pos);
  6166. o.write_shift(1, data.hs || 0);
  6167. o.write_shift(1, data.dt);
  6168. o.write_shift(1, data.name.length);
  6169. if(opts.biff >= 8) o.write_shift(1, 1);
  6170. o.write_shift(w * data.name.length, data.name, opts.biff < 8 ? 'sbcs' : 'utf16le');
  6171. var out = o.slice(0, o.l);
  6172. out.l = o.l; return out;
  6173. }
  6174. /* [MS-XLS] 2.4.265 TODO */
  6175. function parse_SST(blob, length) {
  6176. var end = blob.l + length;
  6177. var cnt = blob.read_shift(4);
  6178. var ucnt = blob.read_shift(4);
  6179. var strs = ([]);
  6180. for(var i = 0; i != ucnt && blob.l < end; ++i) {
  6181. strs.push(parse_XLUnicodeRichExtendedString(blob));
  6182. }
  6183. strs.Count = cnt; strs.Unique = ucnt;
  6184. return strs;
  6185. }
  6186. function write_SST(sst, opts) {
  6187. var header = new_buf(8);
  6188. header.write_shift(4, sst.Count);
  6189. header.write_shift(4, sst.Unique);
  6190. var strs = [];
  6191. for(var j = 0; j < sst.length; ++j) strs[j] = write_XLUnicodeRichExtendedString(sst[j], opts);
  6192. var o = bconcat([header].concat(strs));
  6193. o.parts = [header.length].concat(strs.map(function(str) { return str.length; }));
  6194. return o;
  6195. }
  6196. /* [MS-XLS] 2.4.107 */
  6197. function parse_ExtSST(blob, length) {
  6198. var extsst = {};
  6199. extsst.dsst = blob.read_shift(2);
  6200. blob.l += length-2;
  6201. return extsst;
  6202. }
  6203. /* [MS-XLS] 2.4.221 TODO: check BIFF2-4 */
  6204. function parse_Row(blob) {
  6205. var z = ({});
  6206. z.r = blob.read_shift(2);
  6207. z.c = blob.read_shift(2);
  6208. z.cnt = blob.read_shift(2) - z.c;
  6209. var miyRw = blob.read_shift(2);
  6210. blob.l += 4; // reserved(2), unused(2)
  6211. var flags = blob.read_shift(1); // various flags
  6212. blob.l += 3; // reserved(8), ixfe(12), flags(4)
  6213. if(flags & 0x07) z.level = flags & 0x07;
  6214. // collapsed: flags & 0x10
  6215. if(flags & 0x20) z.hidden = true;
  6216. if(flags & 0x40) z.hpt = miyRw / 20;
  6217. return z;
  6218. }
  6219. /* [MS-XLS] 2.4.125 */
  6220. function parse_ForceFullCalculation(blob) {
  6221. var header = parse_frtHeader(blob);
  6222. if(header.type != 0x08A3) throw new Error("Invalid Future Record " + header.type);
  6223. var fullcalc = blob.read_shift(4);
  6224. return fullcalc !== 0x0;
  6225. }
  6226. /* [MS-XLS] 2.4.215 rt */
  6227. function parse_RecalcId(blob) {
  6228. blob.read_shift(2);
  6229. return blob.read_shift(4);
  6230. }
  6231. /* [MS-XLS] 2.4.87 */
  6232. function parse_DefaultRowHeight(blob, length, opts) {
  6233. var f = 0;
  6234. if(!(opts && opts.biff == 2)) {
  6235. f = blob.read_shift(2);
  6236. }
  6237. var miyRw = blob.read_shift(2);
  6238. if((opts && opts.biff == 2)) {
  6239. f = 1 - (miyRw >> 15); miyRw &= 0x7fff;
  6240. }
  6241. var fl = {Unsynced:f&1,DyZero:(f&2)>>1,ExAsc:(f&4)>>2,ExDsc:(f&8)>>3};
  6242. return [fl, miyRw];
  6243. }
  6244. /* [MS-XLS] 2.4.345 TODO */
  6245. function parse_Window1(blob) {
  6246. var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
  6247. var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
  6248. var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
  6249. return { Pos: [xWn, yWn], Dim: [dxWn, dyWn], Flags: flags, CurTab: iTabCur,
  6250. FirstTab: iTabFirst, Selected: ctabSel, TabRatio: wTabRatio };
  6251. }
  6252. function write_Window1() {
  6253. var o = new_buf(18);
  6254. o.write_shift(2, 0);
  6255. o.write_shift(2, 0);
  6256. o.write_shift(2, 0x7260);
  6257. o.write_shift(2, 0x44c0);
  6258. o.write_shift(2, 0x38);
  6259. o.write_shift(2, 0);
  6260. o.write_shift(2, 0);
  6261. o.write_shift(2, 1);
  6262. o.write_shift(2, 0x01f4);
  6263. return o;
  6264. }
  6265. /* [MS-XLS] 2.4.346 TODO */
  6266. function parse_Window2(blob, length, opts) {
  6267. if(opts && opts.biff >= 2 && opts.biff < 5) return {};
  6268. var f = blob.read_shift(2);
  6269. return { RTL: f & 0x40 };
  6270. }
  6271. function write_Window2(view) {
  6272. var o = new_buf(18), f = 0x6b6;
  6273. if(view && view.RTL) f |= 0x40;
  6274. o.write_shift(2, f);
  6275. o.write_shift(4, 0);
  6276. o.write_shift(4, 64);
  6277. o.write_shift(4, 0);
  6278. o.write_shift(4, 0);
  6279. return o;
  6280. }
  6281. /* [MS-XLS] 2.4.189 TODO */
  6282. function parse_Pane(/*blob, length, opts*/) {
  6283. }
  6284. /* [MS-XLS] 2.4.122 TODO */
  6285. function parse_Font(blob, length, opts) {
  6286. var o = {
  6287. dyHeight: blob.read_shift(2),
  6288. fl: blob.read_shift(2)
  6289. };
  6290. switch((opts && opts.biff) || 8) {
  6291. case 2: break;
  6292. case 3: case 4: blob.l += 2; break;
  6293. default: blob.l += 10; break;
  6294. }
  6295. o.name = parse_ShortXLUnicodeString(blob, 0, opts);
  6296. return o;
  6297. }
  6298. function write_Font(data, opts) {
  6299. var name = data.name || "Arial";
  6300. var b5 = (opts && (opts.biff == 5)), w = (b5 ? (15 + name.length) : (16 + 2 * name.length));
  6301. var o = new_buf(w);
  6302. o.write_shift(2, (data.sz || 12) * 20);
  6303. o.write_shift(4, 0);
  6304. o.write_shift(2, 400);
  6305. o.write_shift(4, 0);
  6306. o.write_shift(2, 0);
  6307. o.write_shift(1, name.length);
  6308. if(!b5) o.write_shift(1, 1);
  6309. o.write_shift((b5 ? 1 : 2) * name.length, name, (b5 ? "sbcs" : "utf16le"));
  6310. return o;
  6311. }
  6312. /* [MS-XLS] 2.4.149 */
  6313. function parse_LabelSst(blob) {
  6314. var cell = parse_XLSCell(blob);
  6315. cell.isst = blob.read_shift(4);
  6316. return cell;
  6317. }
  6318. function write_LabelSst(R, C, v, os ) {
  6319. var o = new_buf(10);
  6320. write_XLSCell(R, C, os, o);
  6321. o.write_shift(4, v);
  6322. return o;
  6323. }
  6324. /* [MS-XLS] 2.4.148 */
  6325. function parse_Label(blob, length, opts) {
  6326. if(opts.biffguess && opts.biff == 2) opts.biff = 5;
  6327. var target = blob.l + length;
  6328. var cell = parse_XLSCell(blob, 6);
  6329. if(opts.biff == 2) blob.l++;
  6330. var str = parse_XLUnicodeString(blob, target - blob.l, opts);
  6331. cell.val = str;
  6332. return cell;
  6333. }
  6334. function write_Label(R, C, v, os, opts) {
  6335. var b8 = !opts || opts.biff == 8;
  6336. var o = new_buf(6 + 2 + (+b8) + (1 + b8) * v.length);
  6337. write_XLSCell(R, C, os, o);
  6338. o.write_shift(2, v.length);
  6339. if(b8) o.write_shift(1, 1);
  6340. o.write_shift((1 + b8) * v.length, v, b8 ? 'utf16le' : 'sbcs');
  6341. return o;
  6342. }
  6343. /* [MS-XLS] 2.4.126 Number Formats */
  6344. function parse_Format(blob, length, opts) {
  6345. var numFmtId = blob.read_shift(2);
  6346. var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
  6347. return [numFmtId, fmtstr];
  6348. }
  6349. function write_Format(i, f, opts, o) {
  6350. var b5 = (opts && (opts.biff == 5));
  6351. if(!o) o = new_buf(b5 ? (3 + f.length) : (5 + 2 * f.length));
  6352. o.write_shift(2, i);
  6353. o.write_shift((b5 ? 1 : 2), f.length);
  6354. if(!b5) o.write_shift(1, 1);
  6355. o.write_shift((b5 ? 1 : 2) * f.length, f, (b5 ? 'sbcs' : 'utf16le'));
  6356. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  6357. if(out.l == null) out.l = out.length;
  6358. return out;
  6359. }
  6360. var parse_BIFF2Format = parse_XLUnicodeString2;
  6361. /* [MS-XLS] 2.4.90 */
  6362. function parse_Dimensions(blob, length, opts) {
  6363. var end = blob.l + length;
  6364. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  6365. var r = blob.read_shift(w), R = blob.read_shift(w);
  6366. var c = blob.read_shift(2), C = blob.read_shift(2);
  6367. blob.l = end;
  6368. return {s: {r:r, c:c}, e: {r:R, c:C}};
  6369. }
  6370. function write_Dimensions(range, opts) {
  6371. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  6372. var o = new_buf(2*w + 6);
  6373. o.write_shift(w, range.s.r);
  6374. o.write_shift(w, range.e.r + 1);
  6375. o.write_shift(2, range.s.c);
  6376. o.write_shift(2, range.e.c + 1);
  6377. o.write_shift(2, 0);
  6378. return o;
  6379. }
  6380. /* [MS-XLS] 2.4.220 */
  6381. function parse_RK(blob) {
  6382. var rw = blob.read_shift(2), col = blob.read_shift(2);
  6383. var rkrec = parse_RkRec(blob);
  6384. return {r:rw, c:col, ixfe:rkrec[0], rknum:rkrec[1]};
  6385. }
  6386. /* [MS-XLS] 2.4.175 */
  6387. function parse_MulRk(blob, length) {
  6388. var target = blob.l + length - 2;
  6389. var rw = blob.read_shift(2), col = blob.read_shift(2);
  6390. var rkrecs = [];
  6391. while(blob.l < target) rkrecs.push(parse_RkRec(blob));
  6392. if(blob.l !== target) throw new Error("MulRK read error");
  6393. var lastcol = blob.read_shift(2);
  6394. if(rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
  6395. return {r:rw, c:col, C:lastcol, rkrec:rkrecs};
  6396. }
  6397. /* [MS-XLS] 2.4.174 */
  6398. function parse_MulBlank(blob, length) {
  6399. var target = blob.l + length - 2;
  6400. var rw = blob.read_shift(2), col = blob.read_shift(2);
  6401. var ixfes = [];
  6402. while(blob.l < target) ixfes.push(blob.read_shift(2));
  6403. if(blob.l !== target) throw new Error("MulBlank read error");
  6404. var lastcol = blob.read_shift(2);
  6405. if(ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
  6406. return {r:rw, c:col, C:lastcol, ixfe:ixfes};
  6407. }
  6408. /* [MS-XLS] 2.5.20 2.5.249 TODO: interpret values here */
  6409. function parse_CellStyleXF(blob, length, style, opts) {
  6410. var o = {};
  6411. var a = blob.read_shift(4), b = blob.read_shift(4);
  6412. var c = blob.read_shift(4), d = blob.read_shift(2);
  6413. o.patternType = XLSFillPattern[c >> 26];
  6414. if(!opts.cellStyles) return o;
  6415. o.alc = a & 0x07;
  6416. o.fWrap = (a >> 3) & 0x01;
  6417. o.alcV = (a >> 4) & 0x07;
  6418. o.fJustLast = (a >> 7) & 0x01;
  6419. o.trot = (a >> 8) & 0xFF;
  6420. o.cIndent = (a >> 16) & 0x0F;
  6421. o.fShrinkToFit = (a >> 20) & 0x01;
  6422. o.iReadOrder = (a >> 22) & 0x02;
  6423. o.fAtrNum = (a >> 26) & 0x01;
  6424. o.fAtrFnt = (a >> 27) & 0x01;
  6425. o.fAtrAlc = (a >> 28) & 0x01;
  6426. o.fAtrBdr = (a >> 29) & 0x01;
  6427. o.fAtrPat = (a >> 30) & 0x01;
  6428. o.fAtrProt = (a >> 31) & 0x01;
  6429. o.dgLeft = b & 0x0F;
  6430. o.dgRight = (b >> 4) & 0x0F;
  6431. o.dgTop = (b >> 8) & 0x0F;
  6432. o.dgBottom = (b >> 12) & 0x0F;
  6433. o.icvLeft = (b >> 16) & 0x7F;
  6434. o.icvRight = (b >> 23) & 0x7F;
  6435. o.grbitDiag = (b >> 30) & 0x03;
  6436. o.icvTop = c & 0x7F;
  6437. o.icvBottom = (c >> 7) & 0x7F;
  6438. o.icvDiag = (c >> 14) & 0x7F;
  6439. o.dgDiag = (c >> 21) & 0x0F;
  6440. o.icvFore = d & 0x7F;
  6441. o.icvBack = (d >> 7) & 0x7F;
  6442. o.fsxButton = (d >> 14) & 0x01;
  6443. return o;
  6444. }
  6445. //function parse_CellXF(blob, length, opts) {return parse_CellStyleXF(blob,length,0, opts);}
  6446. //function parse_StyleXF(blob, length, opts) {return parse_CellStyleXF(blob,length,1, opts);}
  6447. /* [MS-XLS] 2.4.353 TODO: actually do this right */
  6448. function parse_XF(blob, length, opts) {
  6449. var o = {};
  6450. o.ifnt = blob.read_shift(2); o.numFmtId = blob.read_shift(2); o.flags = blob.read_shift(2);
  6451. o.fStyle = (o.flags >> 2) & 0x01;
  6452. length -= 6;
  6453. o.data = parse_CellStyleXF(blob, length, o.fStyle, opts);
  6454. return o;
  6455. }
  6456. function write_XF(data, ixfeP, opts, o) {
  6457. var b5 = (opts && (opts.biff == 5));
  6458. if(!o) o = new_buf(b5 ? 16 : 20);
  6459. o.write_shift(2, 0);
  6460. if(data.style) {
  6461. o.write_shift(2, (data.numFmtId||0));
  6462. o.write_shift(2, 0xFFF4);
  6463. } else {
  6464. o.write_shift(2, (data.numFmtId||0));
  6465. o.write_shift(2, (ixfeP<<4));
  6466. }
  6467. var f = 0;
  6468. if(data.numFmtId > 0 && b5) f |= 0x0400;
  6469. o.write_shift(4, f);
  6470. o.write_shift(4, 0);
  6471. if(!b5) o.write_shift(4, 0);
  6472. o.write_shift(2, 0);
  6473. return o;
  6474. }
  6475. /* [MS-XLS] 2.4.134 */
  6476. function parse_Guts(blob) {
  6477. blob.l += 4;
  6478. var out = [blob.read_shift(2), blob.read_shift(2)];
  6479. if(out[0] !== 0) out[0]--;
  6480. if(out[1] !== 0) out[1]--;
  6481. if(out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
  6482. return out;
  6483. }
  6484. function write_Guts(guts) {
  6485. var o = new_buf(8);
  6486. o.write_shift(4, 0);
  6487. o.write_shift(2, guts[0] ? guts[0] + 1 : 0);
  6488. o.write_shift(2, guts[1] ? guts[1] + 1 : 0);
  6489. return o;
  6490. }
  6491. /* [MS-XLS] 2.4.24 */
  6492. function parse_BoolErr(blob, length, opts) {
  6493. var cell = parse_XLSCell(blob, 6);
  6494. if(opts.biff == 2 || length == 9) ++blob.l;
  6495. var val = parse_Bes(blob, 2);
  6496. cell.val = val;
  6497. cell.t = (val === true || val === false) ? 'b' : 'e';
  6498. return cell;
  6499. }
  6500. function write_BoolErr(R, C, v, os, opts, t) {
  6501. var o = new_buf(8);
  6502. write_XLSCell(R, C, os, o);
  6503. write_Bes(v, t, o);
  6504. return o;
  6505. }
  6506. /* [MS-XLS] 2.4.180 Number */
  6507. function parse_Number(blob, length, opts) {
  6508. if(opts.biffguess && opts.biff == 2) opts.biff = 5;
  6509. var cell = parse_XLSCell(blob, 6);
  6510. var xnum = parse_Xnum(blob, 8);
  6511. cell.val = xnum;
  6512. return cell;
  6513. }
  6514. function write_Number(R, C, v, os) {
  6515. var o = new_buf(14);
  6516. write_XLSCell(R, C, os, o);
  6517. write_Xnum(v, o);
  6518. return o;
  6519. }
  6520. var parse_XLHeaderFooter = parse_OptXLUnicodeString; // TODO: parse 2.4.136
  6521. /* [MS-XLS] 2.4.271 */
  6522. function parse_SupBook(blob, length, opts) {
  6523. var end = blob.l + length;
  6524. var ctab = blob.read_shift(2);
  6525. var cch = blob.read_shift(2);
  6526. opts.sbcch = cch;
  6527. if(cch == 0x0401 || cch == 0x3A01) return [cch, ctab];
  6528. if(cch < 0x01 || cch >0xff) throw new Error("Unexpected SupBook type: "+cch);
  6529. var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
  6530. /* TODO: 2.5.277 Virtual Path */
  6531. var rgst = [];
  6532. while(end > blob.l) rgst.push(parse_XLUnicodeString(blob));
  6533. return [cch, ctab, virtPath, rgst];
  6534. }
  6535. /* [MS-XLS] 2.4.105 TODO */
  6536. function parse_ExternName(blob, length, opts) {
  6537. var flags = blob.read_shift(2);
  6538. var body;
  6539. var o = ({
  6540. fBuiltIn: flags & 0x01,
  6541. fWantAdvise: (flags >>> 1) & 0x01,
  6542. fWantPict: (flags >>> 2) & 0x01,
  6543. fOle: (flags >>> 3) & 0x01,
  6544. fOleLink: (flags >>> 4) & 0x01,
  6545. cf: (flags >>> 5) & 0x3FF,
  6546. fIcon: flags >>> 15 & 0x01
  6547. });
  6548. if(opts.sbcch === 0x3A01) body = parse_AddinUdf(blob, length-2, opts);
  6549. //else throw new Error("unsupported SupBook cch: " + opts.sbcch);
  6550. o.body = body || blob.read_shift(length-2);
  6551. if(typeof body === "string") o.Name = body;
  6552. return o;
  6553. }
  6554. /* [MS-XLS] 2.4.150 TODO */
  6555. function parse_Lbl(blob, length, opts) {
  6556. var target = blob.l + length;
  6557. var flags = blob.read_shift(2);
  6558. var chKey = blob.read_shift(1);
  6559. var cch = blob.read_shift(1);
  6560. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  6561. var itab = 0;
  6562. if(!opts || opts.biff >= 5) {
  6563. if(opts.biff != 5) blob.l += 2;
  6564. itab = blob.read_shift(2);
  6565. if(opts.biff == 5) blob.l += 2;
  6566. blob.l += 4;
  6567. }
  6568. var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
  6569. if(flags & 0x20) name = XLSLblBuiltIn[name.charCodeAt(0)];
  6570. var npflen = target - blob.l; if(opts && opts.biff == 2) --npflen;
  6571. /*jshint -W018 */
  6572. var rgce = (target == blob.l || cce === 0 || !(npflen > 0)) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
  6573. /*jshint +W018 */
  6574. return {
  6575. chKey: chKey,
  6576. Name: name,
  6577. itab: itab,
  6578. rgce: rgce
  6579. };
  6580. }
  6581. /* [MS-XLS] 2.4.106 TODO: verify filename encoding */
  6582. function parse_ExternSheet(blob, length, opts) {
  6583. if(opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
  6584. var o = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
  6585. while(len-- !== 0) o.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
  6586. // [iSupBook, itabFirst, itabLast];
  6587. if(blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
  6588. return o;
  6589. }
  6590. function parse_BIFF5ExternSheet(blob, length, opts) {
  6591. if(blob[blob.l + 1] == 0x03) blob[blob.l]++;
  6592. var o = parse_ShortXLUnicodeString(blob, length, opts);
  6593. return o.charCodeAt(0) == 0x03 ? o.slice(1) : o;
  6594. }
  6595. /* [MS-XLS] 2.4.176 TODO: check older biff */
  6596. function parse_NameCmt(blob, length, opts) {
  6597. if(opts.biff < 8) { blob.l += length; return; }
  6598. var cchName = blob.read_shift(2);
  6599. var cchComment = blob.read_shift(2);
  6600. var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
  6601. var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
  6602. return [name, comment];
  6603. }
  6604. /* [MS-XLS] 2.4.260 */
  6605. function parse_ShrFmla(blob, length, opts) {
  6606. var ref = parse_RefU(blob, 6);
  6607. blob.l++;
  6608. var cUse = blob.read_shift(1);
  6609. length -= 8;
  6610. return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
  6611. }
  6612. /* [MS-XLS] 2.4.4 TODO */
  6613. function parse_Array(blob, length, opts) {
  6614. var ref = parse_Ref(blob, 6);
  6615. /* TODO: fAlwaysCalc */
  6616. switch(opts.biff) {
  6617. case 2: blob.l ++; length -= 7; break;
  6618. case 3: case 4: blob.l += 2; length -= 8; break;
  6619. default: blob.l += 6; length -= 12;
  6620. }
  6621. return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
  6622. }
  6623. /* [MS-XLS] 2.4.173 */
  6624. function parse_MTRSettings(blob) {
  6625. var fMTREnabled = blob.read_shift(4) !== 0x00;
  6626. var fUserSetThreadCount = blob.read_shift(4) !== 0x00;
  6627. var cUserThreadCount = blob.read_shift(4);
  6628. return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
  6629. }
  6630. /* [MS-XLS] 2.5.186 TODO: BIFF5 */
  6631. function parse_NoteSh(blob, length, opts) {
  6632. if(opts.biff < 8) return;
  6633. var row = blob.read_shift(2), col = blob.read_shift(2);
  6634. var flags = blob.read_shift(2), idObj = blob.read_shift(2);
  6635. var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
  6636. if(opts.biff < 8) blob.read_shift(1);
  6637. return [{r:row,c:col}, stAuthor, idObj, flags];
  6638. }
  6639. /* [MS-XLS] 2.4.179 */
  6640. function parse_Note(blob, length, opts) {
  6641. /* TODO: Support revisions */
  6642. return parse_NoteSh(blob, length, opts);
  6643. }
  6644. /* [MS-XLS] 2.4.168 */
  6645. function parse_MergeCells(blob, length) {
  6646. var merges = [];
  6647. var cmcs = blob.read_shift(2);
  6648. while (cmcs--) merges.push(parse_Ref8U(blob,length));
  6649. return merges;
  6650. }
  6651. function write_MergeCells(merges) {
  6652. var o = new_buf(2 + merges.length * 8);
  6653. o.write_shift(2, merges.length);
  6654. for(var i = 0; i < merges.length; ++i) write_Ref8U(merges[i], o);
  6655. return o;
  6656. }
  6657. /* [MS-XLS] 2.4.181 TODO: parse all the things! */
  6658. function parse_Obj(blob, length, opts) {
  6659. if(opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
  6660. var cmo = parse_FtCmo(blob, 22); // id, ot, flags
  6661. var fts = parse_FtArray(blob, length-22, cmo[1]);
  6662. return { cmo: cmo, ft:fts };
  6663. }
  6664. /* from older spec */
  6665. var parse_BIFF5OT = {
  6666. 0x08: function(blob, length) {
  6667. var tgt = blob.l + length;
  6668. blob.l += 10; // todo
  6669. var cf = blob.read_shift(2);
  6670. blob.l += 4;
  6671. blob.l += 2; //var cbPictFmla = blob.read_shift(2);
  6672. blob.l += 2;
  6673. blob.l += 2; //var grbit = blob.read_shift(2);
  6674. blob.l += 4;
  6675. var cchName = blob.read_shift(1);
  6676. blob.l += cchName; // TODO: stName
  6677. blob.l = tgt; // TODO: fmla
  6678. return { fmt:cf };
  6679. }
  6680. };
  6681. function parse_BIFF5Obj(blob, length, opts) {
  6682. blob.l += 4; //var cnt = blob.read_shift(4);
  6683. var ot = blob.read_shift(2);
  6684. var id = blob.read_shift(2);
  6685. var grbit = blob.read_shift(2);
  6686. blob.l += 2; //var colL = blob.read_shift(2);
  6687. blob.l += 2; //var dxL = blob.read_shift(2);
  6688. blob.l += 2; //var rwT = blob.read_shift(2);
  6689. blob.l += 2; //var dyT = blob.read_shift(2);
  6690. blob.l += 2; //var colR = blob.read_shift(2);
  6691. blob.l += 2; //var dxR = blob.read_shift(2);
  6692. blob.l += 2; //var rwB = blob.read_shift(2);
  6693. blob.l += 2; //var dyB = blob.read_shift(2);
  6694. blob.l += 2; //var cbMacro = blob.read_shift(2);
  6695. blob.l += 6;
  6696. length -= 36;
  6697. var fts = [];
  6698. fts.push((parse_BIFF5OT[ot]||parsenoop)(blob, length, opts));
  6699. return { cmo: [id, ot, grbit], ft:fts };
  6700. }
  6701. /* [MS-XLS] 2.4.329 TODO: parse properly */
  6702. function parse_TxO(blob, length, opts) {
  6703. var s = blob.l;
  6704. var texts = "";
  6705. try {
  6706. blob.l += 4;
  6707. var ot = (opts.lastobj||{cmo:[0,0]}).cmo[1];
  6708. var controlInfo; // eslint-disable-line no-unused-vars
  6709. if([0,5,7,11,12,14].indexOf(ot) == -1) blob.l += 6;
  6710. else controlInfo = parse_ControlInfo(blob, 6, opts); // eslint-disable-line no-unused-vars
  6711. var cchText = blob.read_shift(2);
  6712. /*var cbRuns = */blob.read_shift(2);
  6713. /*var ifntEmpty = */parseuint16(blob, 2);
  6714. var len = blob.read_shift(2);
  6715. blob.l += len;
  6716. //var fmla = parse_ObjFmla(blob, s + length - blob.l);
  6717. for(var i = 1; i < blob.lens.length-1; ++i) {
  6718. if(blob.l-s != blob.lens[i]) throw new Error("TxO: bad continue record");
  6719. var hdr = blob[blob.l];
  6720. var t = parse_XLUnicodeStringNoCch(blob, blob.lens[i+1]-blob.lens[i]-1);
  6721. texts += t;
  6722. if(texts.length >= (hdr ? cchText : 2*cchText)) break;
  6723. }
  6724. if(texts.length !== cchText && texts.length !== cchText*2) {
  6725. throw new Error("cchText: " + cchText + " != " + texts.length);
  6726. }
  6727. blob.l = s + length;
  6728. /* [MS-XLS] 2.5.272 TxORuns */
  6729. // var rgTxoRuns = [];
  6730. // for(var j = 0; j != cbRuns/8-1; ++j) blob.l += 8;
  6731. // var cchText2 = blob.read_shift(2);
  6732. // if(cchText2 !== cchText) throw new Error("TxOLastRun mismatch: " + cchText2 + " " + cchText);
  6733. // blob.l += 6;
  6734. // if(s + length != blob.l) throw new Error("TxO " + (s + length) + ", at " + blob.l);
  6735. return { t: texts };
  6736. } catch(e) { blob.l = s + length; return { t: texts }; }
  6737. }
  6738. /* [MS-XLS] 2.4.140 */
  6739. function parse_HLink(blob, length) {
  6740. var ref = parse_Ref8U(blob, 8);
  6741. blob.l += 16; /* CLSID */
  6742. var hlink = parse_Hyperlink(blob, length-24);
  6743. return [ref, hlink];
  6744. }
  6745. function write_HLink(hl) {
  6746. var O = new_buf(24);
  6747. var ref = decode_cell(hl[0]);
  6748. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  6749. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  6750. var clsid = "d0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  6751. for(var i = 0; i < 16; ++i) O.write_shift(1, parseInt(clsid[i], 16));
  6752. return bconcat([O, write_Hyperlink(hl[1])]);
  6753. }
  6754. /* [MS-XLS] 2.4.141 */
  6755. function parse_HLinkTooltip(blob, length) {
  6756. blob.read_shift(2);
  6757. var ref = parse_Ref8U(blob, 8);
  6758. var wzTooltip = blob.read_shift((length-10)/2, 'dbcs-cont');
  6759. wzTooltip = wzTooltip.replace(chr0,"");
  6760. return [ref, wzTooltip];
  6761. }
  6762. function write_HLinkTooltip(hl) {
  6763. var TT = hl[1].Tooltip;
  6764. var O = new_buf(10 + 2 * (TT.length + 1));
  6765. O.write_shift(2, 0x0800);
  6766. var ref = decode_cell(hl[0]);
  6767. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  6768. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  6769. for(var i = 0; i < TT.length; ++i) O.write_shift(2, TT.charCodeAt(i));
  6770. O.write_shift(2, 0);
  6771. return O;
  6772. }
  6773. /* [MS-XLS] 2.4.63 */
  6774. function parse_Country(blob) {
  6775. var o = [0,0], d;
  6776. d = blob.read_shift(2); o[0] = CountryEnum[d] || d;
  6777. d = blob.read_shift(2); o[1] = CountryEnum[d] || d;
  6778. return o;
  6779. }
  6780. function write_Country(o) {
  6781. if(!o) o = new_buf(4);
  6782. o.write_shift(2, 0x01);
  6783. o.write_shift(2, 0x01);
  6784. return o;
  6785. }
  6786. /* [MS-XLS] 2.4.50 ClrtClient */
  6787. function parse_ClrtClient(blob) {
  6788. var ccv = blob.read_shift(2);
  6789. var o = [];
  6790. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  6791. return o;
  6792. }
  6793. /* [MS-XLS] 2.4.188 */
  6794. function parse_Palette(blob) {
  6795. var ccv = blob.read_shift(2);
  6796. var o = [];
  6797. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  6798. return o;
  6799. }
  6800. /* [MS-XLS] 2.4.354 */
  6801. function parse_XFCRC(blob) {
  6802. blob.l += 2;
  6803. var o = {cxfs:0, crc:0};
  6804. o.cxfs = blob.read_shift(2);
  6805. o.crc = blob.read_shift(4);
  6806. return o;
  6807. }
  6808. /* [MS-XLS] 2.4.53 TODO: parse flags */
  6809. /* [MS-XLSB] 2.4.323 TODO: parse flags */
  6810. function parse_ColInfo(blob, length, opts) {
  6811. if(!opts.cellStyles) return parsenoop(blob, length);
  6812. var w = opts && opts.biff >= 12 ? 4 : 2;
  6813. var colFirst = blob.read_shift(w);
  6814. var colLast = blob.read_shift(w);
  6815. var coldx = blob.read_shift(w);
  6816. var ixfe = blob.read_shift(w);
  6817. var flags = blob.read_shift(2);
  6818. if(w == 2) blob.l += 2;
  6819. var o = ({s:colFirst, e:colLast, w:coldx, ixfe:ixfe, flags:flags});
  6820. if(opts.biff >= 5 || !opts.biff) o.level = (flags >> 8) & 0x7;
  6821. return o;
  6822. }
  6823. function write_ColInfo(col, idx) {
  6824. var o = new_buf(12);
  6825. o.write_shift(2, idx);
  6826. o.write_shift(2, idx);
  6827. o.write_shift(2, col.width * 256);
  6828. o.write_shift(2, 0);
  6829. var f = 0;
  6830. if(col.hidden) f |= 1;
  6831. o.write_shift(1, f);
  6832. f = col.level || 0;
  6833. o.write_shift(1, f);
  6834. o.write_shift(2, 0);
  6835. return o;
  6836. }
  6837. /* [MS-XLS] 2.4.257 */
  6838. function parse_Setup(blob, length) {
  6839. var o = {};
  6840. if(length < 32) return o;
  6841. blob.l += 16;
  6842. o.header = parse_Xnum(blob, 8);
  6843. o.footer = parse_Xnum(blob, 8);
  6844. blob.l += 2;
  6845. return o;
  6846. }
  6847. /* [MS-XLS] 2.4.261 */
  6848. function parse_ShtProps(blob, length, opts) {
  6849. var def = {area:false};
  6850. if(opts.biff != 5) { blob.l += length; return def; }
  6851. var d = blob.read_shift(1); blob.l += 3;
  6852. if((d & 0x10)) def.area = true;
  6853. return def;
  6854. }
  6855. /* [MS-XLS] 2.4.241 */
  6856. function write_RRTabId(n) {
  6857. var out = new_buf(2 * n);
  6858. for(var i = 0; i < n; ++i) out.write_shift(2, i+1);
  6859. return out;
  6860. }
  6861. var parse_Blank = parse_XLSCell; /* [MS-XLS] 2.4.20 Just the cell */
  6862. var parse_Scl = parseuint16a; /* [MS-XLS] 2.4.247 num, den */
  6863. var parse_String = parse_XLUnicodeString; /* [MS-XLS] 2.4.268 */
  6864. /* --- Specific to versions before BIFF8 --- */
  6865. function parse_ImData(blob) {
  6866. var cf = blob.read_shift(2);
  6867. var env = blob.read_shift(2);
  6868. var lcb = blob.read_shift(4);
  6869. var o = {fmt:cf, env:env, len:lcb, data:blob.slice(blob.l,blob.l+lcb)};
  6870. blob.l += lcb;
  6871. return o;
  6872. }
  6873. /* BIFF2_??? where ??? is the name from [XLS] */
  6874. function parse_BIFF2STR(blob, length, opts) {
  6875. if(opts.biffguess && opts.biff == 5) opts.biff = 2;
  6876. var cell = parse_XLSCell(blob, 6);
  6877. ++blob.l;
  6878. var str = parse_XLUnicodeString2(blob, length-7, opts);
  6879. cell.t = 'str';
  6880. cell.val = str;
  6881. return cell;
  6882. }
  6883. function parse_BIFF2NUM(blob) {
  6884. var cell = parse_XLSCell(blob, 6);
  6885. ++blob.l;
  6886. var num = parse_Xnum(blob, 8);
  6887. cell.t = 'n';
  6888. cell.val = num;
  6889. return cell;
  6890. }
  6891. function write_BIFF2NUM(r, c, val) {
  6892. var out = new_buf(15);
  6893. write_BIFF2Cell(out, r, c);
  6894. out.write_shift(8, val, 'f');
  6895. return out;
  6896. }
  6897. function parse_BIFF2INT(blob) {
  6898. var cell = parse_XLSCell(blob, 6);
  6899. ++blob.l;
  6900. var num = blob.read_shift(2);
  6901. cell.t = 'n';
  6902. cell.val = num;
  6903. return cell;
  6904. }
  6905. function write_BIFF2INT(r, c, val) {
  6906. var out = new_buf(9);
  6907. write_BIFF2Cell(out, r, c);
  6908. out.write_shift(2, val);
  6909. return out;
  6910. }
  6911. function parse_BIFF2STRING(blob) {
  6912. var cch = blob.read_shift(1);
  6913. if(cch === 0) { blob.l++; return ""; }
  6914. return blob.read_shift(cch, 'sbcs-cont');
  6915. }
  6916. /* TODO: convert to BIFF8 font struct */
  6917. function parse_BIFF2FONTXTRA(blob, length) {
  6918. blob.l += 6; // unknown
  6919. blob.l += 2; // font weight "bls"
  6920. blob.l += 1; // charset
  6921. blob.l += 3; // unknown
  6922. blob.l += 1; // font family
  6923. blob.l += length - 13;
  6924. }
  6925. /* TODO: parse rich text runs */
  6926. function parse_RString(blob, length, opts) {
  6927. var end = blob.l + length;
  6928. var cell = parse_XLSCell(blob, 6);
  6929. var cch = blob.read_shift(2);
  6930. var str = parse_XLUnicodeStringNoCch(blob, cch, opts);
  6931. blob.l = end;
  6932. cell.t = 'str';
  6933. cell.val = str;
  6934. return cell;
  6935. }
  6936. var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
  6937. var DBF = (function() {
  6938. var dbf_codepage_map = {
  6939. /* Code Pages Supported by Visual FoxPro */
  6940. 0x01: 437, 0x02: 850,
  6941. 0x03: 1252, 0x04: 10000,
  6942. 0x64: 852, 0x65: 866,
  6943. 0x66: 865, 0x67: 861,
  6944. 0x68: 895, 0x69: 620,
  6945. 0x6A: 737, 0x6B: 857,
  6946. 0x78: 950, 0x79: 949,
  6947. 0x7A: 936, 0x7B: 932,
  6948. 0x7C: 874, 0x7D: 1255,
  6949. 0x7E: 1256, 0x96: 10007,
  6950. 0x97: 10029, 0x98: 10006,
  6951. 0xC8: 1250, 0xC9: 1251,
  6952. 0xCA: 1254, 0xCB: 1253,
  6953. /* shapefile DBF extension */
  6954. 0x00: 20127, 0x08: 865,
  6955. 0x09: 437, 0x0A: 850,
  6956. 0x0B: 437, 0x0D: 437,
  6957. 0x0E: 850, 0x0F: 437,
  6958. 0x10: 850, 0x11: 437,
  6959. 0x12: 850, 0x13: 932,
  6960. 0x14: 850, 0x15: 437,
  6961. 0x16: 850, 0x17: 865,
  6962. 0x18: 437, 0x19: 437,
  6963. 0x1A: 850, 0x1B: 437,
  6964. 0x1C: 863, 0x1D: 850,
  6965. 0x1F: 852, 0x22: 852,
  6966. 0x23: 852, 0x24: 860,
  6967. 0x25: 850, 0x26: 866,
  6968. 0x37: 850, 0x40: 852,
  6969. 0x4D: 936, 0x4E: 949,
  6970. 0x4F: 950, 0x50: 874,
  6971. 0x57: 1252, 0x58: 1252,
  6972. 0x59: 1252, 0x6C: 863,
  6973. 0x86: 737, 0x87: 852,
  6974. 0x88: 857, 0xCC: 1257,
  6975. 0xFF: 16969
  6976. };
  6977. var dbf_reverse_map = evert({
  6978. 0x01: 437, 0x02: 850,
  6979. 0x03: 1252, 0x04: 10000,
  6980. 0x64: 852, 0x65: 866,
  6981. 0x66: 865, 0x67: 861,
  6982. 0x68: 895, 0x69: 620,
  6983. 0x6A: 737, 0x6B: 857,
  6984. 0x78: 950, 0x79: 949,
  6985. 0x7A: 936, 0x7B: 932,
  6986. 0x7C: 874, 0x7D: 1255,
  6987. 0x7E: 1256, 0x96: 10007,
  6988. 0x97: 10029, 0x98: 10006,
  6989. 0xC8: 1250, 0xC9: 1251,
  6990. 0xCA: 1254, 0xCB: 1253,
  6991. 0x00: 20127
  6992. });
  6993. /* TODO: find an actual specification */
  6994. function dbf_to_aoa(buf, opts) {
  6995. var out = [];
  6996. var d = (new_raw_buf(1));
  6997. switch(opts.type) {
  6998. case 'base64': d = s2a(Base64_decode(buf)); break;
  6999. case 'binary': d = s2a(buf); break;
  7000. case 'buffer':
  7001. case 'array': d = buf; break;
  7002. }
  7003. prep_blob(d, 0);
  7004. /* header */
  7005. var ft = d.read_shift(1);
  7006. var memo = !!(ft & 0x88);
  7007. var vfp = false, l7 = false;
  7008. switch(ft) {
  7009. case 0x02: break; // dBASE II
  7010. case 0x03: break; // dBASE III
  7011. case 0x30: vfp = true; memo = true; break; // VFP
  7012. case 0x31: vfp = true; memo = true; break; // VFP with autoincrement
  7013. // 0x43 dBASE IV SQL table files
  7014. // 0x63 dBASE IV SQL system files
  7015. case 0x83: break; // dBASE III with memo
  7016. case 0x8B: break; // dBASE IV with memo
  7017. case 0x8C: l7 = true; break; // dBASE Level 7 with memo
  7018. // case 0xCB dBASE IV SQL table files with memo
  7019. case 0xF5: break; // FoxPro 2.x with memo
  7020. // case 0xFB FoxBASE
  7021. default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
  7022. }
  7023. var nrow = 0, fpos = 0x0209;
  7024. if(ft == 0x02) nrow = d.read_shift(2);
  7025. d.l += 3; // dBASE II stores DDMMYY date, others use YYMMDD
  7026. if(ft != 0x02) nrow = d.read_shift(4);
  7027. if(nrow > 1048576) nrow = 1e6;
  7028. if(ft != 0x02) fpos = d.read_shift(2); // header length
  7029. var rlen = d.read_shift(2); // record length
  7030. var /*flags = 0,*/ current_cp = opts.codepage || 1252;
  7031. if(ft != 0x02) { // 20 reserved bytes
  7032. d.l+=16;
  7033. /*flags = */d.read_shift(1);
  7034. //if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));
  7035. /* codepage present in FoxPro and dBASE Level 7 */
  7036. if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
  7037. d.l+=1;
  7038. d.l+=2;
  7039. }
  7040. if(l7) d.l += 36; // Level 7: 32 byte "Language driver name", 4 byte reserved
  7041. var fields = [], field = ({});
  7042. var hend = Math.min(d.length, (ft == 0x02 ? 0x209 : (fpos - 10 - (vfp ? 264 : 0))));
  7043. var ww = l7 ? 32 : 11;
  7044. while(d.l < hend && d[d.l] != 0x0d) {
  7045. field = ({});
  7046. field.name = (typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)) : a2s(d.slice(d.l, d.l + ww))).replace(/[\u0000\r\n].*$/g,"");
  7047. d.l += ww;
  7048. field.type = String.fromCharCode(d.read_shift(1));
  7049. if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
  7050. field.len = d.read_shift(1);
  7051. if(ft == 0x02) field.offset = d.read_shift(2);
  7052. field.dec = d.read_shift(1);
  7053. if(field.name.length) fields.push(field);
  7054. if(ft != 0x02) d.l += l7 ? 13 : 14;
  7055. switch(field.type) {
  7056. case 'B': // Double (VFP) / Binary (dBASE L7)
  7057. if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  7058. break;
  7059. case 'G': // General (FoxPro and dBASE L7)
  7060. case 'P': // Picture (FoxPro and dBASE L7)
  7061. if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  7062. break;
  7063. case '+': // Autoincrement (dBASE L7 only)
  7064. case '0': // _NullFlags (VFP only)
  7065. case '@': // Timestamp (dBASE L7 only)
  7066. case 'C': // Character (dBASE II)
  7067. case 'D': // Date (dBASE III)
  7068. case 'F': // Float (dBASE IV)
  7069. case 'I': // Long (VFP and dBASE L7)
  7070. case 'L': // Logical (dBASE II)
  7071. case 'M': // Memo (dBASE III)
  7072. case 'N': // Number (dBASE II)
  7073. case 'O': // Double (dBASE L7 only)
  7074. case 'T': // Datetime (VFP only)
  7075. case 'Y': // Currency (VFP only)
  7076. break;
  7077. default: throw new Error('Unknown Field Type: ' + field.type);
  7078. }
  7079. }
  7080. if(d[d.l] !== 0x0D) d.l = fpos-1;
  7081. if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
  7082. d.l = fpos;
  7083. /* data */
  7084. var R = 0, C = 0;
  7085. out[0] = [];
  7086. for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
  7087. while(nrow-- > 0) {
  7088. if(d[d.l] === 0x2A) {
  7089. // TODO: record marked as deleted -- create a hidden row?
  7090. d.l+=rlen;
  7091. continue;
  7092. }
  7093. ++d.l;
  7094. out[++R] = []; C = 0;
  7095. for(C = 0; C != fields.length; ++C) {
  7096. var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
  7097. prep_blob(dd, 0);
  7098. var s = typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, dd) : a2s(dd);
  7099. switch(fields[C].type) {
  7100. case 'C':
  7101. // NOTE: it is conventional to write ' / / ' for empty dates
  7102. if(s.trim().length) out[R][C] = s.replace(/\s+$/,"");
  7103. break;
  7104. case 'D':
  7105. if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
  7106. else out[R][C] = s;
  7107. break;
  7108. case 'F': out[R][C] = parseFloat(s.trim()); break;
  7109. case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
  7110. case 'L': switch(s.trim().toUpperCase()) {
  7111. case 'Y': case 'T': out[R][C] = true; break;
  7112. case 'N': case 'F': out[R][C] = false; break;
  7113. case '': case '?': break;
  7114. default: throw new Error("DBF Unrecognized L:|" + s + "|");
  7115. } break;
  7116. case 'M': /* TODO: handle memo files */
  7117. if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
  7118. out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
  7119. break;
  7120. case 'N':
  7121. s = s.replace(/\u0000/g,"").trim();
  7122. // NOTE: dBASE II interprets " . " as 0
  7123. if(s && s != ".") out[R][C] = +s || 0; break;
  7124. case '@':
  7125. // NOTE: dBASE specs appear to be incorrect
  7126. out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400);
  7127. break;
  7128. case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
  7129. case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4 + (dd.read_shift(4, 'i')/1e4)*Math.pow(2,32); break;
  7130. case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
  7131. case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
  7132. /* falls through */
  7133. case 'G': case 'P': dd.l += fields[C].len; break;
  7134. case '0':
  7135. if(fields[C].name === '_NullFlags') break;
  7136. /* falls through */
  7137. default: throw new Error("DBF Unsupported data type " + fields[C].type);
  7138. }
  7139. }
  7140. }
  7141. 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));
  7142. if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
  7143. opts.DBF = fields;
  7144. return out;
  7145. }
  7146. function dbf_to_sheet(buf, opts) {
  7147. var o = opts || {};
  7148. if(!o.dateNF) o.dateNF = "yyyymmdd";
  7149. var ws = aoa_to_sheet(dbf_to_aoa(buf, o), o);
  7150. ws["!cols"] = o.DBF.map(function(field) { return {
  7151. wch: field.len,
  7152. DBF: field
  7153. };});
  7154. delete o.DBF;
  7155. return ws;
  7156. }
  7157. function dbf_to_workbook(buf, opts) {
  7158. try {
  7159. var o = sheet_to_workbook(dbf_to_sheet(buf, opts), opts);
  7160. o.bookType = "dbf";
  7161. return o;
  7162. } catch(e) { if(opts && opts.WTF) throw e; }
  7163. return ({SheetNames:[],Sheets:{}});
  7164. }
  7165. var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
  7166. function sheet_to_dbf(ws, opts) {
  7167. var o = opts || {};
  7168. var old_cp = current_codepage;
  7169. if(+o.codepage >= 0) set_cp(+o.codepage);
  7170. if(o.type == "string") throw new Error("Cannot write DBF to JS string");
  7171. var ba = buf_array();
  7172. var aoa = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
  7173. var headers = aoa[0], data = aoa.slice(1), cols = ws["!cols"] || [];
  7174. var i = 0, j = 0, hcnt = 0, rlen = 1;
  7175. for(i = 0; i < headers.length; ++i) {
  7176. if(((cols[i]||{}).DBF||{}).name) { headers[i] = cols[i].DBF.name; ++hcnt; continue; }
  7177. if(headers[i] == null) continue;
  7178. ++hcnt;
  7179. if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
  7180. if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
  7181. if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
  7182. if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
  7183. }
  7184. var range = safe_decode_range(ws['!ref']);
  7185. var coltypes = [];
  7186. var colwidths = [];
  7187. var coldecimals = [];
  7188. for(i = 0; i <= range.e.c - range.s.c; ++i) {
  7189. var guess = '', _guess = '', maxlen = 0;
  7190. var col = [];
  7191. for(j=0; j < data.length; ++j) {
  7192. if(data[j][i] != null) col.push(data[j][i]);
  7193. }
  7194. if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
  7195. for(j = 0; j < col.length; ++j) {
  7196. switch(typeof col[j]) {
  7197. /* TODO: check if L2 compat is desired */
  7198. case 'number': _guess = 'B'; break;
  7199. case 'string': _guess = 'C'; break;
  7200. case 'boolean': _guess = 'L'; break;
  7201. case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
  7202. default: _guess = 'C';
  7203. }
  7204. /* TODO: cache the values instead of encoding twice */
  7205. maxlen = Math.max(maxlen, (typeof $cptable !== "undefined" && typeof col[j] == "string" ? $cptable.utils.encode(current_ansi, col[j]): String(col[j])).length);
  7206. guess = guess && guess != _guess ? 'C' : _guess;
  7207. //if(guess == 'C') break;
  7208. }
  7209. if(maxlen > 250) maxlen = 250;
  7210. _guess = ((cols[i]||{}).DBF||{}).type;
  7211. /* TODO: more fine grained control over DBF type resolution */
  7212. if(_guess == 'C') {
  7213. if(cols[i].DBF.len > maxlen) maxlen = cols[i].DBF.len;
  7214. }
  7215. if(guess == 'B' && _guess == 'N') {
  7216. guess = 'N';
  7217. coldecimals[i] = cols[i].DBF.dec;
  7218. maxlen = cols[i].DBF.len;
  7219. }
  7220. colwidths[i] = guess == 'C' || _guess == 'N' ? maxlen : (_RLEN[guess] || 0);
  7221. rlen += colwidths[i];
  7222. coltypes[i] = guess;
  7223. }
  7224. var h = ba.next(32);
  7225. h.write_shift(4, 0x13021130);
  7226. h.write_shift(4, data.length);
  7227. h.write_shift(2, 296 + 32 * hcnt);
  7228. h.write_shift(2, rlen);
  7229. for(i=0; i < 4; ++i) h.write_shift(4, 0);
  7230. var cp = +dbf_reverse_map[current_codepage] || 0x03;
  7231. h.write_shift(4, 0x00000000 | (cp<<8));
  7232. if(dbf_codepage_map[cp] != +o.codepage) {
  7233. if(o.codepage) console.error("DBF Unsupported codepage " + current_codepage + ", using 1252");
  7234. current_codepage = 1252;
  7235. }
  7236. for(i = 0, j = 0; i < headers.length; ++i) {
  7237. if(headers[i] == null) continue;
  7238. var hf = ba.next(32);
  7239. /* TODO: test how applications handle non-ASCII field names */
  7240. var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
  7241. hf.write_shift(1, _f, "sbcs");
  7242. hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
  7243. hf.write_shift(4, j);
  7244. hf.write_shift(1, colwidths[i] || _RLEN[coltypes[i]] || 0);
  7245. hf.write_shift(1, coldecimals[i] || 0);
  7246. hf.write_shift(1, 0x02);
  7247. hf.write_shift(4, 0);
  7248. hf.write_shift(1, 0);
  7249. hf.write_shift(4, 0);
  7250. hf.write_shift(4, 0);
  7251. j += (colwidths[i] || _RLEN[coltypes[i]] || 0);
  7252. }
  7253. var hb = ba.next(264);
  7254. hb.write_shift(4, 0x0000000D);
  7255. for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
  7256. for(i=0; i < data.length; ++i) {
  7257. var rout = ba.next(rlen);
  7258. rout.write_shift(1, 0);
  7259. for(j=0; j<headers.length; ++j) {
  7260. if(headers[j] == null) continue;
  7261. switch(coltypes[j]) {
  7262. case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
  7263. case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
  7264. case 'N':
  7265. var _n = "0";
  7266. if(typeof data[i][j] == "number") _n = data[i][j].toFixed(coldecimals[j]||0);
  7267. for(hcnt=0; hcnt < colwidths[j]-_n.length; ++hcnt) rout.write_shift(1, 0x20);
  7268. rout.write_shift(1, _n, "sbcs");
  7269. break;
  7270. case 'D':
  7271. if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
  7272. else {
  7273. rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
  7274. rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
  7275. rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
  7276. } break;
  7277. case 'C':
  7278. var _l = rout.l;
  7279. var _s = String(data[i][j] != null ? data[i][j] : "").slice(0, colwidths[j]);
  7280. rout.write_shift(1, _s, "cpstr");
  7281. _l += colwidths[j] - rout.l;
  7282. for(hcnt=0; hcnt < _l; ++hcnt) rout.write_shift(1, 0x20); break;
  7283. }
  7284. }
  7285. // data
  7286. }
  7287. current_codepage = old_cp;
  7288. ba.next(1).write_shift(1, 0x1A);
  7289. return ba.end();
  7290. }
  7291. return {
  7292. to_workbook: dbf_to_workbook,
  7293. to_sheet: dbf_to_sheet,
  7294. from_sheet: sheet_to_dbf
  7295. };
  7296. })();
  7297. var SYLK = (function() {
  7298. /* TODO: stress test sequences */
  7299. var sylk_escapes = ({
  7300. AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
  7301. AE:'È', BE:'É', CE:'Ê', HE:'Ë',
  7302. AI:'Ì', BI:'Í', CI:'Î', HI:'Ï',
  7303. AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
  7304. AU:'Ù', BU:'Ú', CU:'Û', HU:'Ü',
  7305. Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
  7306. Ae:'è', Be:'é', Ce:'ê', He:'ë',
  7307. Ai:'ì', Bi:'í', Ci:'î', Hi:'ï',
  7308. Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
  7309. Au:'ù', Bu:'ú', Cu:'û', Hu:'ü',
  7310. KC:'Ç', Kc:'ç', q:'æ', z:'œ', a:'Æ', j:'Œ',
  7311. DN:209, Dn:241, Hy:255,
  7312. S:169, c:170, R:174, "B ":180,
  7313. 0:176, 1:177, 2:178,
  7314. 3:179, 5:181, 6:182,
  7315. 7:183, Q:185, k:186, b:208, i:216, l:222, s:240, y:248,
  7316. "!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
  7317. "+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
  7318. });
  7319. var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
  7320. var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
  7321. var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
  7322. sylk_escapes["|"] = 254;
  7323. /* https://oss.sheetjs.com/notes/sylk/ for more details */
  7324. function sylk_to_aoa(d, opts) {
  7325. switch(opts.type) {
  7326. case 'base64': return sylk_to_aoa_str(Base64_decode(d), opts);
  7327. case 'binary': return sylk_to_aoa_str(d, opts);
  7328. case 'buffer': return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  7329. case 'array': return sylk_to_aoa_str(cc2str(d), opts);
  7330. }
  7331. throw new Error("Unrecognized type " + opts.type);
  7332. }
  7333. function sylk_to_aoa_str(str, opts) {
  7334. var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr = [];
  7335. var formats = [];
  7336. var next_cell_format = null;
  7337. var sht = {}, rowinfo = [], colinfo = [], cw = [];
  7338. var Mval = 0, j;
  7339. var wb = { Workbook: { WBProps: {}, Names: [] } };
  7340. if(+opts.codepage >= 0) set_cp(+opts.codepage);
  7341. for (; ri !== records.length; ++ri) {
  7342. Mval = 0;
  7343. var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
  7344. var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
  7345. var RT=record[0], val;
  7346. if(rstr.length > 0) switch(RT) {
  7347. case 'ID': break; /* header */
  7348. case 'E': break; /* EOF */
  7349. case 'B': break; /* dimensions */
  7350. case 'O': /* workbook options */
  7351. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  7352. case 'V': {
  7353. var d1904 = parseInt(record[rj].slice(1), 10);
  7354. // NOTE: it is technically an error if d1904 >= 5 or < 0
  7355. if(d1904 >= 1 && d1904 <= 4) wb.Workbook.WBProps.date1904 = true;
  7356. } break;
  7357. } break;
  7358. case 'W': break; /* window */
  7359. case 'P':
  7360. switch(record[1].charAt(0)){
  7361. case 'P': formats.push(rstr.slice(3).replace(/;;/g, ";")); break;
  7362. } break;
  7363. case 'NN': { /* defined name */
  7364. var nn = {Sheet: 0};
  7365. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  7366. case 'N': nn.Name = record[rj].slice(1); break;
  7367. case 'E': nn.Ref = (opts && opts.sheet || "Sheet1") + "!" + rc_to_a1(record[rj].slice(1)); break;
  7368. }
  7369. wb.Workbook.Names.push(nn);
  7370. } break;
  7371. // case 'NE': // ??
  7372. // case 'NU': // ??
  7373. case 'C': /* cell */
  7374. var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1, formula = "", cell_t = "z";
  7375. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  7376. case 'A': break; // TODO: comment
  7377. case 'X': C = parseInt(record[rj].slice(1), 10)-1; C_seen_X = true; break;
  7378. case 'Y':
  7379. R = parseInt(record[rj].slice(1), 10)-1; if(!C_seen_X) C = 0;
  7380. for(j = arr.length; j <= R; ++j) arr[j] = [];
  7381. break;
  7382. case 'K':
  7383. val = record[rj].slice(1);
  7384. if(val.charAt(0) === '"') { val = val.slice(1,val.length - 1); cell_t = "s"; }
  7385. else if(val === 'TRUE' || val === 'FALSE') { val = val === 'TRUE'; cell_t = "b"; }
  7386. else if(!isNaN(fuzzynum(val))) {
  7387. val = fuzzynum(val); cell_t = "n";
  7388. if(next_cell_format !== null && fmt_is_date(next_cell_format) && opts.cellDates) { val = numdate(wb.Workbook.WBProps.date1904 ? val + 1462 : val); cell_t = "d"; }
  7389. } else if(!isNaN(fuzzydate(val).getDate())) {
  7390. val = parseDate(val); cell_t = "d";
  7391. if(!opts.cellDates) { cell_t = "n"; val = datenum(val, wb.Workbook.WBProps.date1904); }
  7392. }
  7393. if(typeof $cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = $cptable.utils.decode(opts.codepage, val);
  7394. C_seen_K = true;
  7395. break;
  7396. case 'E':
  7397. C_seen_E = true;
  7398. formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
  7399. break;
  7400. case 'S':
  7401. C_seen_S = true;
  7402. break;
  7403. case 'G': break; // unknown
  7404. case 'R': _R = parseInt(record[rj].slice(1), 10)-1; break;
  7405. case 'C': _C = parseInt(record[rj].slice(1), 10)-1; break;
  7406. // case 'P': // ??
  7407. // case 'D': // ??
  7408. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  7409. }
  7410. if(C_seen_K) {
  7411. if(!arr[R][C]) arr[R][C] = { t: cell_t, v: val };
  7412. else { arr[R][C].t = cell_t; arr[R][C].v = val; }
  7413. if(next_cell_format) arr[R][C].z = next_cell_format;
  7414. if(opts.cellText !== false && next_cell_format) arr[R][C].w = SSF_format(arr[R][C].z, arr[R][C].v, { date1904: wb.Workbook.WBProps.date1904 });
  7415. next_cell_format = null;
  7416. }
  7417. if(C_seen_S) {
  7418. if(C_seen_E) throw new Error("SYLK shared formula cannot have own formula");
  7419. var shrbase = _R > -1 && arr[_R][_C];
  7420. if(!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base");
  7421. formula = shift_formula_str(shrbase[1], {r: R - _R, c: C - _C});
  7422. }
  7423. if(formula) {
  7424. if(!arr[R][C]) arr[R][C] = { t: 'n', f: formula };
  7425. else arr[R][C].f = formula;
  7426. }
  7427. break;
  7428. case 'F': /* Format */
  7429. var F_seen = 0;
  7430. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  7431. case 'X': C = parseInt(record[rj].slice(1), 10)-1; ++F_seen; break;
  7432. case 'Y':
  7433. R = parseInt(record[rj].slice(1), 10)-1; /*C = 0;*/
  7434. for(j = arr.length; j <= R; ++j) arr[j] = [];
  7435. break;
  7436. case 'M': Mval = parseInt(record[rj].slice(1), 10) / 20; break;
  7437. case 'F': break; /* ??? */
  7438. case 'G': break; /* hide grid */
  7439. case 'P':
  7440. next_cell_format = formats[parseInt(record[rj].slice(1), 10)];
  7441. break;
  7442. case 'S': break; /* cell style */
  7443. case 'D': break; /* column */
  7444. case 'N': break; /* font */
  7445. case 'W':
  7446. cw = record[rj].slice(1).split(" ");
  7447. for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
  7448. Mval = parseInt(cw[2], 10);
  7449. colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval};
  7450. } break;
  7451. case 'C': /* default column format */
  7452. C = parseInt(record[rj].slice(1), 10)-1;
  7453. if(!colinfo[C]) colinfo[C] = {};
  7454. break;
  7455. case 'R': /* row properties */
  7456. R = parseInt(record[rj].slice(1), 10)-1;
  7457. if(!rowinfo[R]) rowinfo[R] = {};
  7458. if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
  7459. else if(Mval === 0) rowinfo[R].hidden = true;
  7460. break;
  7461. // case 'K': // ??
  7462. // case 'E': // ??
  7463. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  7464. }
  7465. if(F_seen < 1) next_cell_format = null; break;
  7466. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  7467. }
  7468. }
  7469. if(rowinfo.length > 0) sht['!rows'] = rowinfo;
  7470. if(colinfo.length > 0) sht['!cols'] = colinfo;
  7471. colinfo.forEach(function(col) { process_col(col); });
  7472. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  7473. return [arr, sht, wb];
  7474. }
  7475. function sylk_to_workbook(d, opts) {
  7476. var aoasht = sylk_to_aoa(d, opts);
  7477. var aoa = aoasht[0], ws = aoasht[1], wb = aoasht[2];
  7478. var _opts = dup(opts); _opts.date1904 = (((wb||{}).Workbook || {}).WBProps || {}).date1904;
  7479. var o = aoa_to_sheet(aoa, _opts);
  7480. keys(ws).forEach(function(k) { o[k] = ws[k]; });
  7481. var outwb = sheet_to_workbook(o, opts);
  7482. keys(wb).forEach(function(k) { outwb[k] = wb[k]; });
  7483. outwb.bookType = "sylk";
  7484. return outwb;
  7485. }
  7486. function write_ws_cell_sylk(cell, ws, R, C) {
  7487. var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
  7488. switch(cell.t) {
  7489. case 'n':
  7490. o += (cell.v||0);
  7491. if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
  7492. case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
  7493. case 'e': o += cell.w || cell.v; break;
  7494. case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
  7495. case 's': o += '"' + (cell.v == null ? "" : String(cell.v)).replace(/"/g,"").replace(/;/g, ";;") + '"'; break;
  7496. }
  7497. return o;
  7498. }
  7499. function write_ws_cols_sylk(out, cols) {
  7500. cols.forEach(function(col, i) {
  7501. var rec = "F;W" + (i+1) + " " + (i+1) + " ";
  7502. if(col.hidden) rec += "0";
  7503. else {
  7504. if(typeof col.width == 'number' && !col.wpx) col.wpx = width2px(col.width);
  7505. if(typeof col.wpx == 'number' && !col.wch) col.wch = px2char(col.wpx);
  7506. if(typeof col.wch == 'number') rec += Math.round(col.wch);
  7507. }
  7508. if(rec.charAt(rec.length - 1) != " ") out.push(rec);
  7509. });
  7510. }
  7511. function write_ws_rows_sylk(out, rows) {
  7512. rows.forEach(function(row, i) {
  7513. var rec = "F;";
  7514. if(row.hidden) rec += "M0;";
  7515. else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
  7516. else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
  7517. if(rec.length > 2) out.push(rec + "R" + (i+1));
  7518. });
  7519. }
  7520. function sheet_to_sylk(ws, opts, wb) {
  7521. /* TODO: codepage */
  7522. var preamble = ["ID;PSheetJS;N;E"], o = [];
  7523. var r = safe_decode_range(ws['!ref']), cell;
  7524. var dense = Array.isArray(ws);
  7525. var RS = "\r\n";
  7526. var d1904 = (((wb||{}).Workbook||{}).WBProps||{}).date1904;
  7527. preamble.push("P;PGeneral");
  7528. preamble.push("F;P0;DG0G8;M255");
  7529. if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
  7530. if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);
  7531. 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(" "));
  7532. preamble.push("O;L;D;B" + (d1904 ? ";V4" : "") + ";K47;G100 0.001");
  7533. for(var R = r.s.r; R <= r.e.r; ++R) {
  7534. var p = [];
  7535. for(var C = r.s.c; C <= r.e.c; ++C) {
  7536. var coord = encode_cell({r:R,c:C});
  7537. cell = dense ? (ws[R]||[])[C]: ws[coord];
  7538. if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
  7539. p.push(write_ws_cell_sylk(cell, ws, R, C, opts)); // TODO: pass date1904 info
  7540. }
  7541. o.push(p.join(RS));
  7542. }
  7543. return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
  7544. }
  7545. return {
  7546. to_workbook: sylk_to_workbook,
  7547. from_sheet: sheet_to_sylk
  7548. };
  7549. })();
  7550. var DIF = (function() {
  7551. function dif_to_aoa(d, opts) {
  7552. switch(opts.type) {
  7553. case 'base64': return dif_to_aoa_str(Base64_decode(d), opts);
  7554. case 'binary': return dif_to_aoa_str(d, opts);
  7555. case 'buffer': return dif_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  7556. case 'array': return dif_to_aoa_str(cc2str(d), opts);
  7557. }
  7558. throw new Error("Unrecognized type " + opts.type);
  7559. }
  7560. function dif_to_aoa_str(str, opts) {
  7561. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  7562. for (; ri !== records.length; ++ri) {
  7563. if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
  7564. if (R < 0) continue;
  7565. var metadata = records[ri].trim().split(",");
  7566. var type = metadata[0], value = metadata[1];
  7567. ++ri;
  7568. var data = records[ri] || "";
  7569. while(((data.match(/["]/g)||[]).length & 1) && ri < records.length - 1) data += "\n" + records[++ri];
  7570. data = data.trim();
  7571. switch (+type) {
  7572. case -1:
  7573. if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
  7574. else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
  7575. break;
  7576. case 0:
  7577. if(data === 'TRUE') arr[R][C] = true;
  7578. else if(data === 'FALSE') arr[R][C] = false;
  7579. else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
  7580. else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
  7581. else arr[R][C] = value;
  7582. ++C; break;
  7583. case 1:
  7584. data = data.slice(1,data.length-1);
  7585. data = data.replace(/""/g, '"');
  7586. if(DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1);
  7587. arr[R][C++] = data !== '' ? data : null;
  7588. break;
  7589. }
  7590. if (data === 'EOD') break;
  7591. }
  7592. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  7593. return arr;
  7594. }
  7595. function dif_to_sheet(str, opts) { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
  7596. function dif_to_workbook(str, opts) {
  7597. var o = sheet_to_workbook(dif_to_sheet(str, opts), opts);
  7598. o.bookType = "dif";
  7599. return o;
  7600. }
  7601. function make_value(v, s) { return "0," + String(v) + "\r\n" + s; }
  7602. function make_value_str(s) { return "1,0\r\n\"" + s.replace(/"/g,'""') + '"'; }
  7603. function sheet_to_dif(ws) {
  7604. var _DIF_XL = DIF_XL;
  7605. var r = safe_decode_range(ws['!ref']);
  7606. var dense = Array.isArray(ws);
  7607. var o = [
  7608. "TABLE\r\n0,1\r\n\"sheetjs\"\r\n",
  7609. "VECTORS\r\n0," + (r.e.r - r.s.r + 1) + "\r\n\"\"\r\n",
  7610. "TUPLES\r\n0," + (r.e.c - r.s.c + 1) + "\r\n\"\"\r\n",
  7611. "DATA\r\n0,0\r\n\"\"\r\n"
  7612. ];
  7613. for(var R = r.s.r; R <= r.e.r; ++R) {
  7614. var p = "-1,0\r\nBOT\r\n";
  7615. for(var C = r.s.c; C <= r.e.c; ++C) {
  7616. var cell = dense ? (ws[R] && ws[R][C]) : ws[encode_cell({r:R,c:C})];
  7617. if(cell == null) { p +=("1,0\r\n\"\"\r\n"); continue;}
  7618. switch(cell.t) {
  7619. case 'n':
  7620. if(_DIF_XL) {
  7621. if(cell.w != null) p +=("0," + cell.w + "\r\nV");
  7622. else if(cell.v != null) p +=(make_value(cell.v, "V")); // TODO: should this call SSF_format?
  7623. else if(cell.f != null && !cell.F) p +=(make_value_str("=" + cell.f));
  7624. else p +=("1,0\r\n\"\"");
  7625. } else {
  7626. if(cell.v == null) p +=("1,0\r\n\"\"");
  7627. else p +=(make_value(cell.v, "V"));
  7628. }
  7629. break;
  7630. case 'b':
  7631. p +=(cell.v ? make_value(1, "TRUE") : make_value(0, "FALSE"));
  7632. break;
  7633. case 's':
  7634. p +=(make_value_str((!_DIF_XL || isNaN(+cell.v)) ? cell.v : '="' + cell.v + '"'));
  7635. break;
  7636. case 'd':
  7637. if(!cell.w) cell.w = SSF_format(cell.z || table_fmt[14], datenum(parseDate(cell.v)));
  7638. if(_DIF_XL) p +=(make_value(cell.w, "V"));
  7639. else p +=(make_value_str(cell.w));
  7640. break;
  7641. default: p +=("1,0\r\n\"\"");
  7642. }
  7643. p += "\r\n";
  7644. }
  7645. o.push(p);
  7646. }
  7647. return o.join("") + "-1,0\r\nEOD";
  7648. }
  7649. return {
  7650. to_workbook: dif_to_workbook,
  7651. to_sheet: dif_to_sheet,
  7652. from_sheet: sheet_to_dif
  7653. };
  7654. })();
  7655. var ETH = (function() {
  7656. function decode(s) { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
  7657. function encode(s) { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }
  7658. function eth_to_aoa(str, opts) {
  7659. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  7660. for (; ri !== records.length; ++ri) {
  7661. var record = records[ri].trim().split(":");
  7662. if(record[0] !== 'cell') continue;
  7663. var addr = decode_cell(record[1]);
  7664. if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
  7665. R = addr.r; C = addr.c;
  7666. switch(record[2]) {
  7667. case 't': arr[R][C] = decode(record[3]); break;
  7668. case 'v': arr[R][C] = +record[3]; break;
  7669. case 'vtf': var _f = record[record.length - 1];
  7670. /* falls through */
  7671. case 'vtc':
  7672. switch(record[3]) {
  7673. case 'nl': arr[R][C] = +record[4] ? true : false; break;
  7674. default: arr[R][C] = +record[4]; break;
  7675. }
  7676. if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
  7677. }
  7678. }
  7679. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  7680. return arr;
  7681. }
  7682. function eth_to_sheet(d, opts) { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
  7683. function eth_to_workbook(d, opts) { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }
  7684. var header = [
  7685. "socialcalc:version:1.5",
  7686. "MIME-Version: 1.0",
  7687. "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  7688. ].join("\n");
  7689. var sep = [
  7690. "--SocialCalcSpreadsheetControlSave",
  7691. "Content-type: text/plain; charset=UTF-8"
  7692. ].join("\n") + "\n";
  7693. /* TODO: the other parts */
  7694. var meta = [
  7695. "# SocialCalc Spreadsheet Control Save",
  7696. "part:sheet"
  7697. ].join("\n");
  7698. var end = "--SocialCalcSpreadsheetControlSave--";
  7699. function sheet_to_eth_data(ws) {
  7700. if(!ws || !ws['!ref']) return "";
  7701. var o = [], oo = [], cell, coord = "";
  7702. var r = decode_range(ws['!ref']);
  7703. var dense = Array.isArray(ws);
  7704. for(var R = r.s.r; R <= r.e.r; ++R) {
  7705. for(var C = r.s.c; C <= r.e.c; ++C) {
  7706. coord = encode_cell({r:R,c:C});
  7707. cell = dense ? (ws[R]||[])[C] : ws[coord];
  7708. if(!cell || cell.v == null || cell.t === 'z') continue;
  7709. oo = ["cell", coord, 't'];
  7710. switch(cell.t) {
  7711. case 's': case 'str': oo.push(encode(cell.v)); break;
  7712. case 'n':
  7713. if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
  7714. else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
  7715. break;
  7716. case 'b':
  7717. oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
  7718. oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
  7719. break;
  7720. case 'd':
  7721. var t = datenum(parseDate(cell.v));
  7722. oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
  7723. oo[5] = cell.w || SSF_format(cell.z || table_fmt[14], t);
  7724. break;
  7725. case 'e': continue;
  7726. }
  7727. o.push(oo.join(":"));
  7728. }
  7729. }
  7730. o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
  7731. o.push("valueformat:1:text-wiki");
  7732. //o.push("copiedfrom:" + ws['!ref']); // clipboard only
  7733. return o.join("\n");
  7734. }
  7735. function sheet_to_eth(ws) {
  7736. return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
  7737. // return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
  7738. }
  7739. return {
  7740. to_workbook: eth_to_workbook,
  7741. to_sheet: eth_to_sheet,
  7742. from_sheet: sheet_to_eth
  7743. };
  7744. })();
  7745. var PRN = (function() {
  7746. function set_text_arr(data, arr, R, C, o) {
  7747. if(o.raw) arr[R][C] = data;
  7748. else if(data === ""){/* empty */}
  7749. else if(data === 'TRUE') arr[R][C] = true;
  7750. else if(data === 'FALSE') arr[R][C] = false;
  7751. else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
  7752. else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
  7753. else arr[R][C] = data;
  7754. }
  7755. function prn_to_aoa_str(f, opts) {
  7756. var o = opts || {};
  7757. var arr = ([]);
  7758. if(!f || f.length === 0) return arr;
  7759. var lines = f.split(/[\r\n]/);
  7760. var L = lines.length - 1;
  7761. while(L >= 0 && lines[L].length === 0) --L;
  7762. var start = 10, idx = 0;
  7763. var R = 0;
  7764. for(; R <= L; ++R) {
  7765. idx = lines[R].indexOf(" ");
  7766. if(idx == -1) idx = lines[R].length; else idx++;
  7767. start = Math.max(start, idx);
  7768. }
  7769. for(R = 0; R <= L; ++R) {
  7770. arr[R] = [];
  7771. /* TODO: confirm that widths are always 10 */
  7772. var C = 0;
  7773. set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
  7774. for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
  7775. set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
  7776. }
  7777. if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
  7778. return arr;
  7779. }
  7780. // List of accepted CSV separators
  7781. var guess_seps = {
  7782. 0x2C: ',',
  7783. 0x09: "\t",
  7784. 0x3B: ';',
  7785. 0x7C: '|'
  7786. };
  7787. // CSV separator weights to be used in case of equal numbers
  7788. var guess_sep_weights = {
  7789. 0x2C: 3,
  7790. 0x09: 2,
  7791. 0x3B: 1,
  7792. 0x7C: 0
  7793. };
  7794. function guess_sep(str) {
  7795. var cnt = {}, instr = false, end = 0, cc = 0;
  7796. for(;end < str.length;++end) {
  7797. if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
  7798. else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
  7799. }
  7800. cc = [];
  7801. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  7802. cc.push([ cnt[end], end ]);
  7803. }
  7804. if ( !cc.length ) {
  7805. cnt = guess_sep_weights;
  7806. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  7807. cc.push([ cnt[end], end ]);
  7808. }
  7809. }
  7810. cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });
  7811. return guess_seps[cc.pop()[1]] || 0x2C;
  7812. }
  7813. function dsv_to_sheet_str(str, opts) {
  7814. var o = opts || {};
  7815. var sep = "";
  7816. if(DENSE != null && o.dense == null) o.dense = DENSE;
  7817. var ws = o.dense ? ([]) : ({});
  7818. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  7819. if(str.slice(0,4) == "sep=") {
  7820. // If the line ends in \r\n
  7821. if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
  7822. sep = str.charAt(4); str = str.slice(7);
  7823. }
  7824. // If line ends in \r OR \n
  7825. else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
  7826. sep = str.charAt(4); str = str.slice(6);
  7827. }
  7828. else sep = guess_sep(str.slice(0,1024));
  7829. }
  7830. else if(o && o.FS) sep = o.FS;
  7831. else sep = guess_sep(str.slice(0,1024));
  7832. var R = 0, C = 0, v = 0;
  7833. var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0, startcc=str.charCodeAt(0);
  7834. var _re = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
  7835. function finish_cell() {
  7836. var s = str.slice(start, end); if(s.slice(-1) == "\r") s = s.slice(0, -1);
  7837. var cell = ({});
  7838. if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
  7839. if(s.length === 0) cell.t = 'z';
  7840. else if(o.raw) { cell.t = 's'; cell.v = s; }
  7841. else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
  7842. else if(s.charCodeAt(0) == 0x3D) {
  7843. if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
  7844. else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
  7845. else { cell.t = 's'; cell.v = s; } }
  7846. else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
  7847. else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
  7848. else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
  7849. else if(!isNaN((v = fuzzydate(s)).getDate()) || _re && s.match(_re)) {
  7850. cell.z = o.dateNF || table_fmt[14];
  7851. var k = 0;
  7852. if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; v = parseDate(s, k); }
  7853. if(o.cellDates) { cell.t = 'd'; cell.v = v; }
  7854. else { cell.t = 'n'; cell.v = datenum(v); }
  7855. if(o.cellText !== false) cell.w = SSF_format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
  7856. if(!o.cellNF) delete cell.z;
  7857. } else {
  7858. cell.t = 's';
  7859. cell.v = s;
  7860. }
  7861. if(cell.t == 'z'){}
  7862. else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
  7863. else ws[encode_cell({c:C,r:R})] = cell;
  7864. start = end+1; startcc = str.charCodeAt(start);
  7865. if(range.e.c < C) range.e.c = C;
  7866. if(range.e.r < R) range.e.r = R;
  7867. if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
  7868. }
  7869. outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
  7870. case 0x22: if(startcc === 0x22) instr = !instr; break;
  7871. case 0x0d:
  7872. if(instr) break;
  7873. if(str.charCodeAt(end+1) == 0x0a) ++end;
  7874. /* falls through */
  7875. case sepcc: case 0x0a: if(!instr && finish_cell()) break outer; break;
  7876. default: break;
  7877. }
  7878. if(end - start > 0) finish_cell();
  7879. ws['!ref'] = encode_range(range);
  7880. return ws;
  7881. }
  7882. function prn_to_sheet_str(str, opts) {
  7883. if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
  7884. if(opts.FS) return dsv_to_sheet_str(str, opts);
  7885. if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
  7886. if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
  7887. return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
  7888. }
  7889. function prn_to_sheet(d, opts) {
  7890. var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
  7891. switch(opts.type) {
  7892. case 'base64': str = Base64_decode(d); break;
  7893. case 'binary': str = d; break;
  7894. case 'buffer':
  7895. if(opts.codepage == 65001) str = d.toString('utf8'); // TODO: test if buf
  7896. else if(opts.codepage && typeof $cptable !== 'undefined') str = $cptable.utils.decode(opts.codepage, d);
  7897. else str = has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d);
  7898. break;
  7899. case 'array': str = cc2str(d); break;
  7900. case 'string': str = d; break;
  7901. default: throw new Error("Unrecognized type " + opts.type);
  7902. }
  7903. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
  7904. else if(opts.type != 'string' && opts.type != 'buffer' && opts.codepage == 65001) str = utf8read(str);
  7905. else if((opts.type == 'binary') && typeof $cptable !== 'undefined' && opts.codepage) str = $cptable.utils.decode(opts.codepage, $cptable.utils.encode(28591,str));
  7906. if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
  7907. return prn_to_sheet_str(str, opts);
  7908. }
  7909. function prn_to_workbook(d, opts) { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }
  7910. function sheet_to_prn(ws) {
  7911. var o = [];
  7912. var r = safe_decode_range(ws['!ref']), cell;
  7913. var dense = Array.isArray(ws);
  7914. for(var R = r.s.r; R <= r.e.r; ++R) {
  7915. var oo = [];
  7916. for(var C = r.s.c; C <= r.e.c; ++C) {
  7917. var coord = encode_cell({r:R,c:C});
  7918. cell = dense ? (ws[R]||[])[C] : ws[coord];
  7919. if(!cell || cell.v == null) { oo.push(" "); continue; }
  7920. var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
  7921. while(w.length < 10) w += " ";
  7922. oo.push(w + (C === 0 ? " " : ""));
  7923. }
  7924. o.push(oo.join(""));
  7925. }
  7926. return o.join("\n");
  7927. }
  7928. return {
  7929. to_workbook: prn_to_workbook,
  7930. to_sheet: prn_to_sheet,
  7931. from_sheet: sheet_to_prn
  7932. };
  7933. })();
  7934. /* Excel defaults to SYLK but warns if data is not valid */
  7935. function read_wb_ID(d, opts) {
  7936. var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
  7937. try {
  7938. var out = SYLK.to_workbook(d, o);
  7939. o.WTF = OLD_WTF;
  7940. return out;
  7941. } catch(e) {
  7942. o.WTF = OLD_WTF;
  7943. if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
  7944. return PRN.to_workbook(d, opts);
  7945. }
  7946. }
  7947. var WK_ = (function() {
  7948. function lotushopper(data, cb, opts) {
  7949. if(!data) return;
  7950. prep_blob(data, data.l || 0);
  7951. var Enum = opts.Enum || WK1Enum;
  7952. while(data.l < data.length) {
  7953. var RT = data.read_shift(2);
  7954. var R = Enum[RT] || Enum[0xFFFF];
  7955. var length = data.read_shift(2);
  7956. var tgt = data.l + length;
  7957. var d = R.f && R.f(data, length, opts);
  7958. data.l = tgt;
  7959. if(cb(d, R, RT)) return;
  7960. }
  7961. }
  7962. function lotus_to_workbook(d, opts) {
  7963. switch(opts.type) {
  7964. case 'base64': return lotus_to_workbook_buf(s2a(Base64_decode(d)), opts);
  7965. case 'binary': return lotus_to_workbook_buf(s2a(d), opts);
  7966. case 'buffer':
  7967. case 'array': return lotus_to_workbook_buf(d, opts);
  7968. }
  7969. throw "Unsupported type " + opts.type;
  7970. }
  7971. function lotus_to_workbook_buf(d, opts) {
  7972. if(!d) return d;
  7973. var o = opts || {};
  7974. if(DENSE != null && o.dense == null) o.dense = DENSE;
  7975. var s = ((o.dense ? [] : {})), n = "Sheet1", next_n = "", sidx = 0;
  7976. var sheets = {}, snames = [], realnames = [];
  7977. var refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  7978. var sheetRows = o.sheetRows || 0;
  7979. if(d[4] == 0x51 && d[5] == 0x50 && d[6] == 0x57) return qpw_to_workbook_buf(d, opts);
  7980. if(d[2] == 0x00) {
  7981. if(d[3] == 0x08 || d[3] == 0x09) {
  7982. if(d.length >= 16 && d[14] == 0x05 && d[15] === 0x6c) throw new Error("Unsupported Works 3 for Mac file");
  7983. }
  7984. }
  7985. if(d[2] == 0x02) {
  7986. o.Enum = WK1Enum;
  7987. lotushopper(d, function(val, R, RT) { switch(RT) {
  7988. case 0x00: /* BOF */
  7989. o.vers = val;
  7990. if(val >= 0x1000) o.qpro = true;
  7991. break;
  7992. case 0xFF: /* BOF (works 3+) */
  7993. o.vers = val;
  7994. o.works = true;
  7995. break;
  7996. case 0x06: refguess = val; break; /* RANGE */
  7997. case 0xCC: if(val) next_n = val; break; /* SHEETNAMECS */
  7998. case 0xDE: next_n = val; break; /* SHEETNAMELP */
  7999. case 0x0F: /* LABEL */
  8000. case 0x33: /* STRING */
  8001. if((!o.qpro && !o.works || RT == 0x33) && val[1].v.charCodeAt(0) < 0x30) val[1].v = val[1].v.slice(1);
  8002. if(o.works || o.works2) val[1].v = val[1].v.replace(/\r\n/g, "\n");
  8003. /* falls through */
  8004. case 0x0D: /* INTEGER */
  8005. case 0x0E: /* NUMBER */
  8006. case 0x10: /* FORMULA */
  8007. /* TODO: actual translation of the format code */
  8008. if(RT == 0x0E && (val[2] & 0x70) == 0x70 && (val[2] & 0x0F) > 1 && (val[2] & 0x0F) < 15) {
  8009. val[1].z = o.dateNF || table_fmt[14];
  8010. if(o.cellDates) { val[1].t = 'd'; val[1].v = numdate(val[1].v); }
  8011. }
  8012. if(o.qpro) {
  8013. if(val[3] > sidx) {
  8014. s["!ref"] = encode_range(refguess);
  8015. sheets[n] = s;
  8016. snames.push(n);
  8017. s = (o.dense ? [] : {});
  8018. refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  8019. sidx = val[3]; n = next_n || "Sheet" + (sidx + 1); next_n = "";
  8020. }
  8021. }
  8022. var tmpcell = o.dense ? (s[val[0].r]||[])[val[0].c] : s[encode_cell(val[0])];
  8023. if(tmpcell) {
  8024. tmpcell.t = val[1].t; tmpcell.v = val[1].v;
  8025. if(val[1].z != null) tmpcell.z = val[1].z;
  8026. if(val[1].f != null) tmpcell.f = val[1].f;
  8027. break;
  8028. }
  8029. if(o.dense) {
  8030. if(!s[val[0].r]) s[val[0].r] = [];
  8031. s[val[0].r][val[0].c] = val[1];
  8032. } else s[encode_cell(val[0])] = val[1];
  8033. break;
  8034. case 0x5405: o.works2 = true; break;
  8035. default:
  8036. }}, o);
  8037. } else if(d[2] == 0x1A || d[2] == 0x0E) {
  8038. o.Enum = WK3Enum;
  8039. if(d[2] == 0x0E) { o.qpro = true; d.l = 0; }
  8040. lotushopper(d, function(val, R, RT) { switch(RT) {
  8041. case 0xCC: n = val; break; /* SHEETNAMECS */
  8042. case 0x16: /* LABEL16 */
  8043. if(val[1].v.charCodeAt(0) < 0x30) val[1].v = val[1].v.slice(1);
  8044. // TODO: R9 appears to encode control codes this way -- verify against other versions
  8045. val[1].v = val[1].v.replace(/\x0F./g, function($$) { return String.fromCharCode($$.charCodeAt(1) - 0x20); }).replace(/\r\n/g, "\n");
  8046. /* falls through */
  8047. case 0x17: /* NUMBER17 */
  8048. case 0x18: /* NUMBER18 */
  8049. case 0x19: /* FORMULA19 */
  8050. case 0x25: /* NUMBER25 */
  8051. case 0x27: /* NUMBER27 */
  8052. case 0x28: /* FORMULA28 */
  8053. if(val[3] > sidx) {
  8054. s["!ref"] = encode_range(refguess);
  8055. sheets[n] = s;
  8056. snames.push(n);
  8057. s = (o.dense ? [] : {});
  8058. refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  8059. sidx = val[3]; n = "Sheet" + (sidx + 1);
  8060. }
  8061. if(sheetRows > 0 && val[0].r >= sheetRows) break;
  8062. if(o.dense) {
  8063. if(!s[val[0].r]) s[val[0].r] = [];
  8064. s[val[0].r][val[0].c] = val[1];
  8065. } else s[encode_cell(val[0])] = val[1];
  8066. if(refguess.e.c < val[0].c) refguess.e.c = val[0].c;
  8067. if(refguess.e.r < val[0].r) refguess.e.r = val[0].r;
  8068. break;
  8069. case 0x1B: /* XFORMAT */
  8070. if(val[0x36b0]) realnames[val[0x36b0][0]] = val[0x36b0][1];
  8071. break;
  8072. case 0x0601: /* SHEETINFOQP */
  8073. realnames[val[0]] = val[1]; if(val[0] == sidx) n = val[1]; break;
  8074. default: break;
  8075. }}, o);
  8076. } else throw new Error("Unrecognized LOTUS BOF " + d[2]);
  8077. s["!ref"] = encode_range(refguess);
  8078. sheets[next_n || n] = s;
  8079. snames.push(next_n || n);
  8080. if(!realnames.length) return { SheetNames: snames, Sheets: sheets };
  8081. var osheets = {}, rnames = [];
  8082. /* TODO: verify no collisions */
  8083. for(var i = 0; i < realnames.length; ++i) if(sheets[snames[i]]) {
  8084. rnames.push(realnames[i] || snames[i]);
  8085. osheets[realnames[i]] = sheets[realnames[i]] || sheets[snames[i]];
  8086. } else {
  8087. rnames.push(realnames[i]);
  8088. osheets[realnames[i]] = ({ "!ref": "A1" });
  8089. }
  8090. return { SheetNames: rnames, Sheets: osheets };
  8091. }
  8092. function sheet_to_wk1(ws, opts) {
  8093. var o = opts || {};
  8094. if(+o.codepage >= 0) set_cp(+o.codepage);
  8095. if(o.type == "string") throw new Error("Cannot write WK1 to JS string");
  8096. var ba = buf_array();
  8097. var range = safe_decode_range(ws["!ref"]);
  8098. var dense = Array.isArray(ws);
  8099. var cols = [];
  8100. write_biff_rec(ba, 0x00, write_BOF_WK1(0x0406));
  8101. write_biff_rec(ba, 0x06, write_RANGE(range));
  8102. var max_R = Math.min(range.e.r, 8191);
  8103. for(var R = range.s.r; R <= max_R; ++R) {
  8104. var rr = encode_row(R);
  8105. for(var C = range.s.c; C <= range.e.c; ++C) {
  8106. if(R === range.s.r) cols[C] = encode_col(C);
  8107. var ref = cols[C] + rr;
  8108. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  8109. if(!cell || cell.t == "z") continue;
  8110. /* TODO: formula records */
  8111. if(cell.t == "n") {
  8112. if((cell.v|0)==cell.v && cell.v >= -32768 && cell.v <= 32767) write_biff_rec(ba, 0x0d, write_INTEGER(R, C, cell.v));
  8113. else write_biff_rec(ba, 0x0e, write_NUMBER(R, C, cell.v));
  8114. } else {
  8115. var str = format_cell(cell);
  8116. write_biff_rec(ba, 0x0F, write_LABEL(R, C, str.slice(0, 239)));
  8117. }
  8118. }
  8119. }
  8120. write_biff_rec(ba, 0x01);
  8121. return ba.end();
  8122. }
  8123. function book_to_wk3(wb, opts) {
  8124. var o = opts || {};
  8125. if(+o.codepage >= 0) set_cp(+o.codepage);
  8126. if(o.type == "string") throw new Error("Cannot write WK3 to JS string");
  8127. var ba = buf_array();
  8128. write_biff_rec(ba, 0x00, write_BOF_WK3(wb));
  8129. for(var i = 0, cnt = 0; i < wb.SheetNames.length; ++i) if((wb.Sheets[wb.SheetNames[i]] || {})["!ref"]) write_biff_rec(ba, 0x1b, write_XFORMAT_SHEETNAME(wb.SheetNames[i], cnt++));
  8130. var wsidx = 0;
  8131. for(i = 0; i < wb.SheetNames.length; ++i) {
  8132. var ws = wb.Sheets[wb.SheetNames[i]];
  8133. if(!ws || !ws["!ref"]) continue;
  8134. var range = safe_decode_range(ws["!ref"]);
  8135. var dense = Array.isArray(ws);
  8136. var cols = [];
  8137. var max_R = Math.min(range.e.r, 8191);
  8138. for(var R = range.s.r; R <= max_R; ++R) {
  8139. var rr = encode_row(R);
  8140. for(var C = range.s.c; C <= range.e.c; ++C) {
  8141. if(R === range.s.r) cols[C] = encode_col(C);
  8142. var ref = cols[C] + rr;
  8143. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  8144. if(!cell || cell.t == "z") continue;
  8145. /* TODO: FORMULA19 NUMBER18 records */
  8146. if(cell.t == "n") {
  8147. write_biff_rec(ba, 0x17, write_NUMBER_17(R, C, wsidx, cell.v));
  8148. } else {
  8149. var str = format_cell(cell);
  8150. /* TODO: max len? */
  8151. write_biff_rec(ba, 0x16, write_LABEL_16(R, C, wsidx, str.slice(0, 239)));
  8152. }
  8153. }
  8154. }
  8155. ++wsidx;
  8156. }
  8157. write_biff_rec(ba, 0x01);
  8158. return ba.end();
  8159. }
  8160. function write_BOF_WK1(v) {
  8161. var out = new_buf(2);
  8162. out.write_shift(2, v);
  8163. return out;
  8164. }
  8165. function write_BOF_WK3(wb) {
  8166. var out = new_buf(26);
  8167. out.write_shift(2, 0x1000);
  8168. out.write_shift(2, 0x0004);
  8169. out.write_shift(4, 0x0000);
  8170. var rows = 0, cols = 0, wscnt = 0;
  8171. for(var i = 0; i < wb.SheetNames.length; ++i) {
  8172. var name = wb.SheetNames[i];
  8173. var ws = wb.Sheets[name];
  8174. if(!ws || !ws["!ref"]) continue;
  8175. ++wscnt;
  8176. var range = decode_range(ws["!ref"]);
  8177. if(rows < range.e.r) rows = range.e.r;
  8178. if(cols < range.e.c) cols = range.e.c;
  8179. }
  8180. if(rows > 8191) rows = 8191;
  8181. out.write_shift(2, rows);
  8182. out.write_shift(1, wscnt);
  8183. out.write_shift(1, cols);
  8184. out.write_shift(2, 0x00);
  8185. out.write_shift(2, 0x00);
  8186. out.write_shift(1, 0x01);
  8187. out.write_shift(1, 0x02);
  8188. out.write_shift(4, 0);
  8189. out.write_shift(4, 0);
  8190. return out;
  8191. }
  8192. function parse_RANGE(blob, length, opts) {
  8193. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  8194. if(length == 8 && opts.qpro) {
  8195. o.s.c = blob.read_shift(1);
  8196. blob.l++;
  8197. o.s.r = blob.read_shift(2);
  8198. o.e.c = blob.read_shift(1);
  8199. blob.l++;
  8200. o.e.r = blob.read_shift(2);
  8201. return o;
  8202. }
  8203. o.s.c = blob.read_shift(2);
  8204. o.s.r = blob.read_shift(2);
  8205. if(length == 12 && opts.qpro) blob.l += 2;
  8206. o.e.c = blob.read_shift(2);
  8207. o.e.r = blob.read_shift(2);
  8208. if(length == 12 && opts.qpro) blob.l += 2;
  8209. if(o.s.c == 0xFFFF) o.s.c = o.e.c = o.s.r = o.e.r = 0;
  8210. return o;
  8211. }
  8212. function write_RANGE(range) {
  8213. var out = new_buf(8);
  8214. out.write_shift(2, range.s.c);
  8215. out.write_shift(2, range.s.r);
  8216. out.write_shift(2, range.e.c);
  8217. out.write_shift(2, range.e.r);
  8218. return out;
  8219. }
  8220. function parse_cell(blob, length, opts) {
  8221. var o = [{c:0,r:0}, {t:'n',v:0}, 0, 0];
  8222. if(opts.qpro && opts.vers != 0x5120) {
  8223. o[0].c = blob.read_shift(1);
  8224. o[3] = blob.read_shift(1);
  8225. o[0].r = blob.read_shift(2);
  8226. blob.l+=2;
  8227. } else if(opts.works) { // TODO: verify with more complex works3-4 examples
  8228. o[0].c = blob.read_shift(2); o[0].r = blob.read_shift(2);
  8229. o[2] = blob.read_shift(2);
  8230. } else {
  8231. o[2] = blob.read_shift(1);
  8232. o[0].c = blob.read_shift(2); o[0].r = blob.read_shift(2);
  8233. }
  8234. return o;
  8235. }
  8236. function parse_LABEL(blob, length, opts) {
  8237. var tgt = blob.l + length;
  8238. var o = parse_cell(blob, length, opts);
  8239. o[1].t = 's';
  8240. if(opts.vers == 0x5120) {
  8241. blob.l++;
  8242. var len = blob.read_shift(1);
  8243. o[1].v = blob.read_shift(len, 'utf8');
  8244. return o;
  8245. }
  8246. if(opts.qpro) blob.l++;
  8247. o[1].v = blob.read_shift(tgt - blob.l, 'cstr');
  8248. return o;
  8249. }
  8250. function write_LABEL(R, C, s) {
  8251. /* TODO: encoding */
  8252. var o = new_buf(7 + s.length);
  8253. o.write_shift(1, 0xFF);
  8254. o.write_shift(2, C);
  8255. o.write_shift(2, R);
  8256. o.write_shift(1, 0x27); // ??
  8257. for(var i = 0; i < o.length; ++i) {
  8258. var cc = s.charCodeAt(i);
  8259. o.write_shift(1, cc >= 0x80 ? 0x5F : cc);
  8260. }
  8261. o.write_shift(1, 0);
  8262. return o;
  8263. }
  8264. function parse_STRING(blob, length, opts) {
  8265. var tgt = blob.l + length;
  8266. var o = parse_cell(blob, length, opts);
  8267. o[1].t = 's';
  8268. if(opts.vers == 0x5120) {
  8269. var len = blob.read_shift(1);
  8270. o[1].v = blob.read_shift(len, 'utf8');
  8271. return o;
  8272. }
  8273. o[1].v = blob.read_shift(tgt - blob.l, 'cstr');
  8274. return o;
  8275. }
  8276. function parse_INTEGER(blob, length, opts) {
  8277. var o = parse_cell(blob, length, opts);
  8278. o[1].v = blob.read_shift(2, 'i');
  8279. return o;
  8280. }
  8281. function write_INTEGER(R, C, v) {
  8282. var o = new_buf(7);
  8283. o.write_shift(1, 0xFF);
  8284. o.write_shift(2, C);
  8285. o.write_shift(2, R);
  8286. o.write_shift(2, v, 'i');
  8287. return o;
  8288. }
  8289. function parse_NUMBER(blob, length, opts) {
  8290. var o = parse_cell(blob, length, opts);
  8291. o[1].v = blob.read_shift(8, 'f');
  8292. return o;
  8293. }
  8294. function write_NUMBER(R, C, v) {
  8295. var o = new_buf(13);
  8296. o.write_shift(1, 0xFF);
  8297. o.write_shift(2, C);
  8298. o.write_shift(2, R);
  8299. o.write_shift(8, v, 'f');
  8300. return o;
  8301. }
  8302. function parse_FORMULA(blob, length, opts) {
  8303. var tgt = blob.l + length;
  8304. var o = parse_cell(blob, length, opts);
  8305. /* TODO: formula */
  8306. o[1].v = blob.read_shift(8, 'f');
  8307. if(opts.qpro) blob.l = tgt;
  8308. else {
  8309. var flen = blob.read_shift(2);
  8310. wk1_fmla_to_csf(blob.slice(blob.l, blob.l + flen), o);
  8311. blob.l += flen;
  8312. }
  8313. return o;
  8314. }
  8315. function wk1_parse_rc(B, V, col) {
  8316. var rel = V & 0x8000;
  8317. V &= ~0x8000;
  8318. V = (rel ? B : 0) + ((V >= 0x2000) ? V - 0x4000 : V);
  8319. return (rel ? "" : "$") + (col ? encode_col(V) : encode_row(V));
  8320. }
  8321. /* var oprec = [
  8322. 8, 8, 8, 8, 8, 8, 8, 8, 6, 4, 4, 5, 5, 7, 3, 3,
  8323. 3, 3, 3, 3, 1, 1, 2, 6, 8, 8, 8, 8, 8, 8, 8, 8
  8324. ]; */
  8325. /* TODO: flesh out */
  8326. var FuncTab = {
  8327. 0x1F: ["NA", 0],
  8328. // 0x20: ["ERR", 0],
  8329. 0x21: ["ABS", 1],
  8330. 0x22: ["TRUNC", 1],
  8331. 0x23: ["SQRT", 1],
  8332. 0x24: ["LOG", 1],
  8333. 0x25: ["LN", 1],
  8334. 0x26: ["PI", 0],
  8335. 0x27: ["SIN", 1],
  8336. 0x28: ["COS", 1],
  8337. 0x29: ["TAN", 1],
  8338. 0x2A: ["ATAN2", 2],
  8339. 0x2B: ["ATAN", 1],
  8340. 0x2C: ["ASIN", 1],
  8341. 0x2D: ["ACOS", 1],
  8342. 0x2E: ["EXP", 1],
  8343. 0x2F: ["MOD", 2],
  8344. // 0x30
  8345. 0x31: ["ISNA", 1],
  8346. 0x32: ["ISERR", 1],
  8347. 0x33: ["FALSE", 0],
  8348. 0x34: ["TRUE", 0],
  8349. 0x35: ["RAND", 0],
  8350. // 0x36 DATE
  8351. // 0x37 NOW
  8352. // 0x38 PMT
  8353. // 0x39 PV
  8354. // 0x3A FV
  8355. // 0x3B IF
  8356. // 0x3C DAY
  8357. // 0x3D MONTH
  8358. // 0x3E YEAR
  8359. 0x3F: ["ROUND", 2],
  8360. // 0x40 TIME
  8361. // 0x41 HOUR
  8362. // 0x42 MINUTE
  8363. // 0x43 SECOND
  8364. 0x44: ["ISNUMBER", 1],
  8365. 0x45: ["ISTEXT", 1],
  8366. 0x46: ["LEN", 1],
  8367. 0x47: ["VALUE", 1],
  8368. // 0x48: ["FIXED", ?? 1],
  8369. 0x49: ["MID", 3],
  8370. 0x4A: ["CHAR", 1],
  8371. // 0x4B
  8372. // 0x4C FIND
  8373. // 0x4D DATEVALUE
  8374. // 0x4E TIMEVALUE
  8375. // 0x4F CELL
  8376. 0x50: ["SUM", 69],
  8377. 0x51: ["AVERAGEA", 69],
  8378. 0x52: ["COUNTA", 69],
  8379. 0x53: ["MINA", 69],
  8380. 0x54: ["MAXA", 69],
  8381. // 0x55 VLOOKUP
  8382. // 0x56 NPV
  8383. // 0x57 VAR
  8384. // 0x58 STD
  8385. // 0x59 IRR
  8386. // 0x5A HLOOKUP
  8387. // 0x5B DSUM
  8388. // 0x5C DAVERAGE
  8389. // 0x5D DCOUNTA
  8390. // 0x5E DMIN
  8391. // 0x5F DMAX
  8392. // 0x60 DVARP
  8393. // 0x61 DSTDEVP
  8394. // 0x62 INDEX
  8395. // 0x63 COLS
  8396. // 0x64 ROWS
  8397. // 0x65 REPEAT
  8398. 0x66: ["UPPER", 1],
  8399. 0x67: ["LOWER", 1],
  8400. // 0x68 LEFT
  8401. // 0x69 RIGHT
  8402. // 0x6A REPLACE
  8403. 0x6B: ["PROPER", 1],
  8404. // 0x6C CELL
  8405. 0x6D: ["TRIM", 1],
  8406. // 0x6E CLEAN
  8407. 0x6F: ["T", 1]
  8408. // 0x70 V
  8409. };
  8410. var BinOpTab = [
  8411. "", "", "", "", "", "", "", "", // eslint-disable-line no-mixed-spaces-and-tabs
  8412. "", "+", "-", "*", "/", "^", "=", "<>", // eslint-disable-line no-mixed-spaces-and-tabs
  8413. "<=", ">=", "<", ">", "", "", "", "", // eslint-disable-line no-mixed-spaces-and-tabs
  8414. "&", "", "", "", "", "", "", "" // eslint-disable-line no-mixed-spaces-and-tabs
  8415. ];
  8416. function wk1_fmla_to_csf(blob, o) {
  8417. prep_blob(blob, 0);
  8418. var out = [], argc = 0, R = "", C = "", argL = "", argR = "";
  8419. while(blob.l < blob.length) {
  8420. var cc = blob[blob.l++];
  8421. switch(cc) {
  8422. case 0x00: out.push(blob.read_shift(8, 'f')); break;
  8423. case 0x01: {
  8424. C = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
  8425. R = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
  8426. out.push(C + R);
  8427. } break;
  8428. case 0x02: {
  8429. var c = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
  8430. var r = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
  8431. C = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
  8432. R = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
  8433. out.push(c + r + ":" + C + R);
  8434. } break;
  8435. case 0x03:
  8436. if(blob.l < blob.length) { console.error("WK1 premature formula end"); return; }
  8437. break;
  8438. case 0x04: out.push("(" + out.pop() + ")"); break;
  8439. case 0x05: out.push(blob.read_shift(2)); break;
  8440. case 0x06: {
  8441. /* TODO: text encoding */
  8442. var Z = ""; while((cc = blob[blob.l++])) Z += String.fromCharCode(cc);
  8443. out.push('"' + Z.replace(/"/g, '""') + '"');
  8444. } break;
  8445. case 0x08: out.push("-" + out.pop()); break;
  8446. case 0x17: out.push("+" + out.pop()); break;
  8447. case 0x16: out.push("NOT(" + out.pop() + ")"); break;
  8448. case 0x14: case 0x15: {
  8449. argR = out.pop(); argL = out.pop();
  8450. out.push(["AND", "OR"][cc - 0x14] + "(" + argL + "," + argR + ")");
  8451. } break;
  8452. default:
  8453. if(cc < 0x20 && BinOpTab[cc]) {
  8454. argR = out.pop(); argL = out.pop();
  8455. out.push(argL + BinOpTab[cc] + argR);
  8456. } else if(FuncTab[cc]) {
  8457. argc = FuncTab[cc][1];
  8458. if(argc == 69) argc = blob[blob.l++];
  8459. if(argc > out.length) { console.error("WK1 bad formula parse 0x" + cc.toString(16) + ":|" + out.join("|") + "|"); return; }
  8460. var args = out.slice(-argc);
  8461. out.length -= argc;
  8462. out.push(FuncTab[cc][0] + "(" + args.join(",") + ")");
  8463. }
  8464. else if(cc <= 0x07) return console.error("WK1 invalid opcode " + cc.toString(16));
  8465. else if(cc <= 0x18) return console.error("WK1 unsupported op " + cc.toString(16));
  8466. else if(cc <= 0x1E) return console.error("WK1 invalid opcode " + cc.toString(16));
  8467. else if(cc <= 0x73) return console.error("WK1 unsupported function opcode " + cc.toString(16));
  8468. // possible future functions ??
  8469. else return console.error("WK1 unrecognized opcode " + cc.toString(16));
  8470. }
  8471. }
  8472. if(out.length == 1) o[1].f = "" + out[0];
  8473. else console.error("WK1 bad formula parse |" + out.join("|") + "|");
  8474. }
  8475. function parse_cell_3(blob) {
  8476. var o = [{c:0,r:0}, {t:'n',v:0}, 0];
  8477. o[0].r = blob.read_shift(2); o[3] = blob[blob.l++]; o[0].c = blob[blob.l++];
  8478. return o;
  8479. }
  8480. function parse_LABEL_16(blob, length) {
  8481. var o = parse_cell_3(blob, length);
  8482. o[1].t = 's';
  8483. o[1].v = blob.read_shift(length - 4, 'cstr');
  8484. return o;
  8485. }
  8486. function write_LABEL_16(R, C, wsidx, s) {
  8487. /* TODO: encoding */
  8488. var o = new_buf(6 + s.length);
  8489. o.write_shift(2, R);
  8490. o.write_shift(1, wsidx);
  8491. o.write_shift(1, C);
  8492. o.write_shift(1, 0x27);
  8493. for(var i = 0; i < s.length; ++i) {
  8494. var cc = s.charCodeAt(i);
  8495. o.write_shift(1, cc >= 0x80 ? 0x5F : cc);
  8496. }
  8497. o.write_shift(1, 0);
  8498. return o;
  8499. }
  8500. function parse_NUMBER_18(blob, length) {
  8501. var o = parse_cell_3(blob, length);
  8502. o[1].v = blob.read_shift(2);
  8503. var v = o[1].v >> 1;
  8504. if(o[1].v & 0x1) {
  8505. switch(v & 0x07) {
  8506. case 0: v = (v >> 3) * 5000; break;
  8507. case 1: v = (v >> 3) * 500; break;
  8508. case 2: v = (v >> 3) / 20; break;
  8509. case 3: v = (v >> 3) / 200; break;
  8510. case 4: v = (v >> 3) / 2000; break;
  8511. case 5: v = (v >> 3) / 20000; break;
  8512. case 6: v = (v >> 3) / 16; break;
  8513. case 7: v = (v >> 3) / 64; break;
  8514. }
  8515. }
  8516. o[1].v = v;
  8517. return o;
  8518. }
  8519. function parse_NUMBER_17(blob, length) {
  8520. var o = parse_cell_3(blob, length);
  8521. var v1 = blob.read_shift(4);
  8522. var v2 = blob.read_shift(4);
  8523. var e = blob.read_shift(2);
  8524. if(e == 0xFFFF) {
  8525. if(v1 === 0 && v2 === 0xC0000000) { o[1].t = "e"; o[1].v = 0x0F; } // ERR -> #VALUE!
  8526. else if(v1 === 0 && v2 === 0xD0000000) { o[1].t = "e"; o[1].v = 0x2A; } // NA -> #N/A
  8527. else o[1].v = 0;
  8528. return o;
  8529. }
  8530. var s = e & 0x8000; e = (e&0x7FFF) - 16446;
  8531. o[1].v = (1 - s*2) * (v2 * Math.pow(2, e+32) + v1 * Math.pow(2, e));
  8532. return o;
  8533. }
  8534. function write_NUMBER_17(R, C, wsidx, v) {
  8535. var o = new_buf(14);
  8536. o.write_shift(2, R);
  8537. o.write_shift(1, wsidx);
  8538. o.write_shift(1, C);
  8539. if(v == 0) {
  8540. o.write_shift(4, 0);
  8541. o.write_shift(4, 0);
  8542. o.write_shift(2, 0xFFFF);
  8543. return o;
  8544. }
  8545. var s = 0, e = 0, v1 = 0, v2 = 0;
  8546. if(v < 0) { s = 1; v = -v; }
  8547. e = Math.log2(v) | 0;
  8548. v /= Math.pow(2, e-31);
  8549. v2 = (v)>>>0;
  8550. if((v2&0x80000000) == 0) { v/=2; ++e; v2 = v >>> 0; }
  8551. v -= v2;
  8552. v2 |= 0x80000000;
  8553. v2 >>>= 0;
  8554. v *= Math.pow(2, 32);
  8555. v1 = v>>>0;
  8556. o.write_shift(4, v1);
  8557. o.write_shift(4, v2);
  8558. e += 0x3FFF + (s ? 0x8000 : 0);
  8559. o.write_shift(2, e);
  8560. return o;
  8561. }
  8562. function parse_FORMULA_19(blob, length) {
  8563. var o = parse_NUMBER_17(blob, 14);
  8564. blob.l += length - 14; /* TODO: WK3 formula */
  8565. return o;
  8566. }
  8567. function parse_NUMBER_25(blob, length) {
  8568. var o = parse_cell_3(blob, length);
  8569. var v1 = blob.read_shift(4);
  8570. o[1].v = v1 >> 6;
  8571. return o;
  8572. }
  8573. function parse_NUMBER_27(blob, length) {
  8574. var o = parse_cell_3(blob, length);
  8575. var v1 = blob.read_shift(8,'f');
  8576. o[1].v = v1;
  8577. return o;
  8578. }
  8579. function parse_FORMULA_28(blob, length) {
  8580. var o = parse_NUMBER_27(blob, 12);
  8581. blob.l += length - 12; /* TODO: formula */
  8582. return o;
  8583. }
  8584. function parse_SHEETNAMECS(blob, length) {
  8585. return blob[blob.l + length - 1] == 0 ? blob.read_shift(length, 'cstr') : "";
  8586. }
  8587. function parse_SHEETNAMELP(blob, length) {
  8588. var len = blob[blob.l++];
  8589. if(len > length - 1) len = length - 1;
  8590. var o = ""; while(o.length < len) o += String.fromCharCode(blob[blob.l++]);
  8591. return o;
  8592. }
  8593. function parse_SHEETINFOQP(blob, length, opts) {
  8594. if(!opts.qpro || length < 21) return;
  8595. var id = blob.read_shift(1);
  8596. blob.l += 17;
  8597. blob.l += 1; //var len = blob.read_shift(1);
  8598. blob.l += 2;
  8599. var nm = blob.read_shift(length - 21, 'cstr');
  8600. return [id, nm];
  8601. }
  8602. function parse_XFORMAT(blob, length) {
  8603. var o = {}, tgt = blob.l + length;
  8604. while(blob.l < tgt) {
  8605. var dt = blob.read_shift(2);
  8606. if(dt == 0x36b0) {
  8607. o[dt] = [0, ""];
  8608. o[dt][0] = blob.read_shift(2);
  8609. while(blob[blob.l]) { o[dt][1] += String.fromCharCode(blob[blob.l]); blob.l++; } blob.l++;
  8610. }
  8611. // TODO: 0x3a99 ??
  8612. }
  8613. return o;
  8614. }
  8615. function write_XFORMAT_SHEETNAME(name, wsidx) {
  8616. var out = new_buf(5 + name.length);
  8617. out.write_shift(2, 0x36b0);
  8618. out.write_shift(2, wsidx);
  8619. for(var i = 0; i < name.length; ++i) {
  8620. var cc = name.charCodeAt(i);
  8621. out[out.l++] = cc > 0x7F ? 0x5F : cc;
  8622. }
  8623. out[out.l++] = 0;
  8624. return out;
  8625. }
  8626. var WK1Enum = {
  8627. 0x0000: { n:"BOF", f:parseuint16 },
  8628. 0x0001: { n:"EOF" },
  8629. 0x0002: { n:"CALCMODE" },
  8630. 0x0003: { n:"CALCORDER" },
  8631. 0x0004: { n:"SPLIT" },
  8632. 0x0005: { n:"SYNC" },
  8633. 0x0006: { n:"RANGE", f:parse_RANGE },
  8634. 0x0007: { n:"WINDOW1" },
  8635. 0x0008: { n:"COLW1" },
  8636. 0x0009: { n:"WINTWO" },
  8637. 0x000A: { n:"COLW2" },
  8638. 0x000B: { n:"NAME" },
  8639. 0x000C: { n:"BLANK" },
  8640. 0x000D: { n:"INTEGER", f:parse_INTEGER },
  8641. 0x000E: { n:"NUMBER", f:parse_NUMBER },
  8642. 0x000F: { n:"LABEL", f:parse_LABEL },
  8643. 0x0010: { n:"FORMULA", f:parse_FORMULA },
  8644. 0x0018: { n:"TABLE" },
  8645. 0x0019: { n:"ORANGE" },
  8646. 0x001A: { n:"PRANGE" },
  8647. 0x001B: { n:"SRANGE" },
  8648. 0x001C: { n:"FRANGE" },
  8649. 0x001D: { n:"KRANGE1" },
  8650. 0x0020: { n:"HRANGE" },
  8651. 0x0023: { n:"KRANGE2" },
  8652. 0x0024: { n:"PROTEC" },
  8653. 0x0025: { n:"FOOTER" },
  8654. 0x0026: { n:"HEADER" },
  8655. 0x0027: { n:"SETUP" },
  8656. 0x0028: { n:"MARGINS" },
  8657. 0x0029: { n:"LABELFMT" },
  8658. 0x002A: { n:"TITLES" },
  8659. 0x002B: { n:"SHEETJS" },
  8660. 0x002D: { n:"GRAPH" },
  8661. 0x002E: { n:"NGRAPH" },
  8662. 0x002F: { n:"CALCCOUNT" },
  8663. 0x0030: { n:"UNFORMATTED" },
  8664. 0x0031: { n:"CURSORW12" },
  8665. 0x0032: { n:"WINDOW" },
  8666. 0x0033: { n:"STRING", f:parse_STRING },
  8667. 0x0037: { n:"PASSWORD" },
  8668. 0x0038: { n:"LOCKED" },
  8669. 0x003C: { n:"QUERY" },
  8670. 0x003D: { n:"QUERYNAME" },
  8671. 0x003E: { n:"PRINT" },
  8672. 0x003F: { n:"PRINTNAME" },
  8673. 0x0040: { n:"GRAPH2" },
  8674. 0x0041: { n:"GRAPHNAME" },
  8675. 0x0042: { n:"ZOOM" },
  8676. 0x0043: { n:"SYMSPLIT" },
  8677. 0x0044: { n:"NSROWS" },
  8678. 0x0045: { n:"NSCOLS" },
  8679. 0x0046: { n:"RULER" },
  8680. 0x0047: { n:"NNAME" },
  8681. 0x0048: { n:"ACOMM" },
  8682. 0x0049: { n:"AMACRO" },
  8683. 0x004A: { n:"PARSE" },
  8684. 0x0066: { n:"PRANGES??" },
  8685. 0x0067: { n:"RRANGES??" },
  8686. 0x0068: { n:"FNAME??" },
  8687. 0x0069: { n:"MRANGES??" },
  8688. 0x00CC: { n:"SHEETNAMECS", f:parse_SHEETNAMECS },
  8689. 0x00DE: { n:"SHEETNAMELP", f:parse_SHEETNAMELP },
  8690. 0x00FF: { n:"BOF", f:parseuint16 },
  8691. 0xFFFF: { n:"" }
  8692. };
  8693. var WK3Enum = {
  8694. 0x0000: { n:"BOF" },
  8695. 0x0001: { n:"EOF" },
  8696. 0x0002: { n:"PASSWORD" },
  8697. 0x0003: { n:"CALCSET" },
  8698. 0x0004: { n:"WINDOWSET" },
  8699. 0x0005: { n:"SHEETCELLPTR" },
  8700. 0x0006: { n:"SHEETLAYOUT" },
  8701. 0x0007: { n:"COLUMNWIDTH" },
  8702. 0x0008: { n:"HIDDENCOLUMN" },
  8703. 0x0009: { n:"USERRANGE" },
  8704. 0x000A: { n:"SYSTEMRANGE" },
  8705. 0x000B: { n:"ZEROFORCE" },
  8706. 0x000C: { n:"SORTKEYDIR" },
  8707. 0x000D: { n:"FILESEAL" },
  8708. 0x000E: { n:"DATAFILLNUMS" },
  8709. 0x000F: { n:"PRINTMAIN" },
  8710. 0x0010: { n:"PRINTSTRING" },
  8711. 0x0011: { n:"GRAPHMAIN" },
  8712. 0x0012: { n:"GRAPHSTRING" },
  8713. 0x0013: { n:"??" },
  8714. 0x0014: { n:"ERRCELL" },
  8715. 0x0015: { n:"NACELL" },
  8716. 0x0016: { n:"LABEL16", f:parse_LABEL_16},
  8717. 0x0017: { n:"NUMBER17", f:parse_NUMBER_17 },
  8718. 0x0018: { n:"NUMBER18", f:parse_NUMBER_18 },
  8719. 0x0019: { n:"FORMULA19", f:parse_FORMULA_19},
  8720. 0x001A: { n:"FORMULA1A" },
  8721. 0x001B: { n:"XFORMAT", f:parse_XFORMAT },
  8722. 0x001C: { n:"DTLABELMISC" },
  8723. 0x001D: { n:"DTLABELCELL" },
  8724. 0x001E: { n:"GRAPHWINDOW" },
  8725. 0x001F: { n:"CPA" },
  8726. 0x0020: { n:"LPLAUTO" },
  8727. 0x0021: { n:"QUERY" },
  8728. 0x0022: { n:"HIDDENSHEET" },
  8729. 0x0023: { n:"??" },
  8730. 0x0025: { n:"NUMBER25", f:parse_NUMBER_25 },
  8731. 0x0026: { n:"??" },
  8732. 0x0027: { n:"NUMBER27", f:parse_NUMBER_27 },
  8733. 0x0028: { n:"FORMULA28", f:parse_FORMULA_28 },
  8734. 0x008E: { n:"??" },
  8735. 0x0093: { n:"??" },
  8736. 0x0096: { n:"??" },
  8737. 0x0097: { n:"??" },
  8738. 0x0098: { n:"??" },
  8739. 0x0099: { n:"??" },
  8740. 0x009A: { n:"??" },
  8741. 0x009B: { n:"??" },
  8742. 0x009C: { n:"??" },
  8743. 0x00A3: { n:"??" },
  8744. 0x00AE: { n:"??" },
  8745. 0x00AF: { n:"??" },
  8746. 0x00B0: { n:"??" },
  8747. 0x00B1: { n:"??" },
  8748. 0x00B8: { n:"??" },
  8749. 0x00B9: { n:"??" },
  8750. 0x00BA: { n:"??" },
  8751. 0x00BB: { n:"??" },
  8752. 0x00BC: { n:"??" },
  8753. 0x00C3: { n:"??" },
  8754. 0x00C9: { n:"??" },
  8755. 0x00CC: { n:"SHEETNAMECS", f:parse_SHEETNAMECS },
  8756. 0x00CD: { n:"??" },
  8757. 0x00CE: { n:"??" },
  8758. 0x00CF: { n:"??" },
  8759. 0x00D0: { n:"??" },
  8760. 0x0100: { n:"??" },
  8761. 0x0103: { n:"??" },
  8762. 0x0104: { n:"??" },
  8763. 0x0105: { n:"??" },
  8764. 0x0106: { n:"??" },
  8765. 0x0107: { n:"??" },
  8766. 0x0109: { n:"??" },
  8767. 0x010A: { n:"??" },
  8768. 0x010B: { n:"??" },
  8769. 0x010C: { n:"??" },
  8770. 0x010E: { n:"??" },
  8771. 0x010F: { n:"??" },
  8772. 0x0180: { n:"??" },
  8773. 0x0185: { n:"??" },
  8774. 0x0186: { n:"??" },
  8775. 0x0189: { n:"??" },
  8776. 0x018C: { n:"??" },
  8777. 0x0200: { n:"??" },
  8778. 0x0202: { n:"??" },
  8779. 0x0201: { n:"??" },
  8780. 0x0204: { n:"??" },
  8781. 0x0205: { n:"??" },
  8782. 0x0280: { n:"??" },
  8783. 0x0281: { n:"??" },
  8784. 0x0282: { n:"??" },
  8785. 0x0283: { n:"??" },
  8786. 0x0284: { n:"??" },
  8787. 0x0285: { n:"??" },
  8788. 0x0286: { n:"??" },
  8789. 0x0287: { n:"??" },
  8790. 0x0288: { n:"??" },
  8791. 0x0292: { n:"??" },
  8792. 0x0293: { n:"??" },
  8793. 0x0294: { n:"??" },
  8794. 0x0295: { n:"??" },
  8795. 0x0296: { n:"??" },
  8796. 0x0299: { n:"??" },
  8797. 0x029A: { n:"??" },
  8798. 0x0300: { n:"??" },
  8799. 0x0304: { n:"??" },
  8800. 0x0601: { n:"SHEETINFOQP", f:parse_SHEETINFOQP },
  8801. 0x0640: { n:"??" },
  8802. 0x0642: { n:"??" },
  8803. 0x0701: { n:"??" },
  8804. 0x0702: { n:"??" },
  8805. 0x0703: { n:"??" },
  8806. 0x0704: { n:"??" },
  8807. 0x0780: { n:"??" },
  8808. 0x0800: { n:"??" },
  8809. 0x0801: { n:"??" },
  8810. 0x0804: { n:"??" },
  8811. 0x0A80: { n:"??" },
  8812. 0x2AF6: { n:"??" },
  8813. 0x3231: { n:"??" },
  8814. 0x6E49: { n:"??" },
  8815. 0x6F44: { n:"??" },
  8816. 0xFFFF: { n:"" }
  8817. };
  8818. /* QPW uses a different set of record types */
  8819. function qpw_to_workbook_buf(d, opts) {
  8820. prep_blob(d, 0);
  8821. var o = opts || {};
  8822. if(DENSE != null && o.dense == null) o.dense = DENSE;
  8823. var s = ((o.dense ? [] : {}));
  8824. var SST = [], sname = "", formulae = [];
  8825. var range = {s:{r:-1,c:-1}, e:{r:-1,c:-1}};
  8826. var cnt = 0, type = 0, C = 0, R = 0;
  8827. var wb = { SheetNames: [], Sheets: {} };
  8828. outer: while(d.l < d.length) {
  8829. var RT = d.read_shift(2), length = d.read_shift(2);
  8830. var p = d.slice(d.l, d.l + length);
  8831. prep_blob(p, 0);
  8832. switch(RT) {
  8833. case 0x01: /* BOF */
  8834. if(p.read_shift(4) != 0x39575051) throw "Bad QPW9 BOF!";
  8835. break;
  8836. case 0x02: /* EOF */ break outer;
  8837. /* TODO: The behavior here should be consistent with Numbers: QP Notebook ~ .TN.SheetArchive, QP Sheet ~ .TST.TableModelArchive */
  8838. case 0x0401: /* BON */ break;
  8839. case 0x0402: /* EON */ /* TODO: backfill missing sheets based on BON cnt */ break;
  8840. case 0x0407: { /* SST */
  8841. p.l += 12;
  8842. while(p.l < p.length) {
  8843. cnt = p.read_shift(2);
  8844. type = p.read_shift(1);
  8845. SST.push(p.read_shift(cnt, 'cstr'));
  8846. }
  8847. } break;
  8848. case 0x0408: { /* FORMULAE */
  8849. //p.l += 12;
  8850. //while(p.l < p.length) {
  8851. // cnt = p.read_shift(2);
  8852. // formulae.push(p.slice(p.l, p.l + cnt + 1)); p.l += cnt + 1;
  8853. //}
  8854. } break;
  8855. case 0x0601: { /* BOS */
  8856. var sidx = p.read_shift(2);
  8857. s = ((o.dense ? [] : {}));
  8858. range.s.c = p.read_shift(2);
  8859. range.e.c = p.read_shift(2);
  8860. range.s.r = p.read_shift(4);
  8861. range.e.r = p.read_shift(4);
  8862. p.l += 4;
  8863. if(p.l + 2 < p.length) {
  8864. cnt = p.read_shift(2);
  8865. type = p.read_shift(1);
  8866. sname = cnt == 0 ? "" : p.read_shift(cnt, 'cstr');
  8867. }
  8868. if(!sname) sname = encode_col(sidx);
  8869. /* TODO: backfill empty sheets */
  8870. } break;
  8871. case 0x0602: { /* EOS */
  8872. /* NOTE: QP valid range A1:IV1000000 */
  8873. if(range.s.c > 0xFF || range.s.r > 999999) break;
  8874. if(range.e.c < range.s.c) range.e.c = range.s.c;
  8875. if(range.e.r < range.s.r) range.e.r = range.s.r;
  8876. s["!ref"] = encode_range(range);
  8877. book_append_sheet(wb, s, sname); // TODO: a barrel roll
  8878. } break;
  8879. case 0x0A01: { /* COL (like XLS Row, modulo the layout transposition) */
  8880. C = p.read_shift(2);
  8881. if(range.e.c < C) range.e.c = C;
  8882. if(range.s.c > C) range.s.c = C;
  8883. R = p.read_shift(4);
  8884. if(range.s.r > R) range.s.r = R;
  8885. R = p.read_shift(4);
  8886. if(range.e.r < R) range.e.r = R;
  8887. } break;
  8888. case 0x0C01: { /* MulCells (like XLS MulRK, but takes advantage of common column data patterns) */
  8889. R = p.read_shift(4), cnt = p.read_shift(4);
  8890. if(range.s.r > R) range.s.r = R;
  8891. if(range.e.r < R + cnt - 1) range.e.r = R + cnt - 1;
  8892. while(p.l < p.length) {
  8893. var cell = { t: "z" };
  8894. var flags = p.read_shift(1);
  8895. if(flags & 0x80) p.l += 2;
  8896. var mul = (flags & 0x40) ? p.read_shift(2) - 1: 0;
  8897. switch(flags & 0x1F) {
  8898. case 1: break;
  8899. case 2: cell = { t: "n", v: p.read_shift(2) }; break;
  8900. case 3: cell = { t: "n", v: p.read_shift(2, 'i') }; break;
  8901. case 5: cell = { t: "n", v: p.read_shift(8, 'f') }; break;
  8902. case 7: cell = { t: "s", v: SST[type = p.read_shift(4) - 1] }; break;
  8903. case 8: cell = { t: "n", v: p.read_shift(8, 'f') }; p.l += 2; /* cell.f = formulae[p.read_shift(4)]; */ p.l += 4; break;
  8904. default: throw "Unrecognized QPW cell type " + (flags & 0x1F);
  8905. }
  8906. var delta = 0;
  8907. if(flags & 0x20) switch(flags & 0x1F) {
  8908. case 2: delta = p.read_shift(2); break;
  8909. case 3: delta = p.read_shift(2, 'i'); break;
  8910. case 7: delta = p.read_shift(2); break;
  8911. default: throw "Unsupported delta for QPW cell type " + (flags & 0x1F);
  8912. }
  8913. if(!(!o.sheetStubs && cell.t == "z")) {
  8914. if(Array.isArray(s)) {
  8915. if(!s[R]) s[R] = [];
  8916. s[R][C] = cell;
  8917. } else s[encode_cell({r:R, c:C})] = cell;
  8918. }
  8919. ++R; --cnt;
  8920. while(mul-- > 0 && cnt >= 0) {
  8921. if(flags & 0x20) switch(flags & 0x1F) {
  8922. case 2: cell = { t: "n", v: (cell.v + delta) & 0xFFFF }; break;
  8923. case 3: cell = { t: "n", v: (cell.v + delta) & 0xFFFF }; if(cell.v > 0x7FFF) cell.v -= 0x10000; break;
  8924. case 7: cell = { t: "s", v: SST[type = (type + delta) >>> 0] }; break;
  8925. default: throw "Cannot apply delta for QPW cell type " + (flags & 0x1F);
  8926. } else switch(flags & 0x1F) {
  8927. case 1: cell = { t: "z" }; break;
  8928. case 2: cell = { t: "n", v: p.read_shift(2) }; break;
  8929. case 7: cell = { t: "s", v: SST[type = p.read_shift(4) - 1] }; break;
  8930. default: throw "Cannot apply repeat for QPW cell type " + (flags & 0x1F);
  8931. }
  8932. if(!(!o.sheetStubs && cell.t == "z")) {
  8933. if(Array.isArray(s)) {
  8934. if(!s[R]) s[R] = [];
  8935. s[R][C] = cell;
  8936. } else s[encode_cell({r:R, c:C})] = cell;
  8937. }
  8938. ++R; --cnt;
  8939. }
  8940. }
  8941. } break;
  8942. default: break;
  8943. }
  8944. d.l += length;
  8945. }
  8946. return wb;
  8947. }
  8948. return {
  8949. sheet_to_wk1: sheet_to_wk1,
  8950. book_to_wk3: book_to_wk3,
  8951. to_workbook: lotus_to_workbook
  8952. };
  8953. })();
  8954. /* 18.4.7 rPr CT_RPrElt */
  8955. function parse_rpr(rpr) {
  8956. var font = {}, m = rpr.match(tagregex), i = 0;
  8957. var pass = false;
  8958. if(m) for(;i!=m.length; ++i) {
  8959. var y = parsexmltag(m[i]);
  8960. switch(y[0].replace(/\w*:/g,"")) {
  8961. /* 18.8.12 condense CT_BooleanProperty */
  8962. /* ** not required . */
  8963. case '<condense': break;
  8964. /* 18.8.17 extend CT_BooleanProperty */
  8965. /* ** not required . */
  8966. case '<extend': break;
  8967. /* 18.8.36 shadow CT_BooleanProperty */
  8968. /* ** not required . */
  8969. case '<shadow':
  8970. if(!y.val) break;
  8971. /* falls through */
  8972. case '<shadow>':
  8973. case '<shadow/>': font.shadow = 1; break;
  8974. case '</shadow>': break;
  8975. /* 18.4.1 charset CT_IntProperty TODO */
  8976. case '<charset':
  8977. if(y.val == '1') break;
  8978. font.cp = CS2CP[parseInt(y.val, 10)];
  8979. break;
  8980. /* 18.4.2 outline CT_BooleanProperty TODO */
  8981. case '<outline':
  8982. if(!y.val) break;
  8983. /* falls through */
  8984. case '<outline>':
  8985. case '<outline/>': font.outline = 1; break;
  8986. case '</outline>': break;
  8987. /* 18.4.5 rFont CT_FontName */
  8988. case '<rFont': font.name = y.val; break;
  8989. /* 18.4.11 sz CT_FontSize */
  8990. case '<sz': font.sz = y.val; break;
  8991. /* 18.4.10 strike CT_BooleanProperty */
  8992. case '<strike':
  8993. if(!y.val) break;
  8994. /* falls through */
  8995. case '<strike>':
  8996. case '<strike/>': font.strike = 1; break;
  8997. case '</strike>': break;
  8998. /* 18.4.13 u CT_UnderlineProperty */
  8999. case '<u':
  9000. if(!y.val) break;
  9001. switch(y.val) {
  9002. case 'double': font.uval = "double"; break;
  9003. case 'singleAccounting': font.uval = "single-accounting"; break;
  9004. case 'doubleAccounting': font.uval = "double-accounting"; break;
  9005. }
  9006. /* falls through */
  9007. case '<u>':
  9008. case '<u/>': font.u = 1; break;
  9009. case '</u>': break;
  9010. /* 18.8.2 b */
  9011. case '<b':
  9012. if(y.val == '0') break;
  9013. /* falls through */
  9014. case '<b>':
  9015. case '<b/>': font.b = 1; break;
  9016. case '</b>': break;
  9017. /* 18.8.26 i */
  9018. case '<i':
  9019. if(y.val == '0') break;
  9020. /* falls through */
  9021. case '<i>':
  9022. case '<i/>': font.i = 1; break;
  9023. case '</i>': break;
  9024. /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
  9025. case '<color':
  9026. if(y.rgb) font.color = y.rgb.slice(2,8);
  9027. break;
  9028. case '<color>': case '<color/>': case '</color>': break;
  9029. /* 18.8.18 family ST_FontFamily */
  9030. case '<family': font.family = y.val; break;
  9031. case '<family>': case '<family/>': case '</family>': break;
  9032. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
  9033. case '<vertAlign': font.valign = y.val; break;
  9034. case '<vertAlign>': case '<vertAlign/>': case '</vertAlign>': break;
  9035. /* 18.8.35 scheme CT_FontScheme TODO */
  9036. case '<scheme': break;
  9037. case '<scheme>': case '<scheme/>': case '</scheme>': break;
  9038. /* 18.2.10 extLst CT_ExtensionList ? */
  9039. case '<extLst': case '<extLst>': case '</extLst>': break;
  9040. case '<ext': pass = true; break;
  9041. case '</ext>': pass = false; break;
  9042. default:
  9043. if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
  9044. }
  9045. }
  9046. return font;
  9047. }
  9048. var parse_rs = (function() {
  9049. var tregex = matchtag("t"), rpregex = matchtag("rPr");
  9050. /* 18.4.4 r CT_RElt */
  9051. function parse_r(r) {
  9052. /* 18.4.12 t ST_Xstring */
  9053. var t = r.match(tregex)/*, cp = 65001*/;
  9054. if(!t) return {t:"s", v:""};
  9055. var o = ({t:'s', v:unescapexml(t[1])});
  9056. var rpr = r.match(rpregex);
  9057. if(rpr) o.s = parse_rpr(rpr[1]);
  9058. return o;
  9059. }
  9060. var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  9061. return function parse_rs(rs) {
  9062. return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
  9063. };
  9064. })();
  9065. /* Parse a list of <r> tags */
  9066. var rs_to_html = (function parse_rs_factory() {
  9067. var nlregex = /(\r\n|\n)/g;
  9068. function parse_rpr2(font, intro, outro) {
  9069. var style = [];
  9070. if(font.u) style.push("text-decoration: underline;");
  9071. if(font.uval) style.push("text-underline-style:" + font.uval + ";");
  9072. if(font.sz) style.push("font-size:" + font.sz + "pt;");
  9073. if(font.outline) style.push("text-effect: outline;");
  9074. if(font.shadow) style.push("text-shadow: auto;");
  9075. intro.push('<span style="' + style.join("") + '">');
  9076. if(font.b) { intro.push("<b>"); outro.push("</b>"); }
  9077. if(font.i) { intro.push("<i>"); outro.push("</i>"); }
  9078. if(font.strike) { intro.push("<s>"); outro.push("</s>"); }
  9079. var align = font.valign || "";
  9080. if(align == "superscript" || align == "super") align = "sup";
  9081. else if(align == "subscript") align = "sub";
  9082. if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }
  9083. outro.push("</span>");
  9084. return font;
  9085. }
  9086. /* 18.4.4 r CT_RElt */
  9087. function r_to_html(r) {
  9088. var terms = [[],r.v,[]];
  9089. if(!r.v) return "";
  9090. if(r.s) parse_rpr2(r.s, terms[0], terms[2]);
  9091. return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
  9092. }
  9093. return function parse_rs(rs) {
  9094. return rs.map(r_to_html).join("");
  9095. };
  9096. })();
  9097. /* 18.4.8 si CT_Rst */
  9098. var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
  9099. var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
  9100. function parse_si(x, opts) {
  9101. var html = opts ? opts.cellHTML : true;
  9102. var z = {};
  9103. if(!x) return { t: "" };
  9104. //var y;
  9105. /* 18.4.12 t ST_Xstring (Plaintext String) */
  9106. // TODO: is whitespace actually valid here?
  9107. if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
  9108. z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""), true);
  9109. z.r = utf8read(x);
  9110. if(html) z.h = escapehtml(z.t);
  9111. }
  9112. /* 18.4.4 r CT_RElt (Rich Text Run) */
  9113. else if((/*y = */x.match(sirregex))) {
  9114. z.r = utf8read(x);
  9115. z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")), true);
  9116. if(html) z.h = rs_to_html(parse_rs(z.r));
  9117. }
  9118. /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
  9119. /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
  9120. return z;
  9121. }
  9122. /* 18.4 Shared String Table */
  9123. var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
  9124. var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
  9125. var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
  9126. function parse_sst_xml(data, opts) {
  9127. var s = ([]), ss = "";
  9128. if(!data) return s;
  9129. /* 18.4.9 sst CT_Sst */
  9130. var sst = data.match(sstr0);
  9131. if(sst) {
  9132. ss = sst[2].replace(sstr1,"").split(sstr2);
  9133. for(var i = 0; i != ss.length; ++i) {
  9134. var o = parse_si(ss[i].trim(), opts);
  9135. if(o != null) s[s.length] = o;
  9136. }
  9137. sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
  9138. }
  9139. return s;
  9140. }
  9141. var straywsregex = /^\s|\s$|[\t\n\r]/;
  9142. function write_sst_xml(sst, opts) {
  9143. if(!opts.bookSST) return "";
  9144. var o = [XML_HEADER];
  9145. o[o.length] = (writextag('sst', null, {
  9146. xmlns: XMLNS_main[0],
  9147. count: sst.Count,
  9148. uniqueCount: sst.Unique
  9149. }));
  9150. for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
  9151. var s = sst[i];
  9152. var sitag = "<si>";
  9153. if(s.r) sitag += s.r;
  9154. else {
  9155. sitag += "<t";
  9156. if(!s.t) s.t = "";
  9157. if(typeof s.t !== "string") s.t = String(s.t);
  9158. if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
  9159. sitag += ">" + escapexml(s.t) + "</t>";
  9160. }
  9161. sitag += "</si>";
  9162. o[o.length] = (sitag);
  9163. }
  9164. if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
  9165. return o.join("");
  9166. }
  9167. /* [MS-XLSB] 2.4.221 BrtBeginSst */
  9168. function parse_BrtBeginSst(data) {
  9169. return [data.read_shift(4), data.read_shift(4)];
  9170. }
  9171. /* [MS-XLSB] 2.1.7.45 Shared Strings */
  9172. function parse_sst_bin(data, opts) {
  9173. var s = ([]);
  9174. var pass = false;
  9175. recordhopper(data, function hopper_sst(val, R, RT) {
  9176. switch(RT) {
  9177. case 0x009F: /* BrtBeginSst */
  9178. s.Count = val[0]; s.Unique = val[1]; break;
  9179. case 0x0013: /* BrtSSTItem */
  9180. s.push(val); break;
  9181. case 0x00A0: /* BrtEndSst */
  9182. return true;
  9183. case 0x0023: /* BrtFRTBegin */
  9184. pass = true; break;
  9185. case 0x0024: /* BrtFRTEnd */
  9186. pass = false; break;
  9187. default:
  9188. if(R.T){}
  9189. if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  9190. }
  9191. });
  9192. return s;
  9193. }
  9194. function write_BrtBeginSst(sst, o) {
  9195. if(!o) o = new_buf(8);
  9196. o.write_shift(4, sst.Count);
  9197. o.write_shift(4, sst.Unique);
  9198. return o;
  9199. }
  9200. var write_BrtSSTItem = write_RichStr;
  9201. function write_sst_bin(sst) {
  9202. var ba = buf_array();
  9203. write_record(ba, 0x009F /* BrtBeginSst */, write_BrtBeginSst(sst));
  9204. for(var i = 0; i < sst.length; ++i) write_record(ba, 0x0013 /* BrtSSTItem */, write_BrtSSTItem(sst[i]));
  9205. /* FRTSST */
  9206. write_record(ba, 0x00A0 /* BrtEndSst */);
  9207. return ba.end();
  9208. }
  9209. function _JS2ANSI(str) {
  9210. if(typeof $cptable !== 'undefined') return $cptable.utils.encode(current_ansi, str);
  9211. var o = [], oo = str.split("");
  9212. for(var i = 0; i < oo.length; ++i) o[i] = oo[i].charCodeAt(0);
  9213. return o;
  9214. }
  9215. /* [MS-OFFCRYPTO] 2.1.4 Version */
  9216. function parse_CRYPTOVersion(blob, length) {
  9217. var o = {};
  9218. o.Major = blob.read_shift(2);
  9219. o.Minor = blob.read_shift(2);
  9220. if(length >= 4) blob.l += length - 4;
  9221. return o;
  9222. }
  9223. /* [MS-OFFCRYPTO] 2.1.5 DataSpaceVersionInfo */
  9224. function parse_DataSpaceVersionInfo(blob) {
  9225. var o = {};
  9226. o.id = blob.read_shift(0, 'lpp4');
  9227. o.R = parse_CRYPTOVersion(blob, 4);
  9228. o.U = parse_CRYPTOVersion(blob, 4);
  9229. o.W = parse_CRYPTOVersion(blob, 4);
  9230. return o;
  9231. }
  9232. /* [MS-OFFCRYPTO] 2.1.6.1 DataSpaceMapEntry Structure */
  9233. function parse_DataSpaceMapEntry(blob) {
  9234. var len = blob.read_shift(4);
  9235. var end = blob.l + len - 4;
  9236. var o = {};
  9237. var cnt = blob.read_shift(4);
  9238. var comps = [];
  9239. /* [MS-OFFCRYPTO] 2.1.6.2 DataSpaceReferenceComponent Structure */
  9240. while(cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, 'lpp4') });
  9241. o.name = blob.read_shift(0, 'lpp4');
  9242. o.comps = comps;
  9243. if(blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
  9244. return o;
  9245. }
  9246. /* [MS-OFFCRYPTO] 2.1.6 DataSpaceMap */
  9247. function parse_DataSpaceMap(blob) {
  9248. var o = [];
  9249. blob.l += 4; // must be 0x8
  9250. var cnt = blob.read_shift(4);
  9251. while(cnt-- > 0) o.push(parse_DataSpaceMapEntry(blob));
  9252. return o;
  9253. }
  9254. /* [MS-OFFCRYPTO] 2.1.7 DataSpaceDefinition */
  9255. function parse_DataSpaceDefinition(blob) {
  9256. var o = [];
  9257. blob.l += 4; // must be 0x8
  9258. var cnt = blob.read_shift(4);
  9259. while(cnt-- > 0) o.push(blob.read_shift(0, 'lpp4'));
  9260. return o;
  9261. }
  9262. /* [MS-OFFCRYPTO] 2.1.8 DataSpaceDefinition */
  9263. function parse_TransformInfoHeader(blob) {
  9264. var o = {};
  9265. /*var len = */blob.read_shift(4);
  9266. blob.l += 4; // must be 0x1
  9267. o.id = blob.read_shift(0, 'lpp4');
  9268. o.name = blob.read_shift(0, 'lpp4');
  9269. o.R = parse_CRYPTOVersion(blob, 4);
  9270. o.U = parse_CRYPTOVersion(blob, 4);
  9271. o.W = parse_CRYPTOVersion(blob, 4);
  9272. return o;
  9273. }
  9274. function parse_Primary(blob) {
  9275. /* [MS-OFFCRYPTO] 2.2.6 IRMDSTransformInfo */
  9276. var hdr = parse_TransformInfoHeader(blob);
  9277. /* [MS-OFFCRYPTO] 2.1.9 EncryptionTransformInfo */
  9278. hdr.ename = blob.read_shift(0, '8lpp4');
  9279. hdr.blksz = blob.read_shift(4);
  9280. hdr.cmode = blob.read_shift(4);
  9281. if(blob.read_shift(4) != 0x04) throw new Error("Bad !Primary record");
  9282. return hdr;
  9283. }
  9284. /* [MS-OFFCRYPTO] 2.3.2 Encryption Header */
  9285. function parse_EncryptionHeader(blob, length) {
  9286. var tgt = blob.l + length;
  9287. var o = {};
  9288. o.Flags = (blob.read_shift(4) & 0x3F);
  9289. blob.l += 4;
  9290. o.AlgID = blob.read_shift(4);
  9291. var valid = false;
  9292. switch(o.AlgID) {
  9293. case 0x660E: case 0x660F: case 0x6610: valid = (o.Flags == 0x24); break;
  9294. case 0x6801: valid = (o.Flags == 0x04); break;
  9295. case 0: valid = (o.Flags == 0x10 || o.Flags == 0x04 || o.Flags == 0x24); break;
  9296. default: throw 'Unrecognized encryption algorithm: ' + o.AlgID;
  9297. }
  9298. if(!valid) throw new Error("Encryption Flags/AlgID mismatch");
  9299. o.AlgIDHash = blob.read_shift(4);
  9300. o.KeySize = blob.read_shift(4);
  9301. o.ProviderType = blob.read_shift(4);
  9302. blob.l += 8;
  9303. o.CSPName = blob.read_shift((tgt-blob.l)>>1, 'utf16le');
  9304. blob.l = tgt;
  9305. return o;
  9306. }
  9307. /* [MS-OFFCRYPTO] 2.3.3 Encryption Verifier */
  9308. function parse_EncryptionVerifier(blob, length) {
  9309. var o = {}, tgt = blob.l + length;
  9310. blob.l += 4; // SaltSize must be 0x10
  9311. o.Salt = blob.slice(blob.l, blob.l+16); blob.l += 16;
  9312. o.Verifier = blob.slice(blob.l, blob.l+16); blob.l += 16;
  9313. /*var sz = */blob.read_shift(4);
  9314. o.VerifierHash = blob.slice(blob.l, tgt); blob.l = tgt;
  9315. return o;
  9316. }
  9317. /* [MS-OFFCRYPTO] 2.3.4.* EncryptionInfo Stream */
  9318. function parse_EncryptionInfo(blob) {
  9319. var vers = parse_CRYPTOVersion(blob);
  9320. switch(vers.Minor) {
  9321. case 0x02: return [vers.Minor, parse_EncInfoStd(blob, vers)];
  9322. case 0x03: return [vers.Minor, parse_EncInfoExt(blob, vers)];
  9323. case 0x04: return [vers.Minor, parse_EncInfoAgl(blob, vers)];
  9324. }
  9325. throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
  9326. }
  9327. /* [MS-OFFCRYPTO] 2.3.4.5 EncryptionInfo Stream (Standard Encryption) */
  9328. function parse_EncInfoStd(blob) {
  9329. var flags = blob.read_shift(4);
  9330. if((flags & 0x3F) != 0x24) throw new Error("EncryptionInfo mismatch");
  9331. var sz = blob.read_shift(4);
  9332. //var tgt = blob.l + sz;
  9333. var hdr = parse_EncryptionHeader(blob, sz);
  9334. var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
  9335. return { t:"Std", h:hdr, v:verifier };
  9336. }
  9337. /* [MS-OFFCRYPTO] 2.3.4.6 EncryptionInfo Stream (Extensible Encryption) */
  9338. function parse_EncInfoExt() { throw new Error("File is password-protected: ECMA-376 Extensible"); }
  9339. /* [MS-OFFCRYPTO] 2.3.4.10 EncryptionInfo Stream (Agile Encryption) */
  9340. function parse_EncInfoAgl(blob) {
  9341. var KeyData = ["saltSize","blockSize","keyBits","hashSize","cipherAlgorithm","cipherChaining","hashAlgorithm","saltValue"];
  9342. blob.l+=4;
  9343. var xml = blob.read_shift(blob.length - blob.l, 'utf8');
  9344. var o = {};
  9345. xml.replace(tagregex, function xml_agile(x) {
  9346. var y = parsexmltag(x);
  9347. switch(strip_ns(y[0])) {
  9348. case '<?xml': break;
  9349. case '<encryption': case '</encryption>': break;
  9350. case '<keyData': KeyData.forEach(function(k) { o[k] = y[k]; }); break;
  9351. case '<dataIntegrity': o.encryptedHmacKey = y.encryptedHmacKey; o.encryptedHmacValue = y.encryptedHmacValue; break;
  9352. case '<keyEncryptors>': case '<keyEncryptors': o.encs = []; break;
  9353. case '</keyEncryptors>': break;
  9354. case '<keyEncryptor': o.uri = y.uri; break;
  9355. case '</keyEncryptor>': break;
  9356. case '<encryptedKey': o.encs.push(y); break;
  9357. default: throw y[0];
  9358. }
  9359. });
  9360. return o;
  9361. }
  9362. /* [MS-OFFCRYPTO] 2.3.5.1 RC4 CryptoAPI Encryption Header */
  9363. function parse_RC4CryptoHeader(blob, length) {
  9364. var o = {};
  9365. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); length -= 4;
  9366. if(vers.Minor != 2) throw new Error('unrecognized minor version code: ' + vers.Minor);
  9367. if(vers.Major > 4 || vers.Major < 2) throw new Error('unrecognized major version code: ' + vers.Major);
  9368. o.Flags = blob.read_shift(4); length -= 4;
  9369. var sz = blob.read_shift(4); length -= 4;
  9370. o.EncryptionHeader = parse_EncryptionHeader(blob, sz); length -= sz;
  9371. o.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
  9372. return o;
  9373. }
  9374. /* [MS-OFFCRYPTO] 2.3.6.1 RC4 Encryption Header */
  9375. function parse_RC4Header(blob) {
  9376. var o = {};
  9377. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
  9378. if(vers.Major != 1 || vers.Minor != 1) throw 'unrecognized version code ' + vers.Major + ' : ' + vers.Minor;
  9379. o.Salt = blob.read_shift(16);
  9380. o.EncryptedVerifier = blob.read_shift(16);
  9381. o.EncryptedVerifierHash = blob.read_shift(16);
  9382. return o;
  9383. }
  9384. /* [MS-OFFCRYPTO] 2.3.7.1 Binary Document Password Verifier Derivation */
  9385. function crypto_CreatePasswordVerifier_Method1(Password) {
  9386. var Verifier = 0x0000, PasswordArray;
  9387. var PasswordDecoded = _JS2ANSI(Password);
  9388. var len = PasswordDecoded.length + 1, i, PasswordByte;
  9389. var Intermediate1, Intermediate2, Intermediate3;
  9390. PasswordArray = new_raw_buf(len);
  9391. PasswordArray[0] = PasswordDecoded.length;
  9392. for(i = 1; i != len; ++i) PasswordArray[i] = PasswordDecoded[i-1];
  9393. for(i = len-1; i >= 0; --i) {
  9394. PasswordByte = PasswordArray[i];
  9395. Intermediate1 = ((Verifier & 0x4000) === 0x0000) ? 0 : 1;
  9396. Intermediate2 = (Verifier << 1) & 0x7FFF;
  9397. Intermediate3 = Intermediate1 | Intermediate2;
  9398. Verifier = Intermediate3 ^ PasswordByte;
  9399. }
  9400. return Verifier ^ 0xCE4B;
  9401. }
  9402. /* [MS-OFFCRYPTO] 2.3.7.2 Binary Document XOR Array Initialization */
  9403. var crypto_CreateXorArray_Method1 = (function() {
  9404. var PadArray = [0xBB, 0xFF, 0xFF, 0xBA, 0xFF, 0xFF, 0xB9, 0x80, 0x00, 0xBE, 0x0F, 0x00, 0xBF, 0x0F, 0x00];
  9405. var InitialCode = [0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3];
  9406. var XorMatrix = [0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09, 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF, 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0, 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40, 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5, 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A, 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9, 0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0, 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC, 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10, 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168, 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C, 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD, 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC, 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4];
  9407. var Ror = function(Byte) { return ((Byte/2) | (Byte*128)) & 0xFF; };
  9408. var XorRor = function(byte1, byte2) { return Ror(byte1 ^ byte2); };
  9409. var CreateXorKey_Method1 = function(Password) {
  9410. var XorKey = InitialCode[Password.length - 1];
  9411. var CurrentElement = 0x68;
  9412. for(var i = Password.length-1; i >= 0; --i) {
  9413. var Char = Password[i];
  9414. for(var j = 0; j != 7; ++j) {
  9415. if(Char & 0x40) XorKey ^= XorMatrix[CurrentElement];
  9416. Char *= 2; --CurrentElement;
  9417. }
  9418. }
  9419. return XorKey;
  9420. };
  9421. return function(password) {
  9422. var Password = _JS2ANSI(password);
  9423. var XorKey = CreateXorKey_Method1(Password);
  9424. var Index = Password.length;
  9425. var ObfuscationArray = new_raw_buf(16);
  9426. for(var i = 0; i != 16; ++i) ObfuscationArray[i] = 0x00;
  9427. var Temp, PasswordLastChar, PadIndex;
  9428. if((Index & 1) === 1) {
  9429. Temp = XorKey >> 8;
  9430. ObfuscationArray[Index] = XorRor(PadArray[0], Temp);
  9431. --Index;
  9432. Temp = XorKey & 0xFF;
  9433. PasswordLastChar = Password[Password.length - 1];
  9434. ObfuscationArray[Index] = XorRor(PasswordLastChar, Temp);
  9435. }
  9436. while(Index > 0) {
  9437. --Index;
  9438. Temp = XorKey >> 8;
  9439. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  9440. --Index;
  9441. Temp = XorKey & 0xFF;
  9442. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  9443. }
  9444. Index = 15;
  9445. PadIndex = 15 - Password.length;
  9446. while(PadIndex > 0) {
  9447. Temp = XorKey >> 8;
  9448. ObfuscationArray[Index] = XorRor(PadArray[PadIndex], Temp);
  9449. --Index;
  9450. --PadIndex;
  9451. Temp = XorKey & 0xFF;
  9452. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  9453. --Index;
  9454. --PadIndex;
  9455. }
  9456. return ObfuscationArray;
  9457. };
  9458. })();
  9459. /* [MS-OFFCRYPTO] 2.3.7.3 Binary Document XOR Data Transformation Method 1 */
  9460. var crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O) {
  9461. /* If XorArray is set, use it; if O is not set, make changes in-place */
  9462. if(!O) O = Data;
  9463. if(!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
  9464. var Index, Value;
  9465. for(Index = 0; Index != Data.length; ++Index) {
  9466. Value = Data[Index];
  9467. Value ^= XorArray[XorArrayIndex];
  9468. Value = ((Value>>5) | (Value<<3)) & 0xFF;
  9469. O[Index] = Value;
  9470. ++XorArrayIndex;
  9471. }
  9472. return [O, XorArrayIndex, XorArray];
  9473. };
  9474. var crypto_MakeXorDecryptor = function(password) {
  9475. var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
  9476. return function(Data) {
  9477. var O = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
  9478. XorArrayIndex = O[1];
  9479. return O[0];
  9480. };
  9481. };
  9482. /* 2.5.343 */
  9483. function parse_XORObfuscation(blob, length, opts, out) {
  9484. var o = ({ key: parseuint16(blob), verificationBytes: parseuint16(blob) });
  9485. if(opts.password) o.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
  9486. out.valid = o.verificationBytes === o.verifier;
  9487. if(out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
  9488. return o;
  9489. }
  9490. /* 2.4.117 */
  9491. function parse_FilePassHeader(blob, length, oo) {
  9492. var o = oo || {}; o.Info = blob.read_shift(2); blob.l -= 2;
  9493. if(o.Info === 1) o.Data = parse_RC4Header(blob, length);
  9494. else o.Data = parse_RC4CryptoHeader(blob, length);
  9495. return o;
  9496. }
  9497. function parse_FilePass(blob, length, opts) {
  9498. var o = ({ Type: opts.biff >= 8 ? blob.read_shift(2) : 0 }); /* wEncryptionType */
  9499. if(o.Type) parse_FilePassHeader(blob, length-2, o);
  9500. else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o);
  9501. return o;
  9502. }
  9503. function rtf_to_sheet(d, opts) {
  9504. switch (opts.type) {
  9505. case "base64":
  9506. return rtf_to_sheet_str(Base64_decode(d), opts);
  9507. case "binary":
  9508. return rtf_to_sheet_str(d, opts);
  9509. case "buffer":
  9510. return rtf_to_sheet_str(has_buf && Buffer.isBuffer(d) ? d.toString("binary") : a2s(d), opts);
  9511. case "array":
  9512. return rtf_to_sheet_str(cc2str(d), opts);
  9513. }
  9514. throw new Error("Unrecognized type " + opts.type);
  9515. }
  9516. function rtf_to_sheet_str(str, opts) {
  9517. var o = opts || {};
  9518. var ws = o.dense ? [] : {};
  9519. var rows = str.match(/\\trowd[\s\S]*?\\row\b/g);
  9520. if (!rows)
  9521. throw new Error("RTF missing table");
  9522. var range = { s: { c: 0, r: 0 }, e: { c: 0, r: rows.length - 1 } };
  9523. rows.forEach(function(rowtf, R) {
  9524. if (Array.isArray(ws))
  9525. ws[R] = [];
  9526. var rtfre = /\\[\w\-]+\b/g;
  9527. var last_index = 0;
  9528. var res;
  9529. var C = -1;
  9530. var payload = [];
  9531. while ((res = rtfre.exec(rowtf)) != null) {
  9532. var data = rowtf.slice(last_index, rtfre.lastIndex - res[0].length);
  9533. if (data.charCodeAt(0) == 32)
  9534. data = data.slice(1);
  9535. if (data.length)
  9536. payload.push(data);
  9537. switch (res[0]) {
  9538. case "\\cell":
  9539. ++C;
  9540. if (payload.length) {
  9541. var cell = { v: payload.join(""), t: "s" };
  9542. if (cell.v == "TRUE" || cell.v == "FALSE") {
  9543. cell.v = cell.v == "TRUE";
  9544. cell.t = "b";
  9545. } else if (!isNaN(fuzzynum(cell.v))) {
  9546. cell.t = "n";
  9547. if (o.cellText !== false)
  9548. cell.w = cell.v;
  9549. cell.v = fuzzynum(cell.v);
  9550. }
  9551. if (Array.isArray(ws))
  9552. ws[R][C] = cell;
  9553. else
  9554. ws[encode_cell({ r: R, c: C })] = cell;
  9555. }
  9556. payload = [];
  9557. break;
  9558. case "\\par":
  9559. payload.push("\n");
  9560. break;
  9561. }
  9562. last_index = rtfre.lastIndex;
  9563. }
  9564. if (C > range.e.c)
  9565. range.e.c = C;
  9566. });
  9567. ws["!ref"] = encode_range(range);
  9568. return ws;
  9569. }
  9570. function rtf_to_workbook(d, opts) {
  9571. var wb = sheet_to_workbook(rtf_to_sheet(d, opts), opts);
  9572. wb.bookType = "rtf";
  9573. return wb;
  9574. }
  9575. function sheet_to_rtf(ws, opts) {
  9576. var o = ["{\\rtf1\\ansi"];
  9577. if (!ws["!ref"])
  9578. return o[0] + "}";
  9579. var r = safe_decode_range(ws["!ref"]), cell;
  9580. var dense = Array.isArray(ws);
  9581. for (var R = r.s.r; R <= r.e.r; ++R) {
  9582. o.push("\\trowd\\trautofit1");
  9583. for (var C = r.s.c; C <= r.e.c; ++C)
  9584. o.push("\\cellx" + (C + 1));
  9585. o.push("\\pard\\intbl");
  9586. for (C = r.s.c; C <= r.e.c; ++C) {
  9587. var coord = encode_cell({ r: R, c: C });
  9588. cell = dense ? (ws[R] || [])[C] : ws[coord];
  9589. if (!cell || cell.v == null && (!cell.f || cell.F)) {
  9590. o.push(" \\cell");
  9591. continue;
  9592. }
  9593. o.push(" " + (cell.w || (format_cell(cell), cell.w) || "").replace(/[\r\n]/g, "\\par "));
  9594. o.push("\\cell");
  9595. }
  9596. o.push("\\pard\\intbl\\row");
  9597. }
  9598. return o.join("") + "}";
  9599. }
  9600. function hex2RGB(h) {
  9601. var o = h.slice(h[0]==="#"?1:0).slice(0,6);
  9602. return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
  9603. }
  9604. function rgb2Hex(rgb) {
  9605. for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
  9606. return o.toString(16).toUpperCase().slice(1);
  9607. }
  9608. function rgb2HSL(rgb) {
  9609. var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
  9610. var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
  9611. if(C === 0) return [0, 0, R];
  9612. var H6 = 0, S = 0, L2 = (M + m);
  9613. S = C / (L2 > 1 ? 2 - L2 : L2);
  9614. switch(M){
  9615. case R: H6 = ((G - B) / C + 6)%6; break;
  9616. case G: H6 = ((B - R) / C + 2); break;
  9617. case B: H6 = ((R - G) / C + 4); break;
  9618. }
  9619. return [H6 / 6, S, L2 / 2];
  9620. }
  9621. function hsl2RGB(hsl){
  9622. var H = hsl[0], S = hsl[1], L = hsl[2];
  9623. var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
  9624. var rgb = [m,m,m], h6 = 6*H;
  9625. var X;
  9626. if(S !== 0) switch(h6|0) {
  9627. case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
  9628. case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
  9629. case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
  9630. case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
  9631. case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
  9632. case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
  9633. }
  9634. for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
  9635. return rgb;
  9636. }
  9637. /* 18.8.3 bgColor tint algorithm */
  9638. function rgb_tint(hex, tint) {
  9639. if(tint === 0) return hex;
  9640. var hsl = rgb2HSL(hex2RGB(hex));
  9641. if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  9642. else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  9643. return rgb2Hex(hsl2RGB(hsl));
  9644. }
  9645. /* 18.3.1.13 width calculations */
  9646. /* [MS-OI29500] 2.1.595 Column Width & Formatting */
  9647. var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
  9648. function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
  9649. function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
  9650. function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
  9651. //function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
  9652. //function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
  9653. function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
  9654. /* XLSX/XLSB/XLS specify width in units of MDW */
  9655. function find_mdw_colw(collw) {
  9656. var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  9657. 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; }
  9658. MDW = _MDW;
  9659. }
  9660. /* XLML specifies width in terms of pixels */
  9661. /*function find_mdw_wpx(wpx) {
  9662. var delta = Infinity, guess = 0, _MDW = MIN_MDW;
  9663. for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
  9664. guess = char2width_(px2char_(wpx))*256;
  9665. guess = (guess) % 1;
  9666. if(guess > 0.5) guess--;
  9667. if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
  9668. }
  9669. MDW = _MDW;
  9670. }*/
  9671. function process_col(coll) {
  9672. if(coll.width) {
  9673. coll.wpx = width2px(coll.width);
  9674. coll.wch = px2char(coll.wpx);
  9675. coll.MDW = MDW;
  9676. } else if(coll.wpx) {
  9677. coll.wch = px2char(coll.wpx);
  9678. coll.width = char2width(coll.wch);
  9679. coll.MDW = MDW;
  9680. } else if(typeof coll.wch == 'number') {
  9681. coll.width = char2width(coll.wch);
  9682. coll.wpx = width2px(coll.width);
  9683. coll.MDW = MDW;
  9684. }
  9685. if(coll.customWidth) delete coll.customWidth;
  9686. }
  9687. var DEF_PPI = 96, PPI = DEF_PPI;
  9688. function px2pt(px) { return px * 96 / PPI; }
  9689. function pt2px(pt) { return pt * PPI / 96; }
  9690. /* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
  9691. var XLMLPatternTypeMap = {
  9692. "None": "none",
  9693. "Solid": "solid",
  9694. "Gray50": "mediumGray",
  9695. "Gray75": "darkGray",
  9696. "Gray25": "lightGray",
  9697. "HorzStripe": "darkHorizontal",
  9698. "VertStripe": "darkVertical",
  9699. "ReverseDiagStripe": "darkDown",
  9700. "DiagStripe": "darkUp",
  9701. "DiagCross": "darkGrid",
  9702. "ThickDiagCross": "darkTrellis",
  9703. "ThinHorzStripe": "lightHorizontal",
  9704. "ThinVertStripe": "lightVertical",
  9705. "ThinReverseDiagStripe": "lightDown",
  9706. "ThinHorzCross": "lightGrid"
  9707. };
  9708. /* 18.8.5 borders CT_Borders */
  9709. function parse_borders(t, styles, themes, opts) {
  9710. styles.Borders = [];
  9711. var border = {};
  9712. var pass = false;
  9713. (t[0].match(tagregex)||[]).forEach(function(x) {
  9714. var y = parsexmltag(x);
  9715. switch(strip_ns(y[0])) {
  9716. case '<borders': case '<borders>': case '</borders>': break;
  9717. /* 18.8.4 border CT_Border */
  9718. case '<border': case '<border>': case '<border/>':
  9719. border = {};
  9720. if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
  9721. if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
  9722. styles.Borders.push(border);
  9723. break;
  9724. case '</border>': break;
  9725. /* note: not in spec, appears to be CT_BorderPr */
  9726. case '<left/>': break;
  9727. case '<left': case '<left>': break;
  9728. case '</left>': break;
  9729. /* note: not in spec, appears to be CT_BorderPr */
  9730. case '<right/>': break;
  9731. case '<right': case '<right>': break;
  9732. case '</right>': break;
  9733. /* 18.8.43 top CT_BorderPr */
  9734. case '<top/>': break;
  9735. case '<top': case '<top>': break;
  9736. case '</top>': break;
  9737. /* 18.8.6 bottom CT_BorderPr */
  9738. case '<bottom/>': break;
  9739. case '<bottom': case '<bottom>': break;
  9740. case '</bottom>': break;
  9741. /* 18.8.13 diagonal CT_BorderPr */
  9742. case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
  9743. case '</diagonal>': break;
  9744. /* 18.8.25 horizontal CT_BorderPr */
  9745. case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
  9746. case '</horizontal>': break;
  9747. /* 18.8.44 vertical CT_BorderPr */
  9748. case '<vertical': case '<vertical>': case '<vertical/>': break;
  9749. case '</vertical>': break;
  9750. /* 18.8.37 start CT_BorderPr */
  9751. case '<start': case '<start>': case '<start/>': break;
  9752. case '</start>': break;
  9753. /* 18.8.16 end CT_BorderPr */
  9754. case '<end': case '<end>': case '<end/>': break;
  9755. case '</end>': break;
  9756. /* 18.8.? color CT_Color */
  9757. case '<color': case '<color>':
  9758. break;
  9759. case '<color/>': case '</color>': break;
  9760. /* 18.2.10 extLst CT_ExtensionList ? */
  9761. case '<extLst': case '<extLst>': case '</extLst>': break;
  9762. case '<ext': pass = true; break;
  9763. case '</ext>': pass = false; break;
  9764. default: if(opts && opts.WTF) {
  9765. if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
  9766. }
  9767. }
  9768. });
  9769. }
  9770. /* 18.8.21 fills CT_Fills */
  9771. function parse_fills(t, styles, themes, opts) {
  9772. styles.Fills = [];
  9773. var fill = {};
  9774. var pass = false;
  9775. (t[0].match(tagregex)||[]).forEach(function(x) {
  9776. var y = parsexmltag(x);
  9777. switch(strip_ns(y[0])) {
  9778. case '<fills': case '<fills>': case '</fills>': break;
  9779. /* 18.8.20 fill CT_Fill */
  9780. case '<fill>': case '<fill': case '<fill/>':
  9781. fill = {}; styles.Fills.push(fill); break;
  9782. case '</fill>': break;
  9783. /* 18.8.24 gradientFill CT_GradientFill */
  9784. case '<gradientFill>': break;
  9785. case '<gradientFill':
  9786. case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;
  9787. /* 18.8.32 patternFill CT_PatternFill */
  9788. case '<patternFill': case '<patternFill>':
  9789. if(y.patternType) fill.patternType = y.patternType;
  9790. break;
  9791. case '<patternFill/>': case '</patternFill>': break;
  9792. /* 18.8.3 bgColor CT_Color */
  9793. case '<bgColor':
  9794. if(!fill.bgColor) fill.bgColor = {};
  9795. if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
  9796. if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
  9797. if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
  9798. /* Excel uses ARGB strings */
  9799. if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
  9800. break;
  9801. case '<bgColor/>': case '</bgColor>': break;
  9802. /* 18.8.19 fgColor CT_Color */
  9803. case '<fgColor':
  9804. if(!fill.fgColor) fill.fgColor = {};
  9805. if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
  9806. if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
  9807. /* Excel uses ARGB strings */
  9808. if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
  9809. break;
  9810. case '<fgColor/>': case '</fgColor>': break;
  9811. /* 18.8.38 stop CT_GradientStop */
  9812. case '<stop': case '<stop/>': break;
  9813. case '</stop>': break;
  9814. /* 18.8.? color CT_Color */
  9815. case '<color': case '<color/>': break;
  9816. case '</color>': break;
  9817. /* 18.2.10 extLst CT_ExtensionList ? */
  9818. case '<extLst': case '<extLst>': case '</extLst>': break;
  9819. case '<ext': pass = true; break;
  9820. case '</ext>': pass = false; break;
  9821. default: if(opts && opts.WTF) {
  9822. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
  9823. }
  9824. }
  9825. });
  9826. }
  9827. /* 18.8.23 fonts CT_Fonts */
  9828. function parse_fonts(t, styles, themes, opts) {
  9829. styles.Fonts = [];
  9830. var font = {};
  9831. var pass = false;
  9832. (t[0].match(tagregex)||[]).forEach(function(x) {
  9833. var y = parsexmltag(x);
  9834. switch(strip_ns(y[0])) {
  9835. case '<fonts': case '<fonts>': case '</fonts>': break;
  9836. /* 18.8.22 font CT_Font */
  9837. case '<font': case '<font>': break;
  9838. case '</font>': case '<font/>':
  9839. styles.Fonts.push(font);
  9840. font = {};
  9841. break;
  9842. /* 18.8.29 name CT_FontName */
  9843. case '<name': if(y.val) font.name = utf8read(y.val); break;
  9844. case '<name/>': case '</name>': break;
  9845. /* 18.8.2 b CT_BooleanProperty */
  9846. case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
  9847. case '<b/>': font.bold = 1; break;
  9848. /* 18.8.26 i CT_BooleanProperty */
  9849. case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
  9850. case '<i/>': font.italic = 1; break;
  9851. /* 18.4.13 u CT_UnderlineProperty */
  9852. case '<u':
  9853. switch(y.val) {
  9854. case "none": font.underline = 0x00; break;
  9855. case "single": font.underline = 0x01; break;
  9856. case "double": font.underline = 0x02; break;
  9857. case "singleAccounting": font.underline = 0x21; break;
  9858. case "doubleAccounting": font.underline = 0x22; break;
  9859. } break;
  9860. case '<u/>': font.underline = 1; break;
  9861. /* 18.4.10 strike CT_BooleanProperty */
  9862. case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
  9863. case '<strike/>': font.strike = 1; break;
  9864. /* 18.4.2 outline CT_BooleanProperty */
  9865. case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
  9866. case '<outline/>': font.outline = 1; break;
  9867. /* 18.8.36 shadow CT_BooleanProperty */
  9868. case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
  9869. case '<shadow/>': font.shadow = 1; break;
  9870. /* 18.8.12 condense CT_BooleanProperty */
  9871. case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
  9872. case '<condense/>': font.condense = 1; break;
  9873. /* 18.8.17 extend CT_BooleanProperty */
  9874. case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
  9875. case '<extend/>': font.extend = 1; break;
  9876. /* 18.4.11 sz CT_FontSize */
  9877. case '<sz': if(y.val) font.sz = +y.val; break;
  9878. case '<sz/>': case '</sz>': break;
  9879. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
  9880. case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
  9881. case '<vertAlign/>': case '</vertAlign>': break;
  9882. /* 18.8.18 family CT_FontFamily */
  9883. case '<family': if(y.val) font.family = parseInt(y.val,10); break;
  9884. case '<family/>': case '</family>': break;
  9885. /* 18.8.35 scheme CT_FontScheme */
  9886. case '<scheme': if(y.val) font.scheme = y.val; break;
  9887. case '<scheme/>': case '</scheme>': break;
  9888. /* 18.4.1 charset CT_IntProperty */
  9889. case '<charset':
  9890. if(y.val == '1') break;
  9891. y.codepage = CS2CP[parseInt(y.val, 10)];
  9892. break;
  9893. /* 18.?.? color CT_Color */
  9894. case '<color':
  9895. if(!font.color) font.color = {};
  9896. if(y.auto) font.color.auto = parsexmlbool(y.auto);
  9897. if(y.rgb) font.color.rgb = y.rgb.slice(-6);
  9898. else if(y.indexed) {
  9899. font.color.index = parseInt(y.indexed, 10);
  9900. var icv = XLSIcv[font.color.index];
  9901. if(font.color.index == 81) icv = XLSIcv[1];
  9902. if(!icv) icv = XLSIcv[1]; //throw new Error(x); // note: 206 is valid
  9903. font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
  9904. } else if(y.theme) {
  9905. font.color.theme = parseInt(y.theme, 10);
  9906. if(y.tint) font.color.tint = parseFloat(y.tint);
  9907. if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
  9908. font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
  9909. }
  9910. }
  9911. break;
  9912. case '<color/>': case '</color>': break;
  9913. /* note: sometimes mc:AlternateContent appears bare */
  9914. case '<AlternateContent': pass = true; break;
  9915. case '</AlternateContent>': pass = false; break;
  9916. /* 18.2.10 extLst CT_ExtensionList ? */
  9917. case '<extLst': case '<extLst>': case '</extLst>': break;
  9918. case '<ext': pass = true; break;
  9919. case '</ext>': pass = false; break;
  9920. default: if(opts && opts.WTF) {
  9921. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
  9922. }
  9923. }
  9924. });
  9925. }
  9926. /* 18.8.31 numFmts CT_NumFmts */
  9927. function parse_numFmts(t, styles, opts) {
  9928. styles.NumberFmt = [];
  9929. var k/*Array<number>*/ = (keys(table_fmt));
  9930. for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = table_fmt[k[i]];
  9931. var m = t[0].match(tagregex);
  9932. if(!m) return;
  9933. for(i=0; i < m.length; ++i) {
  9934. var y = parsexmltag(m[i]);
  9935. switch(strip_ns(y[0])) {
  9936. case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
  9937. case '<numFmt': {
  9938. var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
  9939. styles.NumberFmt[j] = f;
  9940. if(j>0) {
  9941. if(j > 0x188) {
  9942. for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
  9943. styles.NumberFmt[j] = f;
  9944. }
  9945. SSF__load(f,j);
  9946. }
  9947. } break;
  9948. case '</numFmt>': break;
  9949. default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
  9950. }
  9951. }
  9952. }
  9953. function write_numFmts(NF) {
  9954. var o = ["<numFmts>"];
  9955. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  9956. 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])}));
  9957. });
  9958. if(o.length === 1) return "";
  9959. o[o.length] = ("</numFmts>");
  9960. o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
  9961. return o.join("");
  9962. }
  9963. /* 18.8.10 cellXfs CT_CellXfs */
  9964. var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
  9965. var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
  9966. function parse_cellXfs(t, styles, opts) {
  9967. styles.CellXf = [];
  9968. var xf;
  9969. var pass = false;
  9970. (t[0].match(tagregex)||[]).forEach(function(x) {
  9971. var y = parsexmltag(x), i = 0;
  9972. switch(strip_ns(y[0])) {
  9973. case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
  9974. /* 18.8.45 xf CT_Xf */
  9975. case '<xf': case '<xf/>':
  9976. xf = y;
  9977. delete xf[0];
  9978. for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
  9979. xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
  9980. for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
  9981. xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
  9982. if(styles.NumberFmt && xf.numFmtId > 0x188) {
  9983. for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
  9984. }
  9985. styles.CellXf.push(xf); break;
  9986. case '</xf>': break;
  9987. /* 18.8.1 alignment CT_CellAlignment */
  9988. case '<alignment': case '<alignment/>':
  9989. var alignment = {};
  9990. if(y.vertical) alignment.vertical = y.vertical;
  9991. if(y.horizontal) alignment.horizontal = y.horizontal;
  9992. if(y.textRotation != null) alignment.textRotation = y.textRotation;
  9993. if(y.indent) alignment.indent = y.indent;
  9994. if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
  9995. xf.alignment = alignment;
  9996. break;
  9997. case '</alignment>': break;
  9998. /* 18.8.33 protection CT_CellProtection */
  9999. case '<protection':
  10000. break;
  10001. case '</protection>': case '<protection/>': break;
  10002. /* note: sometimes mc:AlternateContent appears bare */
  10003. case '<AlternateContent': pass = true; break;
  10004. case '</AlternateContent>': pass = false; break;
  10005. /* 18.2.10 extLst CT_ExtensionList ? */
  10006. case '<extLst': case '<extLst>': case '</extLst>': break;
  10007. case '<ext': pass = true; break;
  10008. case '</ext>': pass = false; break;
  10009. default: if(opts && opts.WTF) {
  10010. if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
  10011. }
  10012. }
  10013. });
  10014. }
  10015. function write_cellXfs(cellXfs) {
  10016. var o = [];
  10017. o[o.length] = (writextag('cellXfs',null));
  10018. cellXfs.forEach(function(c) {
  10019. o[o.length] = (writextag('xf', null, c));
  10020. });
  10021. o[o.length] = ("</cellXfs>");
  10022. if(o.length === 2) return "";
  10023. o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
  10024. return o.join("");
  10025. }
  10026. /* 18.8 Styles CT_Stylesheet*/
  10027. var parse_sty_xml= (function make_pstyx() {
  10028. var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
  10029. var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
  10030. var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
  10031. var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
  10032. var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;
  10033. return function parse_sty_xml(data, themes, opts) {
  10034. var styles = {};
  10035. if(!data) return styles;
  10036. data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  10037. /* 18.8.39 styleSheet CT_Stylesheet */
  10038. var t;
  10039. /* 18.8.31 numFmts CT_NumFmts ? */
  10040. if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);
  10041. /* 18.8.23 fonts CT_Fonts ? */
  10042. if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);
  10043. /* 18.8.21 fills CT_Fills ? */
  10044. if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);
  10045. /* 18.8.5 borders CT_Borders ? */
  10046. if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);
  10047. /* 18.8.9 cellStyleXfs CT_CellStyleXfs ? */
  10048. /* 18.8.8 cellStyles CT_CellStyles ? */
  10049. /* 18.8.10 cellXfs CT_CellXfs ? */
  10050. if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);
  10051. /* 18.8.15 dxfs CT_Dxfs ? */
  10052. /* 18.8.42 tableStyles CT_TableStyles ? */
  10053. /* 18.8.11 colors CT_Colors ? */
  10054. /* 18.2.10 extLst CT_ExtensionList ? */
  10055. return styles;
  10056. };
  10057. })();
  10058. function write_sty_xml(wb, opts) {
  10059. var o = [XML_HEADER, writextag('styleSheet', null, {
  10060. 'xmlns': XMLNS_main[0],
  10061. 'xmlns:vt': XMLNS.vt
  10062. })], w;
  10063. if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
  10064. o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
  10065. o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  10066. o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
  10067. o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
  10068. if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
  10069. o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
  10070. o[o.length] = ('<dxfs count="0"/>');
  10071. o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
  10072. if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
  10073. return o.join("");
  10074. }
  10075. /* [MS-XLSB] 2.4.657 BrtFmt */
  10076. function parse_BrtFmt(data, length) {
  10077. var numFmtId = data.read_shift(2);
  10078. var stFmtCode = parse_XLWideString(data,length-2);
  10079. return [numFmtId, stFmtCode];
  10080. }
  10081. function write_BrtFmt(i, f, o) {
  10082. if(!o) o = new_buf(6 + 4 * f.length);
  10083. o.write_shift(2, i);
  10084. write_XLWideString(f, o);
  10085. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  10086. if(o.l == null) o.l = o.length;
  10087. return out;
  10088. }
  10089. /* [MS-XLSB] 2.4.659 BrtFont TODO */
  10090. function parse_BrtFont(data, length, opts) {
  10091. var out = ({});
  10092. out.sz = data.read_shift(2) / 20;
  10093. var grbit = parse_FontFlags(data, 2, opts);
  10094. if(grbit.fItalic) out.italic = 1;
  10095. if(grbit.fCondense) out.condense = 1;
  10096. if(grbit.fExtend) out.extend = 1;
  10097. if(grbit.fShadow) out.shadow = 1;
  10098. if(grbit.fOutline) out.outline = 1;
  10099. if(grbit.fStrikeout) out.strike = 1;
  10100. var bls = data.read_shift(2);
  10101. if(bls === 0x02BC) out.bold = 1;
  10102. switch(data.read_shift(2)) {
  10103. /* case 0: out.vertAlign = "baseline"; break; */
  10104. case 1: out.vertAlign = "superscript"; break;
  10105. case 2: out.vertAlign = "subscript"; break;
  10106. }
  10107. var underline = data.read_shift(1);
  10108. if(underline != 0) out.underline = underline;
  10109. var family = data.read_shift(1);
  10110. if(family > 0) out.family = family;
  10111. var bCharSet = data.read_shift(1);
  10112. if(bCharSet > 0) out.charset = bCharSet;
  10113. data.l++;
  10114. out.color = parse_BrtColor(data, 8);
  10115. switch(data.read_shift(1)) {
  10116. /* case 0: out.scheme = "none": break; */
  10117. case 1: out.scheme = "major"; break;
  10118. case 2: out.scheme = "minor"; break;
  10119. }
  10120. out.name = parse_XLWideString(data, length - 21);
  10121. return out;
  10122. }
  10123. function write_BrtFont(font, o) {
  10124. if(!o) o = new_buf(25+4*32);
  10125. o.write_shift(2, font.sz * 20);
  10126. write_FontFlags(font, o);
  10127. o.write_shift(2, font.bold ? 0x02BC : 0x0190);
  10128. var sss = 0;
  10129. if(font.vertAlign == "superscript") sss = 1;
  10130. else if(font.vertAlign == "subscript") sss = 2;
  10131. o.write_shift(2, sss);
  10132. o.write_shift(1, font.underline || 0);
  10133. o.write_shift(1, font.family || 0);
  10134. o.write_shift(1, font.charset || 0);
  10135. o.write_shift(1, 0);
  10136. write_BrtColor(font.color, o);
  10137. var scheme = 0;
  10138. if(font.scheme == "major") scheme = 1;
  10139. if(font.scheme == "minor") scheme = 2;
  10140. o.write_shift(1, scheme);
  10141. write_XLWideString(font.name, o);
  10142. return o.length > o.l ? o.slice(0, o.l) : o;
  10143. }
  10144. /* [MS-XLSB] 2.4.650 BrtFill */
  10145. var XLSBFillPTNames = [
  10146. "none",
  10147. "solid",
  10148. "mediumGray",
  10149. "darkGray",
  10150. "lightGray",
  10151. "darkHorizontal",
  10152. "darkVertical",
  10153. "darkDown",
  10154. "darkUp",
  10155. "darkGrid",
  10156. "darkTrellis",
  10157. "lightHorizontal",
  10158. "lightVertical",
  10159. "lightDown",
  10160. "lightUp",
  10161. "lightGrid",
  10162. "lightTrellis",
  10163. "gray125",
  10164. "gray0625"
  10165. ];
  10166. var rev_XLSBFillPTNames;
  10167. /* TODO: gradient fill representation */
  10168. var parse_BrtFill = parsenoop;
  10169. function write_BrtFill(fill, o) {
  10170. if(!o) o = new_buf(4*3 + 8*7 + 16*1);
  10171. if(!rev_XLSBFillPTNames) rev_XLSBFillPTNames = (evert(XLSBFillPTNames));
  10172. var fls = rev_XLSBFillPTNames[fill.patternType];
  10173. if(fls == null) fls = 0x28;
  10174. o.write_shift(4, fls);
  10175. var j = 0;
  10176. if(fls != 0x28) {
  10177. /* TODO: custom FG Color */
  10178. write_BrtColor({auto:1}, o);
  10179. /* TODO: custom BG Color */
  10180. write_BrtColor({auto:1}, o);
  10181. for(; j < 12; ++j) o.write_shift(4, 0);
  10182. } else {
  10183. for(; j < 4; ++j) o.write_shift(4, 0);
  10184. for(; j < 12; ++j) o.write_shift(4, 0); /* TODO */
  10185. /* iGradientType */
  10186. /* xnumDegree */
  10187. /* xnumFillToLeft */
  10188. /* xnumFillToRight */
  10189. /* xnumFillToTop */
  10190. /* xnumFillToBottom */
  10191. /* cNumStop */
  10192. /* xfillGradientStop */
  10193. }
  10194. return o.length > o.l ? o.slice(0, o.l) : o;
  10195. }
  10196. /* [MS-XLSB] 2.4.824 BrtXF */
  10197. function parse_BrtXF(data, length) {
  10198. var tgt = data.l + length;
  10199. var ixfeParent = data.read_shift(2);
  10200. var ifmt = data.read_shift(2);
  10201. data.l = tgt;
  10202. return {ixfe:ixfeParent, numFmtId:ifmt };
  10203. }
  10204. function write_BrtXF(data, ixfeP, o) {
  10205. if(!o) o = new_buf(16);
  10206. o.write_shift(2, ixfeP||0);
  10207. o.write_shift(2, data.numFmtId||0);
  10208. o.write_shift(2, 0); /* iFont */
  10209. o.write_shift(2, 0); /* iFill */
  10210. o.write_shift(2, 0); /* ixBorder */
  10211. o.write_shift(1, 0); /* trot */
  10212. o.write_shift(1, 0); /* indent */
  10213. var flow = 0;
  10214. o.write_shift(1, flow); /* flags */
  10215. o.write_shift(1, 0); /* flags */
  10216. o.write_shift(1, 0); /* xfGrbitAtr */
  10217. o.write_shift(1, 0);
  10218. return o;
  10219. }
  10220. /* [MS-XLSB] 2.5.4 Blxf TODO */
  10221. function write_Blxf(data, o) {
  10222. if(!o) o = new_buf(10);
  10223. o.write_shift(1, 0); /* dg */
  10224. o.write_shift(1, 0);
  10225. o.write_shift(4, 0); /* color */
  10226. o.write_shift(4, 0); /* color */
  10227. return o;
  10228. }
  10229. /* [MS-XLSB] 2.4.302 BrtBorder TODO */
  10230. var parse_BrtBorder = parsenoop;
  10231. function write_BrtBorder(border, o) {
  10232. if(!o) o = new_buf(51);
  10233. o.write_shift(1, 0); /* diagonal */
  10234. write_Blxf(null, o); /* top */
  10235. write_Blxf(null, o); /* bottom */
  10236. write_Blxf(null, o); /* left */
  10237. write_Blxf(null, o); /* right */
  10238. write_Blxf(null, o); /* diag */
  10239. return o.length > o.l ? o.slice(0, o.l) : o;
  10240. }
  10241. /* [MS-XLSB] 2.4.763 BrtStyle TODO */
  10242. function write_BrtStyle(style, o) {
  10243. if(!o) o = new_buf(12+4*10);
  10244. o.write_shift(4, style.xfId);
  10245. o.write_shift(2, 1);
  10246. o.write_shift(1, +style.builtinId);
  10247. o.write_shift(1, 0); /* iLevel */
  10248. write_XLNullableWideString(style.name || "", o);
  10249. return o.length > o.l ? o.slice(0, o.l) : o;
  10250. }
  10251. /* [MS-XLSB] 2.4.272 BrtBeginTableStyles */
  10252. function write_BrtBeginTableStyles(cnt, defTableStyle, defPivotStyle) {
  10253. var o = new_buf(4+256*2*4);
  10254. o.write_shift(4, cnt);
  10255. write_XLNullableWideString(defTableStyle, o);
  10256. write_XLNullableWideString(defPivotStyle, o);
  10257. return o.length > o.l ? o.slice(0, o.l) : o;
  10258. }
  10259. /* [MS-XLSB] 2.1.7.50 Styles */
  10260. function parse_sty_bin(data, themes, opts) {
  10261. var styles = {};
  10262. styles.NumberFmt = ([]);
  10263. for(var y in table_fmt) styles.NumberFmt[y] = table_fmt[y];
  10264. styles.CellXf = [];
  10265. styles.Fonts = [];
  10266. var state = [];
  10267. var pass = false;
  10268. recordhopper(data, function hopper_sty(val, R, RT) {
  10269. switch(RT) {
  10270. case 0x002C: /* BrtFmt */
  10271. styles.NumberFmt[val[0]] = val[1]; SSF__load(val[1], val[0]);
  10272. break;
  10273. case 0x002B: /* BrtFont */
  10274. styles.Fonts.push(val);
  10275. if(val.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
  10276. val.color.rgb = rgb_tint(themes.themeElements.clrScheme[val.color.theme].rgb, val.color.tint || 0);
  10277. }
  10278. break;
  10279. case 0x0401: /* BrtKnownFonts */ break;
  10280. case 0x002D: /* BrtFill */
  10281. break;
  10282. case 0x002E: /* BrtBorder */
  10283. break;
  10284. case 0x002F: /* BrtXF */
  10285. if(state[state.length - 1] == 0x0269 /* BrtBeginCellXFs */) {
  10286. styles.CellXf.push(val);
  10287. }
  10288. break;
  10289. case 0x0030: /* BrtStyle */
  10290. case 0x01FB: /* BrtDXF */
  10291. case 0x023C: /* BrtMRUColor */
  10292. case 0x01DB: /* BrtIndexedColor */
  10293. break;
  10294. case 0x0493: /* BrtDXF14 */
  10295. case 0x0836: /* BrtDXF15 */
  10296. case 0x046A: /* BrtSlicerStyleElement */
  10297. case 0x0200: /* BrtTableStyleElement */
  10298. case 0x082F: /* BrtTimelineStyleElement */
  10299. case 0x0C00: /* BrtUid */
  10300. break;
  10301. case 0x0023: /* BrtFRTBegin */
  10302. pass = true; break;
  10303. case 0x0024: /* BrtFRTEnd */
  10304. pass = false; break;
  10305. case 0x0025: /* BrtACBegin */
  10306. state.push(RT); pass = true; break;
  10307. case 0x0026: /* BrtACEnd */
  10308. state.pop(); pass = false; break;
  10309. default:
  10310. if(R.T > 0) state.push(RT);
  10311. else if(R.T < 0) state.pop();
  10312. else if(!pass || (opts.WTF && state[state.length-1] != 0x0025 /* BrtACBegin */)) throw new Error("Unexpected record 0x" + RT.toString(16));
  10313. }
  10314. });
  10315. return styles;
  10316. }
  10317. function write_FMTS_bin(ba, NF) {
  10318. if(!NF) return;
  10319. var cnt = 0;
  10320. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  10321. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) ++cnt;
  10322. });
  10323. if(cnt == 0) return;
  10324. write_record(ba, 0x0267 /* BrtBeginFmts */, write_UInt32LE(cnt));
  10325. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  10326. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_record(ba, 0x002C /* BrtFmt */, write_BrtFmt(i, NF[i]));
  10327. });
  10328. write_record(ba, 0x0268 /* BrtEndFmts */);
  10329. }
  10330. function write_FONTS_bin(ba) {
  10331. var cnt = 1;
  10332. if(cnt == 0) return;
  10333. write_record(ba, 0x0263 /* BrtBeginFonts */, write_UInt32LE(cnt));
  10334. write_record(ba, 0x002B /* BrtFont */, write_BrtFont({
  10335. sz:12,
  10336. color: {theme:1},
  10337. name: "Calibri",
  10338. family: 2,
  10339. scheme: "minor"
  10340. }));
  10341. /* 1*65491BrtFont [ACFONTS] */
  10342. write_record(ba, 0x0264 /* BrtEndFonts */);
  10343. }
  10344. function write_FILLS_bin(ba) {
  10345. var cnt = 2;
  10346. if(cnt == 0) return;
  10347. write_record(ba, 0x025B /* BrtBeginFills */, write_UInt32LE(cnt));
  10348. write_record(ba, 0x002D /* BrtFill */, write_BrtFill({patternType:"none"}));
  10349. write_record(ba, 0x002D /* BrtFill */, write_BrtFill({patternType:"gray125"}));
  10350. /* 1*65431BrtFill */
  10351. write_record(ba, 0x025C /* BrtEndFills */);
  10352. }
  10353. function write_BORDERS_bin(ba) {
  10354. var cnt = 1;
  10355. if(cnt == 0) return;
  10356. write_record(ba, 0x0265 /* BrtBeginBorders */, write_UInt32LE(cnt));
  10357. write_record(ba, 0x002E /* BrtBorder */, write_BrtBorder({}));
  10358. /* 1*65430BrtBorder */
  10359. write_record(ba, 0x0266 /* BrtEndBorders */);
  10360. }
  10361. function write_CELLSTYLEXFS_bin(ba) {
  10362. var cnt = 1;
  10363. write_record(ba, 0x0272 /* BrtBeginCellStyleXFs */, write_UInt32LE(cnt));
  10364. write_record(ba, 0x002F /* BrtXF */, write_BrtXF({
  10365. numFmtId: 0,
  10366. fontId: 0,
  10367. fillId: 0,
  10368. borderId: 0
  10369. }, 0xFFFF));
  10370. /* 1*65430(BrtXF *FRT) */
  10371. write_record(ba, 0x0273 /* BrtEndCellStyleXFs */);
  10372. }
  10373. function write_CELLXFS_bin(ba, data) {
  10374. write_record(ba, 0x0269 /* BrtBeginCellXFs */, write_UInt32LE(data.length));
  10375. data.forEach(function(c) { write_record(ba, 0x002F /* BrtXF */, write_BrtXF(c,0)); });
  10376. /* 1*65430(BrtXF *FRT) */
  10377. write_record(ba, 0x026A /* BrtEndCellXFs */);
  10378. }
  10379. function write_STYLES_bin(ba) {
  10380. var cnt = 1;
  10381. write_record(ba, 0x026B /* BrtBeginStyles */, write_UInt32LE(cnt));
  10382. write_record(ba, 0x0030 /* BrtStyle */, write_BrtStyle({
  10383. xfId:0,
  10384. builtinId:0,
  10385. name:"Normal"
  10386. }));
  10387. /* 1*65430(BrtStyle *FRT) */
  10388. write_record(ba, 0x026C /* BrtEndStyles */);
  10389. }
  10390. function write_DXFS_bin(ba) {
  10391. var cnt = 0;
  10392. write_record(ba, 0x01F9 /* BrtBeginDXFs */, write_UInt32LE(cnt));
  10393. /* *2147483647(BrtDXF *FRT) */
  10394. write_record(ba, 0x01FA /* BrtEndDXFs */);
  10395. }
  10396. function write_TABLESTYLES_bin(ba) {
  10397. var cnt = 0;
  10398. write_record(ba, 0x01FC /* BrtBeginTableStyles */, write_BrtBeginTableStyles(cnt, "TableStyleMedium9", "PivotStyleMedium4"));
  10399. /* *TABLESTYLE */
  10400. write_record(ba, 0x01FD /* BrtEndTableStyles */);
  10401. }
  10402. function write_COLORPALETTE_bin() {
  10403. return;
  10404. /* BrtBeginColorPalette [INDEXEDCOLORS] [MRUCOLORS] BrtEndColorPalette */
  10405. }
  10406. /* [MS-XLSB] 2.1.7.50 Styles */
  10407. function write_sty_bin(wb, opts) {
  10408. var ba = buf_array();
  10409. write_record(ba, 0x0116 /* BrtBeginStyleSheet */);
  10410. write_FMTS_bin(ba, wb.SSF);
  10411. write_FONTS_bin(ba, wb);
  10412. write_FILLS_bin(ba, wb);
  10413. write_BORDERS_bin(ba, wb);
  10414. write_CELLSTYLEXFS_bin(ba, wb);
  10415. write_CELLXFS_bin(ba, opts.cellXfs);
  10416. write_STYLES_bin(ba, wb);
  10417. write_DXFS_bin(ba, wb);
  10418. write_TABLESTYLES_bin(ba, wb);
  10419. write_COLORPALETTE_bin(ba, wb);
  10420. /* FRTSTYLESHEET*/
  10421. write_record(ba, 0x0117 /* BrtEndStyleSheet */);
  10422. return ba.end();
  10423. }
  10424. /* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
  10425. var XLSXThemeClrScheme = [
  10426. '</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
  10427. '</a:accent1>', '</a:accent2>', '</a:accent3>',
  10428. '</a:accent4>', '</a:accent5>', '</a:accent6>',
  10429. '</a:hlink>', '</a:folHlink>'
  10430. ];
  10431. /* 20.1.6.2 clrScheme CT_ColorScheme */
  10432. function parse_clrScheme(t, themes, opts) {
  10433. themes.themeElements.clrScheme = [];
  10434. var color = {};
  10435. (t[0].match(tagregex)||[]).forEach(function(x) {
  10436. var y = parsexmltag(x);
  10437. switch(y[0]) {
  10438. /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
  10439. case '<a:clrScheme': case '</a:clrScheme>': break;
  10440. /* 20.1.2.3.32 srgbClr CT_SRgbColor */
  10441. case '<a:srgbClr':
  10442. color.rgb = y.val; break;
  10443. /* 20.1.2.3.33 sysClr CT_SystemColor */
  10444. case '<a:sysClr':
  10445. color.rgb = y.lastClr; break;
  10446. /* 20.1.4.1.1 accent1 (Accent 1) */
  10447. /* 20.1.4.1.2 accent2 (Accent 2) */
  10448. /* 20.1.4.1.3 accent3 (Accent 3) */
  10449. /* 20.1.4.1.4 accent4 (Accent 4) */
  10450. /* 20.1.4.1.5 accent5 (Accent 5) */
  10451. /* 20.1.4.1.6 accent6 (Accent 6) */
  10452. /* 20.1.4.1.9 dk1 (Dark 1) */
  10453. /* 20.1.4.1.10 dk2 (Dark 2) */
  10454. /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
  10455. /* 20.1.4.1.19 hlink (Hyperlink) */
  10456. /* 20.1.4.1.22 lt1 (Light 1) */
  10457. /* 20.1.4.1.23 lt2 (Light 2) */
  10458. case '<a:dk1>': case '</a:dk1>':
  10459. case '<a:lt1>': case '</a:lt1>':
  10460. case '<a:dk2>': case '</a:dk2>':
  10461. case '<a:lt2>': case '</a:lt2>':
  10462. case '<a:accent1>': case '</a:accent1>':
  10463. case '<a:accent2>': case '</a:accent2>':
  10464. case '<a:accent3>': case '</a:accent3>':
  10465. case '<a:accent4>': case '</a:accent4>':
  10466. case '<a:accent5>': case '</a:accent5>':
  10467. case '<a:accent6>': case '</a:accent6>':
  10468. case '<a:hlink>': case '</a:hlink>':
  10469. case '<a:folHlink>': case '</a:folHlink>':
  10470. if (y[0].charAt(1) === '/') {
  10471. themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
  10472. color = {};
  10473. } else {
  10474. color.name = y[0].slice(3, y[0].length - 1);
  10475. }
  10476. break;
  10477. default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
  10478. }
  10479. });
  10480. }
  10481. /* 20.1.4.1.18 fontScheme CT_FontScheme */
  10482. function parse_fontScheme() { }
  10483. /* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
  10484. function parse_fmtScheme() { }
  10485. var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
  10486. var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
  10487. var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;
  10488. /* 20.1.6.10 themeElements CT_BaseStyles */
  10489. function parse_themeElements(data, themes, opts) {
  10490. themes.themeElements = {};
  10491. var t;
  10492. [
  10493. /* clrScheme CT_ColorScheme */
  10494. ['clrScheme', clrsregex, parse_clrScheme],
  10495. /* fontScheme CT_FontScheme */
  10496. ['fontScheme', fntsregex, parse_fontScheme],
  10497. /* fmtScheme CT_StyleMatrix */
  10498. ['fmtScheme', fmtsregex, parse_fmtScheme]
  10499. ].forEach(function(m) {
  10500. if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
  10501. m[2](t, themes, opts);
  10502. });
  10503. }
  10504. var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;
  10505. /* 14.2.7 Theme Part */
  10506. function parse_theme_xml(data, opts) {
  10507. /* 20.1.6.9 theme CT_OfficeStyleSheet */
  10508. if(!data || data.length === 0) data = write_theme();
  10509. var t;
  10510. var themes = {};
  10511. /* themeElements CT_BaseStyles */
  10512. if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
  10513. parse_themeElements(t[0], themes, opts);
  10514. themes.raw = data;
  10515. return themes;
  10516. }
  10517. function write_theme(Themes, opts) {
  10518. if(opts && opts.themeXLSX) return opts.themeXLSX;
  10519. if(Themes && typeof Themes.raw == "string") return Themes.raw;
  10520. var o = [XML_HEADER];
  10521. o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  10522. o[o.length] = '<a:themeElements>';
  10523. o[o.length] = '<a:clrScheme name="Office">';
  10524. o[o.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  10525. o[o.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  10526. o[o.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  10527. o[o.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  10528. o[o.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  10529. o[o.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  10530. o[o.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  10531. o[o.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  10532. o[o.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  10533. o[o.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  10534. o[o.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  10535. o[o.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  10536. o[o.length] = '</a:clrScheme>';
  10537. o[o.length] = '<a:fontScheme name="Office">';
  10538. o[o.length] = '<a:majorFont>';
  10539. o[o.length] = '<a:latin typeface="Cambria"/>';
  10540. o[o.length] = '<a:ea typeface=""/>';
  10541. o[o.length] = '<a:cs typeface=""/>';
  10542. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  10543. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  10544. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  10545. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  10546. o[o.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  10547. o[o.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  10548. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  10549. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  10550. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  10551. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  10552. o[o.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  10553. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  10554. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  10555. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  10556. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  10557. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  10558. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  10559. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  10560. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  10561. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  10562. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  10563. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  10564. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  10565. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  10566. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  10567. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  10568. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  10569. o[o.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  10570. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  10571. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  10572. o[o.length] = '</a:majorFont>';
  10573. o[o.length] = '<a:minorFont>';
  10574. o[o.length] = '<a:latin typeface="Calibri"/>';
  10575. o[o.length] = '<a:ea typeface=""/>';
  10576. o[o.length] = '<a:cs typeface=""/>';
  10577. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  10578. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  10579. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  10580. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  10581. o[o.length] = '<a:font script="Arab" typeface="Arial"/>';
  10582. o[o.length] = '<a:font script="Hebr" typeface="Arial"/>';
  10583. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  10584. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  10585. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  10586. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  10587. o[o.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  10588. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  10589. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  10590. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  10591. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  10592. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  10593. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  10594. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  10595. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  10596. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  10597. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  10598. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  10599. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  10600. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  10601. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  10602. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  10603. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  10604. o[o.length] = '<a:font script="Viet" typeface="Arial"/>';
  10605. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  10606. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  10607. o[o.length] = '</a:minorFont>';
  10608. o[o.length] = '</a:fontScheme>';
  10609. o[o.length] = '<a:fmtScheme name="Office">';
  10610. o[o.length] = '<a:fillStyleLst>';
  10611. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  10612. o[o.length] = '<a:gradFill rotWithShape="1">';
  10613. o[o.length] = '<a:gsLst>';
  10614. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  10615. o[o.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  10616. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  10617. o[o.length] = '</a:gsLst>';
  10618. o[o.length] = '<a:lin ang="16200000" scaled="1"/>';
  10619. o[o.length] = '</a:gradFill>';
  10620. o[o.length] = '<a:gradFill rotWithShape="1">';
  10621. o[o.length] = '<a:gsLst>';
  10622. 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>';
  10623. 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>';
  10624. o[o.length] = '</a:gsLst>';
  10625. o[o.length] = '<a:lin ang="16200000" scaled="0"/>';
  10626. o[o.length] = '</a:gradFill>';
  10627. o[o.length] = '</a:fillStyleLst>';
  10628. o[o.length] = '<a:lnStyleLst>';
  10629. 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>';
  10630. 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>';
  10631. 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>';
  10632. o[o.length] = '</a:lnStyleLst>';
  10633. o[o.length] = '<a:effectStyleLst>';
  10634. o[o.length] = '<a:effectStyle>';
  10635. o[o.length] = '<a:effectLst>';
  10636. 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>';
  10637. o[o.length] = '</a:effectLst>';
  10638. o[o.length] = '</a:effectStyle>';
  10639. o[o.length] = '<a:effectStyle>';
  10640. o[o.length] = '<a:effectLst>';
  10641. 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>';
  10642. o[o.length] = '</a:effectLst>';
  10643. o[o.length] = '</a:effectStyle>';
  10644. o[o.length] = '<a:effectStyle>';
  10645. o[o.length] = '<a:effectLst>';
  10646. 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>';
  10647. o[o.length] = '</a:effectLst>';
  10648. 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>';
  10649. o[o.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  10650. o[o.length] = '</a:effectStyle>';
  10651. o[o.length] = '</a:effectStyleLst>';
  10652. o[o.length] = '<a:bgFillStyleLst>';
  10653. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  10654. o[o.length] = '<a:gradFill rotWithShape="1">';
  10655. o[o.length] = '<a:gsLst>';
  10656. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  10657. 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>';
  10658. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  10659. o[o.length] = '</a:gsLst>';
  10660. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  10661. o[o.length] = '</a:gradFill>';
  10662. o[o.length] = '<a:gradFill rotWithShape="1">';
  10663. o[o.length] = '<a:gsLst>';
  10664. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  10665. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  10666. o[o.length] = '</a:gsLst>';
  10667. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  10668. o[o.length] = '</a:gradFill>';
  10669. o[o.length] = '</a:bgFillStyleLst>';
  10670. o[o.length] = '</a:fmtScheme>';
  10671. o[o.length] = '</a:themeElements>';
  10672. o[o.length] = '<a:objectDefaults>';
  10673. o[o.length] = '<a:spDef>';
  10674. 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>';
  10675. o[o.length] = '</a:spDef>';
  10676. o[o.length] = '<a:lnDef>';
  10677. 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>';
  10678. o[o.length] = '</a:lnDef>';
  10679. o[o.length] = '</a:objectDefaults>';
  10680. o[o.length] = '<a:extraClrSchemeLst/>';
  10681. o[o.length] = '</a:theme>';
  10682. return o.join("");
  10683. }
  10684. /* [MS-XLS] 2.4.326 TODO: payload is a zip file */
  10685. function parse_Theme(blob, length, opts) {
  10686. var end = blob.l + length;
  10687. var dwThemeVersion = blob.read_shift(4);
  10688. if(dwThemeVersion === 124226) return;
  10689. if(!opts.cellStyles) { blob.l = end; return; }
  10690. var data = blob.slice(blob.l);
  10691. blob.l = end;
  10692. var zip; try { zip = zip_read(data, {type: "array"}); } catch(e) { return; }
  10693. var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
  10694. if(!themeXML) return;
  10695. return parse_theme_xml(themeXML, opts);
  10696. }
  10697. /* 2.5.49 */
  10698. function parse_ColorTheme(blob) { return blob.read_shift(4); }
  10699. /* 2.5.155 */
  10700. function parse_FullColorExt(blob) {
  10701. var o = {};
  10702. o.xclrType = blob.read_shift(2);
  10703. o.nTintShade = blob.read_shift(2);
  10704. switch(o.xclrType) {
  10705. case 0: blob.l += 4; break;
  10706. case 1: o.xclrValue = parse_IcvXF(blob, 4); break;
  10707. case 2: o.xclrValue = parse_LongRGBA(blob, 4); break;
  10708. case 3: o.xclrValue = parse_ColorTheme(blob, 4); break;
  10709. case 4: blob.l += 4; break;
  10710. }
  10711. blob.l += 8;
  10712. return o;
  10713. }
  10714. /* 2.5.164 TODO: read 7 bits*/
  10715. function parse_IcvXF(blob, length) {
  10716. return parsenoop(blob, length);
  10717. }
  10718. /* 2.5.280 */
  10719. function parse_XFExtGradient(blob, length) {
  10720. return parsenoop(blob, length);
  10721. }
  10722. /* [MS-XLS] 2.5.108 */
  10723. function parse_ExtProp(blob) {
  10724. var extType = blob.read_shift(2);
  10725. var cb = blob.read_shift(2) - 4;
  10726. var o = [extType];
  10727. switch(extType) {
  10728. case 0x04: case 0x05: case 0x07: case 0x08:
  10729. case 0x09: case 0x0A: case 0x0B: case 0x0D:
  10730. o[1] = parse_FullColorExt(blob, cb); break;
  10731. case 0x06: o[1] = parse_XFExtGradient(blob, cb); break;
  10732. case 0x0E: case 0x0F: o[1] = blob.read_shift(cb === 1 ? 1 : 2); break;
  10733. default: throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
  10734. }
  10735. return o;
  10736. }
  10737. /* 2.4.355 */
  10738. function parse_XFExt(blob, length) {
  10739. var end = blob.l + length;
  10740. blob.l += 2;
  10741. var ixfe = blob.read_shift(2);
  10742. blob.l += 2;
  10743. var cexts = blob.read_shift(2);
  10744. var ext = [];
  10745. while(cexts-- > 0) ext.push(parse_ExtProp(blob, end-blob.l));
  10746. return {ixfe:ixfe, ext:ext};
  10747. }
  10748. /* xf is an XF, see parse_XFExt for xfext */
  10749. function update_xfext(xf, xfext) {
  10750. xfext.forEach(function(xfe) {
  10751. switch(xfe[0]) { /* 2.5.108 extPropData */
  10752. case 0x04: break; /* foreground color */
  10753. case 0x05: break; /* background color */
  10754. case 0x06: break; /* gradient fill */
  10755. case 0x07: break; /* top cell border color */
  10756. case 0x08: break; /* bottom cell border color */
  10757. case 0x09: break; /* left cell border color */
  10758. case 0x0a: break; /* right cell border color */
  10759. case 0x0b: break; /* diagonal cell border color */
  10760. case 0x0d: /* text color */
  10761. break;
  10762. case 0x0e: break; /* font scheme */
  10763. case 0x0f: break; /* indentation level */
  10764. }
  10765. });
  10766. }
  10767. function parse_BrtMdtinfo(data, length) {
  10768. return {
  10769. flags: data.read_shift(4),
  10770. version: data.read_shift(4),
  10771. name: parse_XLWideString(data, length - 8)
  10772. };
  10773. }
  10774. function write_BrtMdtinfo(data) {
  10775. var o = new_buf(12 + 2 * data.name.length);
  10776. o.write_shift(4, data.flags);
  10777. o.write_shift(4, data.version);
  10778. write_XLWideString(data.name, o);
  10779. return o.slice(0, o.l);
  10780. }
  10781. function parse_BrtMdb(data) {
  10782. var out = [];
  10783. var cnt = data.read_shift(4);
  10784. while (cnt-- > 0)
  10785. out.push([data.read_shift(4), data.read_shift(4)]);
  10786. return out;
  10787. }
  10788. function write_BrtMdb(mdb) {
  10789. var o = new_buf(4 + 8 * mdb.length);
  10790. o.write_shift(4, mdb.length);
  10791. for (var i = 0; i < mdb.length; ++i) {
  10792. o.write_shift(4, mdb[i][0]);
  10793. o.write_shift(4, mdb[i][1]);
  10794. }
  10795. return o;
  10796. }
  10797. function write_BrtBeginEsfmd(cnt, name) {
  10798. var o = new_buf(8 + 2 * name.length);
  10799. o.write_shift(4, cnt);
  10800. write_XLWideString(name, o);
  10801. return o.slice(0, o.l);
  10802. }
  10803. function parse_BrtBeginEsmdb(data) {
  10804. data.l += 4;
  10805. return data.read_shift(4) != 0;
  10806. }
  10807. function write_BrtBeginEsmdb(cnt, cm) {
  10808. var o = new_buf(8);
  10809. o.write_shift(4, cnt);
  10810. o.write_shift(4, cm ? 1 : 0);
  10811. return o;
  10812. }
  10813. function parse_xlmeta_bin(data, name, _opts) {
  10814. var out = { Types: [], Cell: [], Value: [] };
  10815. var opts = _opts || {};
  10816. var state = [];
  10817. var pass = false;
  10818. var metatype = 2;
  10819. recordhopper(data, function(val, R, RT) {
  10820. switch (RT) {
  10821. case 335:
  10822. out.Types.push({ name: val.name });
  10823. break;
  10824. case 51:
  10825. val.forEach(function(r) {
  10826. if (metatype == 1)
  10827. out.Cell.push({ type: out.Types[r[0] - 1].name, index: r[1] });
  10828. else if (metatype == 0)
  10829. out.Value.push({ type: out.Types[r[0] - 1].name, index: r[1] });
  10830. });
  10831. break;
  10832. case 337:
  10833. metatype = val ? 1 : 0;
  10834. break;
  10835. case 338:
  10836. metatype = 2;
  10837. break;
  10838. case 35:
  10839. state.push(RT);
  10840. pass = true;
  10841. break;
  10842. case 36:
  10843. state.pop();
  10844. pass = false;
  10845. break;
  10846. default:
  10847. if (R.T) {
  10848. } else if (!pass || opts.WTF && state[state.length - 1] != 35)
  10849. throw new Error("Unexpected record 0x" + RT.toString(16));
  10850. }
  10851. });
  10852. return out;
  10853. }
  10854. function write_xlmeta_bin() {
  10855. var ba = buf_array();
  10856. write_record(ba, 332);
  10857. write_record(ba, 334, write_UInt32LE(1));
  10858. write_record(ba, 335, write_BrtMdtinfo({
  10859. name: "XLDAPR",
  10860. version: 12e4,
  10861. flags: 3496657072
  10862. }));
  10863. write_record(ba, 336);
  10864. write_record(ba, 339, write_BrtBeginEsfmd(1, "XLDAPR"));
  10865. write_record(ba, 52);
  10866. write_record(ba, 35, write_UInt32LE(514));
  10867. write_record(ba, 4096, write_UInt32LE(0));
  10868. write_record(ba, 4097, writeuint16(1));
  10869. write_record(ba, 36);
  10870. write_record(ba, 53);
  10871. write_record(ba, 340);
  10872. write_record(ba, 337, write_BrtBeginEsmdb(1, true));
  10873. write_record(ba, 51, write_BrtMdb([[1, 0]]));
  10874. write_record(ba, 338);
  10875. write_record(ba, 333);
  10876. return ba.end();
  10877. }
  10878. function parse_xlmeta_xml(data, name, opts) {
  10879. var out = { Types: [], Cell: [], Value: [] };
  10880. if (!data)
  10881. return out;
  10882. var pass = false;
  10883. var metatype = 2;
  10884. var lastmeta;
  10885. data.replace(tagregex, function(x) {
  10886. var y = parsexmltag(x);
  10887. switch (strip_ns(y[0])) {
  10888. case "<?xml":
  10889. break;
  10890. case "<metadata":
  10891. case "</metadata>":
  10892. break;
  10893. case "<metadataTypes":
  10894. case "</metadataTypes>":
  10895. break;
  10896. case "<metadataType":
  10897. out.Types.push({ name: y.name });
  10898. break;
  10899. case "</metadataType>":
  10900. break;
  10901. case "<futureMetadata":
  10902. for (var j = 0; j < out.Types.length; ++j)
  10903. if (out.Types[j].name == y.name)
  10904. lastmeta = out.Types[j];
  10905. break;
  10906. case "</futureMetadata>":
  10907. break;
  10908. case "<bk>":
  10909. break;
  10910. case "</bk>":
  10911. break;
  10912. case "<rc":
  10913. if (metatype == 1)
  10914. out.Cell.push({ type: out.Types[y.t - 1].name, index: +y.v });
  10915. else if (metatype == 0)
  10916. out.Value.push({ type: out.Types[y.t - 1].name, index: +y.v });
  10917. break;
  10918. case "</rc>":
  10919. break;
  10920. case "<cellMetadata":
  10921. metatype = 1;
  10922. break;
  10923. case "</cellMetadata>":
  10924. metatype = 2;
  10925. break;
  10926. case "<valueMetadata":
  10927. metatype = 0;
  10928. break;
  10929. case "</valueMetadata>":
  10930. metatype = 2;
  10931. break;
  10932. case "<extLst":
  10933. case "<extLst>":
  10934. case "</extLst>":
  10935. case "<extLst/>":
  10936. break;
  10937. case "<ext":
  10938. pass = true;
  10939. break;
  10940. case "</ext>":
  10941. pass = false;
  10942. break;
  10943. case "<rvb":
  10944. if (!lastmeta)
  10945. break;
  10946. if (!lastmeta.offsets)
  10947. lastmeta.offsets = [];
  10948. lastmeta.offsets.push(+y.i);
  10949. break;
  10950. default:
  10951. if (!pass && (opts == null ? void 0 : opts.WTF))
  10952. throw new Error("unrecognized " + y[0] + " in metadata");
  10953. }
  10954. return x;
  10955. });
  10956. return out;
  10957. }
  10958. function write_xlmeta_xml() {
  10959. var o = [XML_HEADER];
  10960. o.push('<metadata xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:xlrd="http://schemas.microsoft.com/office/spreadsheetml/2017/richdata" xmlns:xda="http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray">\n <metadataTypes count="1">\n <metadataType name="XLDAPR" minSupportedVersion="120000" copy="1" pasteAll="1" pasteValues="1" merge="1" splitFirst="1" rowColShift="1" clearFormats="1" clearComments="1" assign="1" coerce="1" cellMeta="1"/>\n </metadataTypes>\n <futureMetadata name="XLDAPR" count="1">\n <bk>\n <extLst>\n <ext uri="{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}">\n <xda:dynamicArrayProperties fDynamic="1" fCollapsed="0"/>\n </ext>\n </extLst>\n </bk>\n </futureMetadata>\n <cellMetadata count="1">\n <bk>\n <rc t="1" v="0"/>\n </bk>\n </cellMetadata>\n</metadata>');
  10961. return o.join("");
  10962. }
  10963. /* 18.6 Calculation Chain */
  10964. function parse_cc_xml(data) {
  10965. var d = [];
  10966. if(!data) return d;
  10967. var i = 1;
  10968. (data.match(tagregex)||[]).forEach(function(x) {
  10969. var y = parsexmltag(x);
  10970. switch(y[0]) {
  10971. case '<?xml': break;
  10972. /* 18.6.2 calcChain CT_CalcChain 1 */
  10973. case '<calcChain': case '<calcChain>': case '</calcChain>': break;
  10974. /* 18.6.1 c CT_CalcCell 1 */
  10975. case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
  10976. }
  10977. });
  10978. return d;
  10979. }
  10980. //function write_cc_xml(data, opts) { }
  10981. /* [MS-XLSB] 2.6.4.1 */
  10982. function parse_BrtCalcChainItem$(data) {
  10983. var out = {};
  10984. out.i = data.read_shift(4);
  10985. var cell = {};
  10986. cell.r = data.read_shift(4);
  10987. cell.c = data.read_shift(4);
  10988. out.r = encode_cell(cell);
  10989. var flags = data.read_shift(1);
  10990. if(flags & 0x2) out.l = '1';
  10991. if(flags & 0x8) out.a = '1';
  10992. return out;
  10993. }
  10994. /* 18.6 Calculation Chain */
  10995. function parse_cc_bin(data, name, opts) {
  10996. var out = [];
  10997. var pass = false;
  10998. recordhopper(data, function hopper_cc(val, R, RT) {
  10999. switch(RT) {
  11000. case 0x003F: /* 'BrtCalcChainItem$' */
  11001. out.push(val); break;
  11002. default:
  11003. if(R.T){/* empty */}
  11004. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  11005. }
  11006. });
  11007. return out;
  11008. }
  11009. //function write_cc_bin(data, opts) { }
  11010. /* 18.14 Supplementary Workbook Data */
  11011. function parse_xlink_xml() {
  11012. //var opts = _opts || {};
  11013. //if(opts.WTF) throw "XLSX External Link";
  11014. }
  11015. /* [MS-XLSB] 2.1.7.25 External Link */
  11016. function parse_xlink_bin(data, rel, name, _opts) {
  11017. if(!data) return data;
  11018. var opts = _opts || {};
  11019. var pass = false, end = false;
  11020. recordhopper(data, function xlink_parse(val, R, RT) {
  11021. if(end) return;
  11022. switch(RT) {
  11023. case 0x0167: /* 'BrtSupTabs' */
  11024. case 0x016B: /* 'BrtExternTableStart' */
  11025. case 0x016C: /* 'BrtExternTableEnd' */
  11026. case 0x016E: /* 'BrtExternRowHdr' */
  11027. case 0x016F: /* 'BrtExternCellBlank' */
  11028. case 0x0170: /* 'BrtExternCellReal' */
  11029. case 0x0171: /* 'BrtExternCellBool' */
  11030. case 0x0172: /* 'BrtExternCellError' */
  11031. case 0x0173: /* 'BrtExternCellString' */
  11032. case 0x01D8: /* 'BrtExternValueMeta' */
  11033. case 0x0241: /* 'BrtSupNameStart' */
  11034. case 0x0242: /* 'BrtSupNameValueStart' */
  11035. case 0x0243: /* 'BrtSupNameValueEnd' */
  11036. case 0x0244: /* 'BrtSupNameNum' */
  11037. case 0x0245: /* 'BrtSupNameErr' */
  11038. case 0x0246: /* 'BrtSupNameSt' */
  11039. case 0x0247: /* 'BrtSupNameNil' */
  11040. case 0x0248: /* 'BrtSupNameBool' */
  11041. case 0x0249: /* 'BrtSupNameFmla' */
  11042. case 0x024A: /* 'BrtSupNameBits' */
  11043. case 0x024B: /* 'BrtSupNameEnd' */
  11044. break;
  11045. case 0x0023: /* 'BrtFRTBegin' */
  11046. pass = true; break;
  11047. case 0x0024: /* 'BrtFRTEnd' */
  11048. pass = false; break;
  11049. default:
  11050. if(R.T){/* empty */}
  11051. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  11052. }
  11053. }, opts);
  11054. }
  11055. /* 20.5 DrawingML - SpreadsheetML Drawing */
  11056. /* 20.5.2.35 wsDr CT_Drawing */
  11057. function parse_drawing(data, rels) {
  11058. if(!data) return "??";
  11059. /*
  11060. Chartsheet Drawing:
  11061. - 20.5.2.35 wsDr CT_Drawing
  11062. - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor
  11063. - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
  11064. - 20.1.2.2.16 graphic CT_GraphicalObject
  11065. - 20.1.2.2.17 graphicData CT_GraphicalObjectData
  11066. - chart reference
  11067. the actual type is based on the URI of the graphicData
  11068. TODO: handle embedded charts and other types of graphics
  11069. */
  11070. var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];
  11071. return rels['!id'][id].Target;
  11072. }
  11073. /* L.5.5.2 SpreadsheetML Comments + VML Schema */
  11074. function write_vml(rId, comments) {
  11075. var csize = [21600, 21600];
  11076. /* L.5.2.1.2 Path Attribute */
  11077. var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
  11078. var o = [
  11079. writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
  11080. writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"})
  11081. ];
  11082. var _shapeid = 65536 * rId;
  11083. var _comments = comments || [];
  11084. if(_comments.length > 0) o.push(writextag("v:shapetype", [
  11085. writextag("v:stroke", null, {joinstyle:"miter"}),
  11086. writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
  11087. ].join(""), {id:"_x0000_t202", coordsize:csize.join(","), 'o:spt':202, path:bbox}));
  11088. _comments.forEach(function(x) { ++_shapeid; o.push(write_vml_comment(x, _shapeid)); });
  11089. o.push('</xml>');
  11090. return o.join("");
  11091. }
  11092. function write_vml_comment(x, _shapeid) {
  11093. var c = decode_cell(x[0]);
  11094. var fillopts = {'color2':"#BEFF82", 'type':"gradient"};
  11095. if(fillopts.type == "gradient") fillopts.angle = "-180";
  11096. var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
  11097. var fillxml = writextag('v:fill', fillparm, fillopts);
  11098. var shadata = ({on:"t", 'obscured':"t"});
  11099. return [
  11100. '<v:shape' + wxt_helper({
  11101. id:'_x0000_s' + _shapeid,
  11102. type:"#_x0000_t202",
  11103. style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
  11104. fillcolor:"#ECFAD4",
  11105. strokecolor:"#edeaa1"
  11106. }) + '>',
  11107. fillxml,
  11108. writextag("v:shadow", null, shadata),
  11109. writextag("v:path", null, {'o:connecttype':"none"}),
  11110. '<v:textbox><div style="text-align:left"></div></v:textbox>',
  11111. '<x:ClientData ObjectType="Note">',
  11112. '<x:MoveWithCells/>',
  11113. '<x:SizeWithCells/>',
  11114. /* Part 4 19.4.2.3 Anchor (Anchor) */
  11115. writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
  11116. writetag('x:AutoFill', "False"),
  11117. writetag('x:Row', String(c.r)),
  11118. writetag('x:Column', String(c.c)),
  11119. x[1].hidden ? '' : '<x:Visible/>',
  11120. '</x:ClientData>',
  11121. '</v:shape>'
  11122. ].join("");
  11123. }
  11124. function sheet_insert_comments(sheet, comments, threaded, people) {
  11125. var dense = Array.isArray(sheet);
  11126. var cell;
  11127. comments.forEach(function(comment) {
  11128. var r = decode_cell(comment.ref);
  11129. if(dense) {
  11130. if(!sheet[r.r]) sheet[r.r] = [];
  11131. cell = sheet[r.r][r.c];
  11132. } else cell = sheet[comment.ref];
  11133. if (!cell) {
  11134. cell = ({t:"z"});
  11135. if(dense) sheet[r.r][r.c] = cell;
  11136. else sheet[comment.ref] = cell;
  11137. var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
  11138. if(range.s.r > r.r) range.s.r = r.r;
  11139. if(range.e.r < r.r) range.e.r = r.r;
  11140. if(range.s.c > r.c) range.s.c = r.c;
  11141. if(range.e.c < r.c) range.e.c = r.c;
  11142. var encoded = encode_range(range);
  11143. if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
  11144. }
  11145. if (!cell.c) cell.c = [];
  11146. var o = ({a: comment.author, t: comment.t, r: comment.r, T: threaded});
  11147. if(comment.h) o.h = comment.h;
  11148. /* threaded comments always override */
  11149. for(var i = cell.c.length - 1; i >= 0; --i) {
  11150. if(!threaded && cell.c[i].T) return;
  11151. if(threaded && !cell.c[i].T) cell.c.splice(i, 1);
  11152. }
  11153. if(threaded && people) for(i = 0; i < people.length; ++i) {
  11154. if(o.a == people[i].id) { o.a = people[i].name || o.a; break; }
  11155. }
  11156. cell.c.push(o);
  11157. });
  11158. }
  11159. /* 18.7 Comments */
  11160. function parse_comments_xml(data, opts) {
  11161. /* 18.7.6 CT_Comments */
  11162. if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
  11163. var authors = [];
  11164. var commentList = [];
  11165. var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
  11166. if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
  11167. if(x === "" || x.trim() === "") return;
  11168. var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
  11169. if(a) authors.push(a[1]);
  11170. });
  11171. var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
  11172. if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
  11173. if(x === "" || x.trim() === "") return;
  11174. var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
  11175. if(!cm) return;
  11176. var y = parsexmltag(cm[0]);
  11177. var comment = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid });
  11178. var cell = decode_cell(y.ref);
  11179. if(opts.sheetRows && opts.sheetRows <= cell.r) return;
  11180. var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
  11181. var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
  11182. comment.r = rt.r;
  11183. if(rt.r == "<t></t>") rt.t = rt.h = "";
  11184. comment.t = (rt.t||"").replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  11185. if(opts.cellHTML) comment.h = rt.h;
  11186. commentList.push(comment);
  11187. });
  11188. return commentList;
  11189. }
  11190. function write_comments_xml(data) {
  11191. var o = [XML_HEADER, writextag('comments', null, { 'xmlns': XMLNS_main[0] })];
  11192. var iauthor = [];
  11193. o.push("<authors>");
  11194. data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
  11195. if(iauthor.indexOf(a) == -1) {
  11196. iauthor.push(a);
  11197. o.push("<author>" + a + "</author>");
  11198. }
  11199. if(w.T && w.ID && iauthor.indexOf("tc=" + w.ID) == -1) {
  11200. iauthor.push("tc=" + w.ID);
  11201. o.push("<author>" + "tc=" + w.ID + "</author>");
  11202. }
  11203. }); });
  11204. if(iauthor.length == 0) { iauthor.push("SheetJ5"); o.push("<author>SheetJ5</author>"); }
  11205. o.push("</authors>");
  11206. o.push("<commentList>");
  11207. data.forEach(function(d) {
  11208. /* 18.7.3 CT_Comment */
  11209. var lastauthor = 0, ts = [], tcnt = 0;
  11210. if(d[1][0] && d[1][0].T && d[1][0].ID) lastauthor = iauthor.indexOf("tc=" + d[1][0].ID);
  11211. d[1].forEach(function(c) {
  11212. if(c.a) lastauthor = iauthor.indexOf(escapexml(c.a));
  11213. if(c.T) ++tcnt;
  11214. ts.push(c.t == null ? "" : escapexml(c.t));
  11215. });
  11216. if(tcnt === 0) {
  11217. d[1].forEach(function(c) {
  11218. o.push('<comment ref="' + d[0] + '" authorId="' + iauthor.indexOf(escapexml(c.a)) + '"><text>');
  11219. o.push(writetag("t", c.t == null ? "" : escapexml(c.t)));
  11220. o.push('</text></comment>');
  11221. });
  11222. } else {
  11223. /* based on Threaded Comments -> Comments projection */
  11224. o.push('<comment ref="' + d[0] + '" authorId="' + lastauthor + '"><text>');
  11225. var t = "Comment:\n " + (ts[0]) + "\n";
  11226. for(var i = 1; i < ts.length; ++i) t += "Reply:\n " + ts[i] + "\n";
  11227. o.push(writetag("t", escapexml(t)));
  11228. o.push('</text></comment>');
  11229. }
  11230. });
  11231. o.push("</commentList>");
  11232. if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
  11233. return o.join("");
  11234. }
  11235. /* [MS-XLSX] 2.1.17 */
  11236. function parse_tcmnt_xml(data, opts) {
  11237. var out = [];
  11238. var pass = false, comment = {}, tidx = 0;
  11239. data.replace(tagregex, function xml_tcmnt(x, idx) {
  11240. var y = parsexmltag(x);
  11241. switch(strip_ns(y[0])) {
  11242. case '<?xml': break;
  11243. /* 2.6.207 ThreadedComments CT_ThreadedComments */
  11244. case '<ThreadedComments': break;
  11245. case '</ThreadedComments>': break;
  11246. /* 2.6.205 threadedComment CT_ThreadedComment */
  11247. case '<threadedComment': comment = {author: y.personId, guid: y.id, ref: y.ref, T: 1}; break;
  11248. case '</threadedComment>': if(comment.t != null) out.push(comment); break;
  11249. case '<text>': case '<text': tidx = idx + x.length; break;
  11250. case '</text>': comment.t = data.slice(tidx, idx).replace(/\r\n/g, "\n").replace(/\r/g, "\n"); break;
  11251. /* 2.6.206 mentions CT_ThreadedCommentMentions TODO */
  11252. case '<mentions': case '<mentions>': pass = true; break;
  11253. case '</mentions>': pass = false; break;
  11254. /* 2.6.202 mention CT_Mention TODO */
  11255. /* 18.2.10 extLst CT_ExtensionList ? */
  11256. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  11257. /* 18.2.7 ext CT_Extension + */
  11258. case '<ext': pass=true; break;
  11259. case '</ext>': pass=false; break;
  11260. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in threaded comments');
  11261. }
  11262. return x;
  11263. });
  11264. return out;
  11265. }
  11266. function write_tcmnt_xml(comments, people, opts) {
  11267. var o = [XML_HEADER, writextag('ThreadedComments', null, { 'xmlns': XMLNS.TCMNT }).replace(/[\/]>/, ">")];
  11268. comments.forEach(function(carr) {
  11269. var rootid = "";
  11270. (carr[1] || []).forEach(function(c, idx) {
  11271. if(!c.T) { delete c.ID; return; }
  11272. if(c.a && people.indexOf(c.a) == -1) people.push(c.a);
  11273. var tcopts = {
  11274. ref: carr[0],
  11275. id: "{54EE7951-7262-4200-6969-" + ("000000000000" + opts.tcid++).slice(-12) + "}"
  11276. };
  11277. if(idx == 0) rootid = tcopts.id;
  11278. else tcopts.parentId = rootid;
  11279. c.ID = tcopts.id;
  11280. if(c.a) tcopts.personId = "{54EE7950-7262-4200-6969-" + ("000000000000" + people.indexOf(c.a)).slice(-12) + "}";
  11281. o.push(writextag('threadedComment', writetag('text', c.t||""), tcopts));
  11282. });
  11283. });
  11284. o.push('</ThreadedComments>');
  11285. return o.join("");
  11286. }
  11287. /* [MS-XLSX] 2.1.18 */
  11288. function parse_people_xml(data, opts) {
  11289. var out = [];
  11290. var pass = false;
  11291. data.replace(tagregex, function xml_tcmnt(x) {
  11292. var y = parsexmltag(x);
  11293. switch(strip_ns(y[0])) {
  11294. case '<?xml': break;
  11295. /* 2.4.85 personList CT_PersonList */
  11296. case '<personList': break;
  11297. case '</personList>': break;
  11298. /* 2.6.203 person CT_Person TODO: providers */
  11299. case '<person': out.push({name: y.displayname, id: y.id }); break;
  11300. case '</person>': break;
  11301. /* 18.2.10 extLst CT_ExtensionList ? */
  11302. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  11303. /* 18.2.7 ext CT_Extension + */
  11304. case '<ext': pass=true; break;
  11305. case '</ext>': pass=false; break;
  11306. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in threaded comments');
  11307. }
  11308. return x;
  11309. });
  11310. return out;
  11311. }
  11312. function write_people_xml(people/*, opts*/) {
  11313. var o = [XML_HEADER, writextag('personList', null, {
  11314. 'xmlns': XMLNS.TCMNT,
  11315. 'xmlns:x': XMLNS_main[0]
  11316. }).replace(/[\/]>/, ">")];
  11317. people.forEach(function(person, idx) {
  11318. o.push(writextag('person', null, {
  11319. displayName: person,
  11320. id: "{54EE7950-7262-4200-6969-" + ("000000000000" + idx).slice(-12) + "}",
  11321. userId: person,
  11322. providerId: "None"
  11323. }));
  11324. });
  11325. o.push("</personList>");
  11326. return o.join("");
  11327. }
  11328. /* [MS-XLSB] 2.4.28 BrtBeginComment */
  11329. function parse_BrtBeginComment(data) {
  11330. var out = {};
  11331. out.iauthor = data.read_shift(4);
  11332. var rfx = parse_UncheckedRfX(data, 16);
  11333. out.rfx = rfx.s;
  11334. out.ref = encode_cell(rfx.s);
  11335. data.l += 16; /*var guid = parse_GUID(data); */
  11336. return out;
  11337. }
  11338. function write_BrtBeginComment(data, o) {
  11339. if(o == null) o = new_buf(36);
  11340. o.write_shift(4, data[1].iauthor);
  11341. write_UncheckedRfX((data[0]), o);
  11342. o.write_shift(4, 0);
  11343. o.write_shift(4, 0);
  11344. o.write_shift(4, 0);
  11345. o.write_shift(4, 0);
  11346. return o;
  11347. }
  11348. /* [MS-XLSB] 2.4.327 BrtCommentAuthor */
  11349. var parse_BrtCommentAuthor = parse_XLWideString;
  11350. function write_BrtCommentAuthor(data) { return write_XLWideString(data.slice(0, 54)); }
  11351. /* [MS-XLSB] 2.1.7.8 Comments */
  11352. function parse_comments_bin(data, opts) {
  11353. var out = [];
  11354. var authors = [];
  11355. var c = {};
  11356. var pass = false;
  11357. recordhopper(data, function hopper_cmnt(val, R, RT) {
  11358. switch(RT) {
  11359. case 0x0278: /* 'BrtCommentAuthor' */
  11360. authors.push(val); break;
  11361. case 0x027B: /* 'BrtBeginComment' */
  11362. c = val; break;
  11363. case 0x027D: /* 'BrtCommentText' */
  11364. c.t = val.t; c.h = val.h; c.r = val.r; break;
  11365. case 0x027C: /* 'BrtEndComment' */
  11366. c.author = authors[c.iauthor];
  11367. delete (c).iauthor;
  11368. if(opts.sheetRows && c.rfx && opts.sheetRows <= c.rfx.r) break;
  11369. if(!c.t) c.t = "";
  11370. delete c.rfx; out.push(c); break;
  11371. case 0x0C00: /* 'BrtUid' */
  11372. break;
  11373. case 0x0023: /* 'BrtFRTBegin' */
  11374. pass = true; break;
  11375. case 0x0024: /* 'BrtFRTEnd' */
  11376. pass = false; break;
  11377. case 0x0025: /* 'BrtACBegin' */ break;
  11378. case 0x0026: /* 'BrtACEnd' */ break;
  11379. default:
  11380. if(R.T){/* empty */}
  11381. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  11382. }
  11383. });
  11384. return out;
  11385. }
  11386. function write_comments_bin(data) {
  11387. var ba = buf_array();
  11388. var iauthor = [];
  11389. write_record(ba, 0x0274 /* BrtBeginComments */);
  11390. write_record(ba, 0x0276 /* BrtBeginCommentAuthors */);
  11391. data.forEach(function(comment) {
  11392. comment[1].forEach(function(c) {
  11393. if(iauthor.indexOf(c.a) > -1) return;
  11394. iauthor.push(c.a.slice(0,54));
  11395. write_record(ba, 0x0278 /* BrtCommentAuthor */, write_BrtCommentAuthor(c.a));
  11396. });
  11397. });
  11398. write_record(ba, 0x0277 /* BrtEndCommentAuthors */);
  11399. write_record(ba, 0x0279 /* BrtBeginCommentList */);
  11400. data.forEach(function(comment) {
  11401. comment[1].forEach(function(c) {
  11402. c.iauthor = iauthor.indexOf(c.a);
  11403. var range = {s:decode_cell(comment[0]),e:decode_cell(comment[0])};
  11404. write_record(ba, 0x027B /* BrtBeginComment */, write_BrtBeginComment([range, c]));
  11405. if(c.t && c.t.length > 0) write_record(ba, 0x027D /* BrtCommentText */, write_BrtCommentText(c));
  11406. write_record(ba, 0x027C /* BrtEndComment */);
  11407. delete c.iauthor;
  11408. });
  11409. });
  11410. write_record(ba, 0x027A /* BrtEndCommentList */);
  11411. write_record(ba, 0x0275 /* BrtEndComments */);
  11412. return ba.end();
  11413. }
  11414. var CT_VBA = "application/vnd.ms-office.vbaProject";
  11415. function make_vba_xls(cfb) {
  11416. var newcfb = CFB.utils.cfb_new({ root: "R" });
  11417. cfb.FullPaths.forEach(function(p, i) {
  11418. if (p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/))
  11419. return;
  11420. var newpath = p.replace(/^[^\/]*/, "R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
  11421. CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  11422. });
  11423. return CFB.write(newcfb);
  11424. }
  11425. function fill_vba_xls(cfb, vba) {
  11426. vba.FullPaths.forEach(function(p, i) {
  11427. if (i == 0)
  11428. return;
  11429. var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
  11430. if (newpath.slice(-1) !== "/")
  11431. CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  11432. });
  11433. }
  11434. var VBAFMTS = ["xlsb", "xlsm", "xlam", "biff8", "xla"];
  11435. /* macro and dialog sheet stubs */
  11436. function parse_ds_bin() { return {'!type':'dialog'}; }
  11437. function parse_ds_xml() { return {'!type':'dialog'}; }
  11438. function parse_ms_bin() { return {'!type':'macro'}; }
  11439. function parse_ms_xml() { return {'!type':'macro'}; }
  11440. /* TODO: it will be useful to parse the function str */
  11441. var rc_to_a1 = (function(){
  11442. var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  11443. var rcbase = ({r:0,c:0});
  11444. function rcfunc($$,$1,$2,$3) {
  11445. var cRel = false, rRel = false;
  11446. if($2.length == 0) rRel = true;
  11447. else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }
  11448. if($3.length == 0) cRel = true;
  11449. else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }
  11450. var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;
  11451. if(cRel) C += rcbase.c; else --C;
  11452. if(rRel) R += rcbase.r; else --R;
  11453. return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
  11454. }
  11455. return function rc_to_a1(fstr, base) {
  11456. rcbase = base;
  11457. return fstr.replace(rcregex, rcfunc);
  11458. };
  11459. })();
  11460. 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;
  11461. var a1_to_rc = (function(){
  11462. return function a1_to_rc(fstr, base) {
  11463. return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  11464. var c = decode_col($3) - ($2 ? 0 : base.c);
  11465. var r = decode_row($5) - ($4 ? 0 : base.r);
  11466. var R = $4 == "$" ? (r+1) : (r == 0 ? "" : "[" + r + "]");
  11467. var C = $2 == "$" ? (c+1) : (c == 0 ? "" : "[" + c + "]");
  11468. return $1 + "R" + R + "C" + C;
  11469. });
  11470. };
  11471. })();
  11472. /* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
  11473. function shift_formula_str(f, delta) {
  11474. return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  11475. return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
  11476. });
  11477. }
  11478. function shift_formula_xlsx(f, range, cell) {
  11479. var r = decode_range(range), s = r.s, c = decode_cell(cell);
  11480. var delta = {r:c.r - s.r, c:c.c - s.c};
  11481. return shift_formula_str(f, delta);
  11482. }
  11483. /* TODO: parse formula */
  11484. function fuzzyfmla(f) {
  11485. if(f.length == 1) return false;
  11486. return true;
  11487. }
  11488. function _xlfn(f) {
  11489. return f.replace(/_xlfn\./g,"");
  11490. }
  11491. function parseread1(blob) { blob.l+=1; return; }
  11492. /* [MS-XLS] 2.5.51 */
  11493. function parse_ColRelU(blob, length) {
  11494. var c = blob.read_shift(length == 1 ? 1 : 2);
  11495. return [c & 0x3FFF, (c >> 14) & 1, (c >> 15) & 1];
  11496. }
  11497. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.89 */
  11498. function parse_RgceArea(blob, length, opts) {
  11499. var w = 2;
  11500. if(opts) {
  11501. if(opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
  11502. else if(opts.biff == 12) w = 4;
  11503. }
  11504. var r=blob.read_shift(w), R=blob.read_shift(w);
  11505. var c=parse_ColRelU(blob, 2);
  11506. var C=parse_ColRelU(blob, 2);
  11507. return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
  11508. }
  11509. /* BIFF 2-5 encodes flags in the row field */
  11510. function parse_RgceArea_BIFF2(blob) {
  11511. var r=parse_ColRelU(blob, 2), R=parse_ColRelU(blob, 2);
  11512. var c=blob.read_shift(1);
  11513. var C=blob.read_shift(1);
  11514. return { s:{r:r[0], c:c, cRel:r[1], rRel:r[2]}, e:{r:R[0], c:C, cRel:R[1], rRel:R[2]} };
  11515. }
  11516. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.90 */
  11517. function parse_RgceAreaRel(blob, length, opts) {
  11518. if(opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
  11519. var r=blob.read_shift(opts.biff == 12 ? 4 : 2), R=blob.read_shift(opts.biff == 12 ? 4 : 2);
  11520. var c=parse_ColRelU(blob, 2);
  11521. var C=parse_ColRelU(blob, 2);
  11522. return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
  11523. }
  11524. /* [MS-XLS] 2.5.198.109 ; [MS-XLSB] 2.5.97.91 */
  11525. function parse_RgceLoc(blob, length, opts) {
  11526. if(opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
  11527. var r = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
  11528. var c = parse_ColRelU(blob, 2);
  11529. return {r:r, c:c[0], cRel:c[1], rRel:c[2]};
  11530. }
  11531. function parse_RgceLoc_BIFF2(blob) {
  11532. var r = parse_ColRelU(blob, 2);
  11533. var c = blob.read_shift(1);
  11534. return {r:r[0], c:c, cRel:r[1], rRel:r[2]};
  11535. }
  11536. /* [MS-XLS] 2.5.198.107, 2.5.47 */
  11537. function parse_RgceElfLoc(blob) {
  11538. var r = blob.read_shift(2);
  11539. var c = blob.read_shift(2);
  11540. return {r:r, c:c & 0xFF, fQuoted:!!(c & 0x4000), cRel:c>>15, rRel:c>>15 };
  11541. }
  11542. /* [MS-XLS] 2.5.198.111 ; [MS-XLSB] 2.5.97.92 TODO */
  11543. function parse_RgceLocRel(blob, length, opts) {
  11544. var biff = opts && opts.biff ? opts.biff : 8;
  11545. if(biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
  11546. var r = blob.read_shift(biff >= 12 ? 4 : 2);
  11547. var cl = blob.read_shift(2);
  11548. var cRel = (cl & 0x4000) >> 14, rRel = (cl & 0x8000) >> 15;
  11549. cl &= 0x3FFF;
  11550. if(rRel == 1) while(r > 0x7FFFF) r -= 0x100000;
  11551. if(cRel == 1) while(cl > 0x1FFF) cl = cl - 0x4000;
  11552. return {r:r,c:cl,cRel:cRel,rRel:rRel};
  11553. }
  11554. function parse_RgceLocRel_BIFF2(blob) {
  11555. var rl = blob.read_shift(2);
  11556. var c = blob.read_shift(1);
  11557. var rRel = (rl & 0x8000) >> 15, cRel = (rl & 0x4000) >> 14;
  11558. rl &= 0x3FFF;
  11559. if(rRel == 1 && rl >= 0x2000) rl = rl - 0x4000;
  11560. if(cRel == 1 && c >= 0x80) c = c - 0x100;
  11561. return {r:rl,c:c,cRel:cRel,rRel:rRel};
  11562. }
  11563. /* [MS-XLS] 2.5.198.27 ; [MS-XLSB] 2.5.97.18 */
  11564. function parse_PtgArea(blob, length, opts) {
  11565. var type = (blob[blob.l++] & 0x60) >> 5;
  11566. var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
  11567. return [type, area];
  11568. }
  11569. /* [MS-XLS] 2.5.198.28 ; [MS-XLSB] 2.5.97.19 */
  11570. function parse_PtgArea3d(blob, length, opts) {
  11571. var type = (blob[blob.l++] & 0x60) >> 5;
  11572. var ixti = blob.read_shift(2, 'i');
  11573. var w = 8;
  11574. if(opts) switch(opts.biff) {
  11575. case 5: blob.l += 12; w = 6; break;
  11576. case 12: w = 12; break;
  11577. }
  11578. var area = parse_RgceArea(blob, w, opts);
  11579. return [type, ixti, area];
  11580. }
  11581. /* [MS-XLS] 2.5.198.29 ; [MS-XLSB] 2.5.97.20 */
  11582. function parse_PtgAreaErr(blob, length, opts) {
  11583. var type = (blob[blob.l++] & 0x60) >> 5;
  11584. blob.l += opts && (opts.biff > 8) ? 12 : (opts.biff < 8 ? 6 : 8);
  11585. return [type];
  11586. }
  11587. /* [MS-XLS] 2.5.198.30 ; [MS-XLSB] 2.5.97.21 */
  11588. function parse_PtgAreaErr3d(blob, length, opts) {
  11589. var type = (blob[blob.l++] & 0x60) >> 5;
  11590. var ixti = blob.read_shift(2);
  11591. var w = 8;
  11592. if(opts) switch(opts.biff) {
  11593. case 5: blob.l += 12; w = 6; break;
  11594. case 12: w = 12; break;
  11595. }
  11596. blob.l += w;
  11597. return [type, ixti];
  11598. }
  11599. /* [MS-XLS] 2.5.198.31 ; [MS-XLSB] 2.5.97.22 */
  11600. function parse_PtgAreaN(blob, length, opts) {
  11601. var type = (blob[blob.l++] & 0x60) >> 5;
  11602. var area = parse_RgceAreaRel(blob, length - 1, opts);
  11603. return [type, area];
  11604. }
  11605. /* [MS-XLS] 2.5.198.32 ; [MS-XLSB] 2.5.97.23 */
  11606. function parse_PtgArray(blob, length, opts) {
  11607. var type = (blob[blob.l++] & 0x60) >> 5;
  11608. blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
  11609. return [type];
  11610. }
  11611. /* [MS-XLS] 2.5.198.33 ; [MS-XLSB] 2.5.97.24 */
  11612. function parse_PtgAttrBaxcel(blob) {
  11613. var bitSemi = blob[blob.l+1] & 0x01; /* 1 = volatile */
  11614. var bitBaxcel = 1;
  11615. blob.l += 4;
  11616. return [bitSemi, bitBaxcel];
  11617. }
  11618. /* [MS-XLS] 2.5.198.34 ; [MS-XLSB] 2.5.97.25 */
  11619. function parse_PtgAttrChoose(blob, length, opts) {
  11620. blob.l +=2;
  11621. var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11622. var o = [];
  11623. /* offset is 1 less than the number of elements */
  11624. for(var i = 0; i <= offset; ++i) o.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
  11625. return o;
  11626. }
  11627. /* [MS-XLS] 2.5.198.35 ; [MS-XLSB] 2.5.97.26 */
  11628. function parse_PtgAttrGoto(blob, length, opts) {
  11629. var bitGoto = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11630. blob.l += 2;
  11631. return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  11632. }
  11633. /* [MS-XLS] 2.5.198.36 ; [MS-XLSB] 2.5.97.27 */
  11634. function parse_PtgAttrIf(blob, length, opts) {
  11635. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11636. blob.l += 2;
  11637. return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  11638. }
  11639. /* [MS-XLSB] 2.5.97.28 */
  11640. function parse_PtgAttrIfError(blob) {
  11641. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11642. blob.l += 2;
  11643. return [bitIf, blob.read_shift(2)];
  11644. }
  11645. /* [MS-XLS] 2.5.198.37 ; [MS-XLSB] 2.5.97.29 */
  11646. function parse_PtgAttrSemi(blob, length, opts) {
  11647. var bitSemi = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11648. blob.l += opts && opts.biff == 2 ? 3 : 4;
  11649. return [bitSemi];
  11650. }
  11651. /* [MS-XLS] 2.5.198.40 ; [MS-XLSB] 2.5.97.32 */
  11652. function parse_PtgAttrSpaceType(blob) {
  11653. var type = blob.read_shift(1), cch = blob.read_shift(1);
  11654. return [type, cch];
  11655. }
  11656. /* [MS-XLS] 2.5.198.38 ; [MS-XLSB] 2.5.97.30 */
  11657. function parse_PtgAttrSpace(blob) {
  11658. blob.read_shift(2);
  11659. return parse_PtgAttrSpaceType(blob, 2);
  11660. }
  11661. /* [MS-XLS] 2.5.198.39 ; [MS-XLSB] 2.5.97.31 */
  11662. function parse_PtgAttrSpaceSemi(blob) {
  11663. blob.read_shift(2);
  11664. return parse_PtgAttrSpaceType(blob, 2);
  11665. }
  11666. /* [MS-XLS] 2.5.198.84 ; [MS-XLSB] 2.5.97.68 TODO */
  11667. function parse_PtgRef(blob, length, opts) {
  11668. //var ptg = blob[blob.l] & 0x1F;
  11669. var type = (blob[blob.l] & 0x60)>>5;
  11670. blob.l += 1;
  11671. var loc = parse_RgceLoc(blob, 0, opts);
  11672. return [type, loc];
  11673. }
  11674. /* [MS-XLS] 2.5.198.88 ; [MS-XLSB] 2.5.97.72 TODO */
  11675. function parse_PtgRefN(blob, length, opts) {
  11676. var type = (blob[blob.l] & 0x60)>>5;
  11677. blob.l += 1;
  11678. var loc = parse_RgceLocRel(blob, 0, opts);
  11679. return [type, loc];
  11680. }
  11681. /* [MS-XLS] 2.5.198.85 ; [MS-XLSB] 2.5.97.69 TODO */
  11682. function parse_PtgRef3d(blob, length, opts) {
  11683. var type = (blob[blob.l] & 0x60)>>5;
  11684. blob.l += 1;
  11685. var ixti = blob.read_shift(2); // XtiIndex
  11686. if(opts && opts.biff == 5) blob.l += 12;
  11687. var loc = parse_RgceLoc(blob, 0, opts); // TODO: or RgceLocRel
  11688. return [type, ixti, loc];
  11689. }
  11690. /* [MS-XLS] 2.5.198.62 ; [MS-XLSB] 2.5.97.45 TODO */
  11691. function parse_PtgFunc(blob, length, opts) {
  11692. //var ptg = blob[blob.l] & 0x1F;
  11693. var type = (blob[blob.l] & 0x60)>>5;
  11694. blob.l += 1;
  11695. var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
  11696. return [FtabArgc[iftab], Ftab[iftab], type];
  11697. }
  11698. /* [MS-XLS] 2.5.198.63 ; [MS-XLSB] 2.5.97.46 TODO */
  11699. function parse_PtgFuncVar(blob, length, opts) {
  11700. var type = blob[blob.l++];
  11701. var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [(type == 0x58 ? -1 : 0), blob.read_shift(1)]: parsetab(blob);
  11702. return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
  11703. }
  11704. function parsetab(blob) {
  11705. return [blob[blob.l+1]>>7, blob.read_shift(2) & 0x7FFF];
  11706. }
  11707. /* [MS-XLS] 2.5.198.41 ; [MS-XLSB] 2.5.97.33 */
  11708. function parse_PtgAttrSum(blob, length, opts) {
  11709. blob.l += opts && opts.biff == 2 ? 3 : 4; return;
  11710. }
  11711. /* [MS-XLS] 2.5.198.58 ; [MS-XLSB] 2.5.97.40 */
  11712. function parse_PtgExp(blob, length, opts) {
  11713. blob.l++;
  11714. if(opts && opts.biff == 12) return [blob.read_shift(4, 'i'), 0];
  11715. var row = blob.read_shift(2);
  11716. var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11717. return [row, col];
  11718. }
  11719. /* [MS-XLS] 2.5.198.57 ; [MS-XLSB] 2.5.97.39 */
  11720. function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }
  11721. /* [MS-XLS] 2.5.198.66 ; [MS-XLSB] 2.5.97.49 */
  11722. function parse_PtgInt(blob) { blob.l++; return blob.read_shift(2); }
  11723. /* [MS-XLS] 2.5.198.42 ; [MS-XLSB] 2.5.97.34 */
  11724. function parse_PtgBool(blob) { blob.l++; return blob.read_shift(1)!==0;}
  11725. /* [MS-XLS] 2.5.198.79 ; [MS-XLSB] 2.5.97.63 */
  11726. function parse_PtgNum(blob) { blob.l++; return parse_Xnum(blob, 8); }
  11727. /* [MS-XLS] 2.5.198.89 ; [MS-XLSB] 2.5.97.74 */
  11728. function parse_PtgStr(blob, length, opts) { blob.l++; return parse_ShortXLUnicodeString(blob, length-1, opts); }
  11729. /* [MS-XLS] 2.5.192.112 + 2.5.192.11{3,4,5,6,7} */
  11730. /* [MS-XLSB] 2.5.97.93 + 2.5.97.9{4,5,6,7} */
  11731. function parse_SerAr(blob, biff) {
  11732. var val = [blob.read_shift(1)];
  11733. if(biff == 12) switch(val[0]) {
  11734. case 0x02: val[0] = 0x04; break; /* SerBool */
  11735. case 0x04: val[0] = 0x10; break; /* SerErr */
  11736. case 0x00: val[0] = 0x01; break; /* SerNum */
  11737. case 0x01: val[0] = 0x02; break; /* SerStr */
  11738. }
  11739. switch(val[0]) {
  11740. case 0x04: /* SerBool -- boolean */
  11741. val[1] = parsebool(blob, 1) ? 'TRUE' : 'FALSE';
  11742. if(biff != 12) blob.l += 7; break;
  11743. case 0x25: /* appears to be an alias */
  11744. case 0x10: /* SerErr -- error */
  11745. val[1] = BErr[blob[blob.l]];
  11746. blob.l += ((biff == 12) ? 4 : 8); break;
  11747. case 0x00: /* SerNil -- honestly, I'm not sure how to reproduce this */
  11748. blob.l += 8; break;
  11749. case 0x01: /* SerNum -- Xnum */
  11750. val[1] = parse_Xnum(blob, 8); break;
  11751. case 0x02: /* SerStr -- XLUnicodeString (<256 chars) */
  11752. val[1] = parse_XLUnicodeString2(blob, 0, {biff:biff > 0 && biff < 8 ? 2 : biff}); break;
  11753. default: throw new Error("Bad SerAr: " + val[0]); /* Unreachable */
  11754. }
  11755. return val;
  11756. }
  11757. /* [MS-XLS] 2.5.198.61 ; [MS-XLSB] 2.5.97.44 */
  11758. function parse_PtgExtraMem(blob, cce, opts) {
  11759. var count = blob.read_shift((opts.biff == 12) ? 4 : 2);
  11760. var out = [];
  11761. for(var i = 0; i != count; ++i) out.push(((opts.biff == 12) ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
  11762. return out;
  11763. }
  11764. /* [MS-XLS] 2.5.198.59 ; [MS-XLSB] 2.5.97.41 */
  11765. function parse_PtgExtraArray(blob, length, opts) {
  11766. var rows = 0, cols = 0;
  11767. if(opts.biff == 12) {
  11768. rows = blob.read_shift(4); // DRw
  11769. cols = blob.read_shift(4); // DCol
  11770. } else {
  11771. cols = 1 + blob.read_shift(1); //DColByteU
  11772. rows = 1 + blob.read_shift(2); //DRw
  11773. }
  11774. if(opts.biff >= 2 && opts.biff < 8) { --rows; if(--cols == 0) cols = 0x100; }
  11775. // $FlowIgnore
  11776. for(var i = 0, o = []; i != rows && (o[i] = []); ++i)
  11777. for(var j = 0; j != cols; ++j) o[i][j] = parse_SerAr(blob, opts.biff);
  11778. return o;
  11779. }
  11780. /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 */
  11781. function parse_PtgName(blob, length, opts) {
  11782. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11783. var w = (!opts || (opts.biff >= 8)) ? 4 : 2;
  11784. var nameindex = blob.read_shift(w);
  11785. switch(opts.biff) {
  11786. case 2: blob.l += 5; break;
  11787. case 3: case 4: blob.l += 8; break;
  11788. case 5: blob.l += 12; break;
  11789. }
  11790. return [type, 0, nameindex];
  11791. }
  11792. /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 */
  11793. function parse_PtgNameX(blob, length, opts) {
  11794. if(opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
  11795. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11796. var ixti = blob.read_shift(2); // XtiIndex
  11797. var nameindex = blob.read_shift(4);
  11798. return [type, ixti, nameindex];
  11799. }
  11800. function parse_PtgNameX_BIFF5(blob) {
  11801. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11802. var ixti = blob.read_shift(2, 'i'); // XtiIndex
  11803. blob.l += 8;
  11804. var nameindex = blob.read_shift(2);
  11805. blob.l += 12;
  11806. return [type, ixti, nameindex];
  11807. }
  11808. /* [MS-XLS] 2.5.198.70 ; [MS-XLSB] 2.5.97.54 */
  11809. function parse_PtgMemArea(blob, length, opts) {
  11810. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11811. blob.l += (opts && opts.biff == 2 ? 3 : 4);
  11812. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11813. return [type, cce];
  11814. }
  11815. /* [MS-XLS] 2.5.198.72 ; [MS-XLSB] 2.5.97.56 */
  11816. function parse_PtgMemFunc(blob, length, opts) {
  11817. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11818. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11819. return [type, cce];
  11820. }
  11821. /* [MS-XLS] 2.5.198.86 ; [MS-XLSB] 2.5.97.69 */
  11822. function parse_PtgRefErr(blob, length, opts) {
  11823. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11824. blob.l += 4;
  11825. if(opts.biff < 8) blob.l--;
  11826. if(opts.biff == 12) blob.l += 2;
  11827. return [type];
  11828. }
  11829. /* [MS-XLS] 2.5.198.87 ; [MS-XLSB] 2.5.97.71 */
  11830. function parse_PtgRefErr3d(blob, length, opts) {
  11831. var type = (blob[blob.l++] & 0x60) >> 5;
  11832. var ixti = blob.read_shift(2);
  11833. var w = 4;
  11834. if(opts) switch(opts.biff) {
  11835. case 5: w = 15; break;
  11836. case 12: w = 6; break;
  11837. }
  11838. blob.l += w;
  11839. return [type, ixti];
  11840. }
  11841. /* [MS-XLS] 2.5.198.71 ; [MS-XLSB] 2.5.97.55 */
  11842. var parse_PtgMemErr = parsenoop;
  11843. /* [MS-XLS] 2.5.198.73 ; [MS-XLSB] 2.5.97.57 */
  11844. var parse_PtgMemNoMem = parsenoop;
  11845. /* [MS-XLS] 2.5.198.92 */
  11846. var parse_PtgTbl = parsenoop;
  11847. function parse_PtgElfLoc(blob, length, opts) {
  11848. blob.l += 2;
  11849. return [parse_RgceElfLoc(blob, 4, opts)];
  11850. }
  11851. function parse_PtgElfNoop(blob) {
  11852. blob.l += 6;
  11853. return [];
  11854. }
  11855. /* [MS-XLS] 2.5.198.46 */
  11856. var parse_PtgElfCol = parse_PtgElfLoc;
  11857. /* [MS-XLS] 2.5.198.47 */
  11858. var parse_PtgElfColS = parse_PtgElfNoop;
  11859. /* [MS-XLS] 2.5.198.48 */
  11860. var parse_PtgElfColSV = parse_PtgElfNoop;
  11861. /* [MS-XLS] 2.5.198.49 */
  11862. var parse_PtgElfColV = parse_PtgElfLoc;
  11863. /* [MS-XLS] 2.5.198.50 */
  11864. function parse_PtgElfLel(blob) {
  11865. blob.l += 2;
  11866. return [parseuint16(blob), blob.read_shift(2) & 0x01];
  11867. }
  11868. /* [MS-XLS] 2.5.198.51 */
  11869. var parse_PtgElfRadical = parse_PtgElfLoc;
  11870. /* [MS-XLS] 2.5.198.52 */
  11871. var parse_PtgElfRadicalLel = parse_PtgElfLel;
  11872. /* [MS-XLS] 2.5.198.53 */
  11873. var parse_PtgElfRadicalS = parse_PtgElfNoop;
  11874. /* [MS-XLS] 2.5.198.54 */
  11875. var parse_PtgElfRw = parse_PtgElfLoc;
  11876. /* [MS-XLS] 2.5.198.55 */
  11877. var parse_PtgElfRwV = parse_PtgElfLoc;
  11878. /* [MS-XLSB] 2.5.97.52 TODO */
  11879. var PtgListRT = [
  11880. "Data",
  11881. "All",
  11882. "Headers",
  11883. "??",
  11884. "?Data2",
  11885. "??",
  11886. "?DataHeaders",
  11887. "??",
  11888. "Totals",
  11889. "??",
  11890. "??",
  11891. "??",
  11892. "?DataTotals",
  11893. "??",
  11894. "??",
  11895. "??",
  11896. "?Current"
  11897. ];
  11898. function parse_PtgList(blob) {
  11899. blob.l += 2;
  11900. var ixti = blob.read_shift(2);
  11901. var flags = blob.read_shift(2);
  11902. var idx = blob.read_shift(4);
  11903. var c = blob.read_shift(2);
  11904. var C = blob.read_shift(2);
  11905. var rt = PtgListRT[(flags >> 2) & 0x1F];
  11906. return {ixti: ixti, coltype:(flags&0x3), rt:rt, idx:idx, c:c, C:C};
  11907. }
  11908. /* [MS-XLS] 2.5.198.91 ; [MS-XLSB] 2.5.97.76 */
  11909. function parse_PtgSxName(blob) {
  11910. blob.l += 2;
  11911. return [blob.read_shift(4)];
  11912. }
  11913. /* [XLS] old spec */
  11914. function parse_PtgSheet(blob, length, opts) {
  11915. blob.l += 5;
  11916. blob.l += 2;
  11917. blob.l += (opts.biff == 2 ? 1 : 4);
  11918. return ["PTGSHEET"];
  11919. }
  11920. function parse_PtgEndSheet(blob, length, opts) {
  11921. blob.l += (opts.biff == 2 ? 4 : 5);
  11922. return ["PTGENDSHEET"];
  11923. }
  11924. function parse_PtgMemAreaN(blob) {
  11925. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11926. var cce = blob.read_shift(2);
  11927. return [type, cce];
  11928. }
  11929. function parse_PtgMemNoMemN(blob) {
  11930. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11931. var cce = blob.read_shift(2);
  11932. return [type, cce];
  11933. }
  11934. function parse_PtgAttrNoop(blob) {
  11935. blob.l += 4;
  11936. return [0, 0];
  11937. }
  11938. /* [MS-XLS] 2.5.198.25 ; [MS-XLSB] 2.5.97.16 */
  11939. var PtgTypes = {
  11940. 0x01: { n:'PtgExp', f:parse_PtgExp },
  11941. 0x02: { n:'PtgTbl', f:parse_PtgTbl },
  11942. 0x03: { n:'PtgAdd', f:parseread1 },
  11943. 0x04: { n:'PtgSub', f:parseread1 },
  11944. 0x05: { n:'PtgMul', f:parseread1 },
  11945. 0x06: { n:'PtgDiv', f:parseread1 },
  11946. 0x07: { n:'PtgPower', f:parseread1 },
  11947. 0x08: { n:'PtgConcat', f:parseread1 },
  11948. 0x09: { n:'PtgLt', f:parseread1 },
  11949. 0x0A: { n:'PtgLe', f:parseread1 },
  11950. 0x0B: { n:'PtgEq', f:parseread1 },
  11951. 0x0C: { n:'PtgGe', f:parseread1 },
  11952. 0x0D: { n:'PtgGt', f:parseread1 },
  11953. 0x0E: { n:'PtgNe', f:parseread1 },
  11954. 0x0F: { n:'PtgIsect', f:parseread1 },
  11955. 0x10: { n:'PtgUnion', f:parseread1 },
  11956. 0x11: { n:'PtgRange', f:parseread1 },
  11957. 0x12: { n:'PtgUplus', f:parseread1 },
  11958. 0x13: { n:'PtgUminus', f:parseread1 },
  11959. 0x14: { n:'PtgPercent', f:parseread1 },
  11960. 0x15: { n:'PtgParen', f:parseread1 },
  11961. 0x16: { n:'PtgMissArg', f:parseread1 },
  11962. 0x17: { n:'PtgStr', f:parse_PtgStr },
  11963. 0x1A: { n:'PtgSheet', f:parse_PtgSheet },
  11964. 0x1B: { n:'PtgEndSheet', f:parse_PtgEndSheet },
  11965. 0x1C: { n:'PtgErr', f:parse_PtgErr },
  11966. 0x1D: { n:'PtgBool', f:parse_PtgBool },
  11967. 0x1E: { n:'PtgInt', f:parse_PtgInt },
  11968. 0x1F: { n:'PtgNum', f:parse_PtgNum },
  11969. 0x20: { n:'PtgArray', f:parse_PtgArray },
  11970. 0x21: { n:'PtgFunc', f:parse_PtgFunc },
  11971. 0x22: { n:'PtgFuncVar', f:parse_PtgFuncVar },
  11972. 0x23: { n:'PtgName', f:parse_PtgName },
  11973. 0x24: { n:'PtgRef', f:parse_PtgRef },
  11974. 0x25: { n:'PtgArea', f:parse_PtgArea },
  11975. 0x26: { n:'PtgMemArea', f:parse_PtgMemArea },
  11976. 0x27: { n:'PtgMemErr', f:parse_PtgMemErr },
  11977. 0x28: { n:'PtgMemNoMem', f:parse_PtgMemNoMem },
  11978. 0x29: { n:'PtgMemFunc', f:parse_PtgMemFunc },
  11979. 0x2A: { n:'PtgRefErr', f:parse_PtgRefErr },
  11980. 0x2B: { n:'PtgAreaErr', f:parse_PtgAreaErr },
  11981. 0x2C: { n:'PtgRefN', f:parse_PtgRefN },
  11982. 0x2D: { n:'PtgAreaN', f:parse_PtgAreaN },
  11983. 0x2E: { n:'PtgMemAreaN', f:parse_PtgMemAreaN },
  11984. 0x2F: { n:'PtgMemNoMemN', f:parse_PtgMemNoMemN },
  11985. 0x39: { n:'PtgNameX', f:parse_PtgNameX },
  11986. 0x3A: { n:'PtgRef3d', f:parse_PtgRef3d },
  11987. 0x3B: { n:'PtgArea3d', f:parse_PtgArea3d },
  11988. 0x3C: { n:'PtgRefErr3d', f:parse_PtgRefErr3d },
  11989. 0x3D: { n:'PtgAreaErr3d', f:parse_PtgAreaErr3d },
  11990. 0xFF: {}
  11991. };
  11992. /* These are duplicated in the PtgTypes table */
  11993. var PtgDupes = {
  11994. 0x40: 0x20, 0x60: 0x20,
  11995. 0x41: 0x21, 0x61: 0x21,
  11996. 0x42: 0x22, 0x62: 0x22,
  11997. 0x43: 0x23, 0x63: 0x23,
  11998. 0x44: 0x24, 0x64: 0x24,
  11999. 0x45: 0x25, 0x65: 0x25,
  12000. 0x46: 0x26, 0x66: 0x26,
  12001. 0x47: 0x27, 0x67: 0x27,
  12002. 0x48: 0x28, 0x68: 0x28,
  12003. 0x49: 0x29, 0x69: 0x29,
  12004. 0x4A: 0x2A, 0x6A: 0x2A,
  12005. 0x4B: 0x2B, 0x6B: 0x2B,
  12006. 0x4C: 0x2C, 0x6C: 0x2C,
  12007. 0x4D: 0x2D, 0x6D: 0x2D,
  12008. 0x4E: 0x2E, 0x6E: 0x2E,
  12009. 0x4F: 0x2F, 0x6F: 0x2F,
  12010. 0x58: 0x22, 0x78: 0x22,
  12011. 0x59: 0x39, 0x79: 0x39,
  12012. 0x5A: 0x3A, 0x7A: 0x3A,
  12013. 0x5B: 0x3B, 0x7B: 0x3B,
  12014. 0x5C: 0x3C, 0x7C: 0x3C,
  12015. 0x5D: 0x3D, 0x7D: 0x3D
  12016. };
  12017. var Ptg18 = {
  12018. 0x01: { n:'PtgElfLel', f:parse_PtgElfLel },
  12019. 0x02: { n:'PtgElfRw', f:parse_PtgElfRw },
  12020. 0x03: { n:'PtgElfCol', f:parse_PtgElfCol },
  12021. 0x06: { n:'PtgElfRwV', f:parse_PtgElfRwV },
  12022. 0x07: { n:'PtgElfColV', f:parse_PtgElfColV },
  12023. 0x0A: { n:'PtgElfRadical', f:parse_PtgElfRadical },
  12024. 0x0B: { n:'PtgElfRadicalS', f:parse_PtgElfRadicalS },
  12025. 0x0D: { n:'PtgElfColS', f:parse_PtgElfColS },
  12026. 0x0F: { n:'PtgElfColSV', f:parse_PtgElfColSV },
  12027. 0x10: { n:'PtgElfRadicalLel', f:parse_PtgElfRadicalLel },
  12028. 0x19: { n:'PtgList', f:parse_PtgList },
  12029. 0x1D: { n:'PtgSxName', f:parse_PtgSxName },
  12030. 0xFF: {}
  12031. };
  12032. var Ptg19 = {
  12033. 0x00: { n:'PtgAttrNoop', f:parse_PtgAttrNoop },
  12034. 0x01: { n:'PtgAttrSemi', f:parse_PtgAttrSemi },
  12035. 0x02: { n:'PtgAttrIf', f:parse_PtgAttrIf },
  12036. 0x04: { n:'PtgAttrChoose', f:parse_PtgAttrChoose },
  12037. 0x08: { n:'PtgAttrGoto', f:parse_PtgAttrGoto },
  12038. 0x10: { n:'PtgAttrSum', f:parse_PtgAttrSum },
  12039. 0x20: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
  12040. 0x21: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
  12041. 0x40: { n:'PtgAttrSpace', f:parse_PtgAttrSpace },
  12042. 0x41: { n:'PtgAttrSpaceSemi', f:parse_PtgAttrSpaceSemi },
  12043. 0x80: { n:'PtgAttrIfError', f:parse_PtgAttrIfError },
  12044. 0xFF: {}
  12045. };
  12046. /* [MS-XLS] 2.5.198.103 ; [MS-XLSB] 2.5.97.87 */
  12047. function parse_RgbExtra(blob, length, rgce, opts) {
  12048. if(opts.biff < 8) return parsenoop(blob, length);
  12049. var target = blob.l + length;
  12050. var o = [];
  12051. for(var i = 0; i !== rgce.length; ++i) {
  12052. switch(rgce[i][0]) {
  12053. case 'PtgArray': /* PtgArray -> PtgExtraArray */
  12054. rgce[i][1] = parse_PtgExtraArray(blob, 0, opts);
  12055. o.push(rgce[i][1]);
  12056. break;
  12057. case 'PtgMemArea': /* PtgMemArea -> PtgExtraMem */
  12058. rgce[i][2] = parse_PtgExtraMem(blob, rgce[i][1], opts);
  12059. o.push(rgce[i][2]);
  12060. break;
  12061. case 'PtgExp': /* PtgExp -> PtgExtraCol */
  12062. if(opts && opts.biff == 12) {
  12063. rgce[i][1][1] = blob.read_shift(4);
  12064. o.push(rgce[i][1]);
  12065. } break;
  12066. case 'PtgList': /* TODO: PtgList -> PtgExtraList */
  12067. case 'PtgElfRadicalS': /* TODO: PtgElfRadicalS -> PtgExtraElf */
  12068. case 'PtgElfColS': /* TODO: PtgElfColS -> PtgExtraElf */
  12069. case 'PtgElfColSV': /* TODO: PtgElfColSV -> PtgExtraElf */
  12070. throw "Unsupported " + rgce[i][0];
  12071. default: break;
  12072. }
  12073. }
  12074. length = target - blob.l;
  12075. /* note: this is technically an error but Excel disregards */
  12076. //if(target !== blob.l && blob.l !== target - length) throw new Error(target + " != " + blob.l);
  12077. if(length !== 0) o.push(parsenoop(blob, length));
  12078. return o;
  12079. }
  12080. /* [MS-XLS] 2.5.198.104 ; [MS-XLSB] 2.5.97.88 */
  12081. function parse_Rgce(blob, length, opts) {
  12082. var target = blob.l + length;
  12083. var R, id, ptgs = [];
  12084. while(target != blob.l) {
  12085. length = target - blob.l;
  12086. id = blob[blob.l];
  12087. R = PtgTypes[id] || PtgTypes[PtgDupes[id]];
  12088. if(id === 0x18 || id === 0x19) R = (id === 0x18 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
  12089. if(!R || !R.f) { /*ptgs.push*/(parsenoop(blob, length)); }
  12090. else { ptgs.push([R.n, R.f(blob, length, opts)]); }
  12091. }
  12092. return ptgs;
  12093. }
  12094. function stringify_array(f) {
  12095. var o = [];
  12096. for(var i = 0; i < f.length; ++i) {
  12097. var x = f[i], r = [];
  12098. for(var j = 0; j < x.length; ++j) {
  12099. var y = x[j];
  12100. if(y) switch(y[0]) {
  12101. // TODO: handle embedded quotes
  12102. case 0x02:
  12103. r.push('"' + y[1].replace(/"/g,'""') + '"'); break;
  12104. default: r.push(y[1]);
  12105. } else r.push("");
  12106. }
  12107. o.push(r.join(","));
  12108. }
  12109. return o.join(";");
  12110. }
  12111. /* [MS-XLS] 2.2.2 ; [MS-XLSB] 2.2.2 TODO */
  12112. var PtgBinOp = {
  12113. PtgAdd: "+",
  12114. PtgConcat: "&",
  12115. PtgDiv: "/",
  12116. PtgEq: "=",
  12117. PtgGe: ">=",
  12118. PtgGt: ">",
  12119. PtgLe: "<=",
  12120. PtgLt: "<",
  12121. PtgMul: "*",
  12122. PtgNe: "<>",
  12123. PtgPower: "^",
  12124. PtgSub: "-"
  12125. };
  12126. // TODO: explore space
  12127. function make_3d_range(start, end) {
  12128. var s = start.lastIndexOf("!"), e = end.lastIndexOf("!");
  12129. if(s == -1 && e == -1) return start + ":" + end;
  12130. if(s > 0 && e > 0 && start.slice(0, s).toLowerCase() == end.slice(0, e).toLowerCase()) return start + ":" + end.slice(e+1);
  12131. console.error("Cannot hydrate range", start, end);
  12132. return start + ":" + end;
  12133. }
  12134. function get_ixti_raw(supbooks, ixti, opts) {
  12135. if(!supbooks) return "SH33TJSERR0";
  12136. if(opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
  12137. if(!supbooks.XTI) return "SH33TJSERR6";
  12138. var XTI = supbooks.XTI[ixti];
  12139. if(opts.biff < 8) {
  12140. if(ixti > 10000) ixti-= 65536;
  12141. if(ixti < 0) ixti = -ixti;
  12142. return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
  12143. }
  12144. if(!XTI) return "SH33TJSERR1";
  12145. var o = "";
  12146. if(opts.biff > 8) switch(supbooks[XTI[0]][0]) {
  12147. case 0x0165: /* 'BrtSupSelf' */
  12148. o = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
  12149. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  12150. case 0x0166: /* 'BrtSupSame' */
  12151. if(opts.SID != null) return supbooks.SheetNames[opts.SID];
  12152. return "SH33TJSSAME" + supbooks[XTI[0]][0];
  12153. case 0x0163: /* 'BrtSupBookSrc' */
  12154. /* falls through */
  12155. default: return "SH33TJSSRC" + supbooks[XTI[0]][0];
  12156. }
  12157. switch(supbooks[XTI[0]][0][0]) {
  12158. case 0x0401:
  12159. o = XTI[1] == -1 ? "#REF" : (supbooks.SheetNames[XTI[1]] || "SH33TJSERR3");
  12160. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  12161. case 0x3A01: return supbooks[XTI[0]].slice(1).map(function(name) { return name.Name; }).join(";;"); //return "SH33TJSERR8";
  12162. default:
  12163. if(!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
  12164. o = XTI[1] == -1 ? "#REF" : (supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4");
  12165. return XTI[1] == XTI[2] ? o : o + ":" + supbooks[XTI[0]][0][3][XTI[2]];
  12166. }
  12167. }
  12168. function get_ixti(supbooks, ixti, opts) {
  12169. var ixtiraw = get_ixti_raw(supbooks, ixti, opts);
  12170. return ixtiraw == "#REF" ? ixtiraw : formula_quote_sheet_name(ixtiraw, opts);
  12171. }
  12172. function stringify_formula(formula/*Array<any>*/, range, cell, supbooks, opts) {
  12173. var biff = (opts && opts.biff) || 8;
  12174. var _range = /*range != null ? range :*/ {s:{c:0, r:0},e:{c:0, r:0}};
  12175. var stack = [], e1, e2, c, ixti=0, nameidx=0, r, sname="";
  12176. if(!formula[0] || !formula[0][0]) return "";
  12177. var last_sp = -1, sp = "";
  12178. for(var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
  12179. var f = formula[0][ff];
  12180. switch(f[0]) {
  12181. case 'PtgUminus': /* [MS-XLS] 2.5.198.93 */
  12182. stack.push("-" + stack.pop()); break;
  12183. case 'PtgUplus': /* [MS-XLS] 2.5.198.95 */
  12184. stack.push("+" + stack.pop()); break;
  12185. case 'PtgPercent': /* [MS-XLS] 2.5.198.81 */
  12186. stack.push(stack.pop() + "%"); break;
  12187. case 'PtgAdd': /* [MS-XLS] 2.5.198.26 */
  12188. case 'PtgConcat': /* [MS-XLS] 2.5.198.43 */
  12189. case 'PtgDiv': /* [MS-XLS] 2.5.198.45 */
  12190. case 'PtgEq': /* [MS-XLS] 2.5.198.56 */
  12191. case 'PtgGe': /* [MS-XLS] 2.5.198.64 */
  12192. case 'PtgGt': /* [MS-XLS] 2.5.198.65 */
  12193. case 'PtgLe': /* [MS-XLS] 2.5.198.68 */
  12194. case 'PtgLt': /* [MS-XLS] 2.5.198.69 */
  12195. case 'PtgMul': /* [MS-XLS] 2.5.198.75 */
  12196. case 'PtgNe': /* [MS-XLS] 2.5.198.78 */
  12197. case 'PtgPower': /* [MS-XLS] 2.5.198.82 */
  12198. case 'PtgSub': /* [MS-XLS] 2.5.198.90 */
  12199. e1 = stack.pop(); e2 = stack.pop();
  12200. if(last_sp >= 0) {
  12201. switch(formula[0][last_sp][1][0]) {
  12202. case 0:
  12203. // $FlowIgnore
  12204. sp = fill(" ", formula[0][last_sp][1][1]); break;
  12205. case 1:
  12206. // $FlowIgnore
  12207. sp = fill("\r", formula[0][last_sp][1][1]); break;
  12208. default:
  12209. sp = "";
  12210. // $FlowIgnore
  12211. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  12212. }
  12213. e2 = e2 + sp;
  12214. last_sp = -1;
  12215. }
  12216. stack.push(e2+PtgBinOp[f[0]]+e1);
  12217. break;
  12218. case 'PtgIsect': /* [MS-XLS] 2.5.198.67 */
  12219. e1 = stack.pop(); e2 = stack.pop();
  12220. stack.push(e2+" "+e1);
  12221. break;
  12222. case 'PtgUnion': /* [MS-XLS] 2.5.198.94 */
  12223. e1 = stack.pop(); e2 = stack.pop();
  12224. stack.push(e2+","+e1);
  12225. break;
  12226. case 'PtgRange': /* [MS-XLS] 2.5.198.83 */
  12227. e1 = stack.pop(); e2 = stack.pop();
  12228. stack.push(make_3d_range(e2,e1));
  12229. break;
  12230. case 'PtgAttrChoose': /* [MS-XLS] 2.5.198.34 */
  12231. break;
  12232. case 'PtgAttrGoto': /* [MS-XLS] 2.5.198.35 */
  12233. break;
  12234. case 'PtgAttrIf': /* [MS-XLS] 2.5.198.36 */
  12235. break;
  12236. case 'PtgAttrIfError': /* [MS-XLSB] 2.5.97.28 */
  12237. break;
  12238. case 'PtgRef': /* [MS-XLS] 2.5.198.84 */
  12239. c = shift_cell_xls((f[1][1]), _range, opts);
  12240. stack.push(encode_cell_xls(c, biff));
  12241. break;
  12242. case 'PtgRefN': /* [MS-XLS] 2.5.198.88 */
  12243. c = cell ? shift_cell_xls((f[1][1]), cell, opts) : (f[1][1]);
  12244. stack.push(encode_cell_xls(c, biff));
  12245. break;
  12246. case 'PtgRef3d': /* [MS-XLS] 2.5.198.85 */
  12247. ixti = f[1][1]; c = shift_cell_xls((f[1][2]), _range, opts);
  12248. sname = get_ixti(supbooks, ixti, opts);
  12249. var w = sname; /* IE9 fails on defined names */ // eslint-disable-line no-unused-vars
  12250. stack.push(sname + "!" + encode_cell_xls(c, biff));
  12251. break;
  12252. case 'PtgFunc': /* [MS-XLS] 2.5.198.62 */
  12253. case 'PtgFuncVar': /* [MS-XLS] 2.5.198.63 */
  12254. /* f[1] = [argc, func, type] */
  12255. var argc = (f[1][0]), func = (f[1][1]);
  12256. if(!argc) argc = 0;
  12257. argc &= 0x7F;
  12258. var args = argc == 0 ? [] : stack.slice(-argc);
  12259. stack.length -= argc;
  12260. if(func === 'User') func = args.shift();
  12261. stack.push(func + "(" + args.join(",") + ")");
  12262. break;
  12263. case 'PtgBool': /* [MS-XLS] 2.5.198.42 */
  12264. stack.push(f[1] ? "TRUE" : "FALSE"); break;
  12265. case 'PtgInt': /* [MS-XLS] 2.5.198.66 */
  12266. stack.push(f[1]); break;
  12267. case 'PtgNum': /* [MS-XLS] 2.5.198.79 TODO: precision? */
  12268. stack.push(String(f[1])); break;
  12269. case 'PtgStr': /* [MS-XLS] 2.5.198.89 */
  12270. // $FlowIgnore
  12271. stack.push('"' + f[1].replace(/"/g, '""') + '"'); break;
  12272. case 'PtgErr': /* [MS-XLS] 2.5.198.57 */
  12273. stack.push(f[1]); break;
  12274. case 'PtgAreaN': /* [MS-XLS] 2.5.198.31 TODO */
  12275. r = shift_range_xls(f[1][1], cell ? {s:cell} : _range, opts);
  12276. stack.push(encode_range_xls((r), opts));
  12277. break;
  12278. case 'PtgArea': /* [MS-XLS] 2.5.198.27 TODO: fixed points */
  12279. r = shift_range_xls(f[1][1], _range, opts);
  12280. stack.push(encode_range_xls((r), opts));
  12281. break;
  12282. case 'PtgArea3d': /* [MS-XLS] 2.5.198.28 TODO */
  12283. ixti = f[1][1]; r = f[1][2];
  12284. sname = get_ixti(supbooks, ixti, opts);
  12285. stack.push(sname + "!" + encode_range_xls((r), opts));
  12286. break;
  12287. case 'PtgAttrSum': /* [MS-XLS] 2.5.198.41 */
  12288. stack.push("SUM(" + stack.pop() + ")");
  12289. break;
  12290. case 'PtgAttrBaxcel': /* [MS-XLS] 2.5.198.33 */
  12291. case 'PtgAttrSemi': /* [MS-XLS] 2.5.198.37 */
  12292. break;
  12293. case 'PtgName': /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 TODO: revisions */
  12294. /* f[1] = type, 0, nameindex */
  12295. nameidx = (f[1][2]);
  12296. var lbl = (supbooks.names||[])[nameidx-1] || (supbooks[0]||[])[nameidx];
  12297. var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
  12298. /* [MS-XLSB] 2.5.97.10 Ftab -- last verified 20220204 */
  12299. if(name && name.slice(0,6) == "_xlfn." && !opts.xlfn) name = name.slice(6);
  12300. stack.push(name);
  12301. break;
  12302. case 'PtgNameX': /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 TODO: revisions */
  12303. /* f[1] = type, ixti, nameindex */
  12304. var bookidx = (f[1][1]); nameidx = (f[1][2]); var externbook;
  12305. /* TODO: Properly handle missing values -- this should be using get_ixti_raw primarily */
  12306. if(opts.biff <= 5) {
  12307. if(bookidx < 0) bookidx = -bookidx;
  12308. if(supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
  12309. } else {
  12310. var o = "";
  12311. if(((supbooks[bookidx]||[])[0]||[])[0] == 0x3A01){/* empty */}
  12312. else if(((supbooks[bookidx]||[])[0]||[])[0] == 0x0401){
  12313. if(supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
  12314. o = supbooks.SheetNames[supbooks[bookidx][nameidx].itab-1] + "!";
  12315. }
  12316. }
  12317. else o = supbooks.SheetNames[nameidx-1]+ "!";
  12318. if(supbooks[bookidx] && supbooks[bookidx][nameidx]) o += supbooks[bookidx][nameidx].Name;
  12319. else if(supbooks[0] && supbooks[0][nameidx]) o += supbooks[0][nameidx].Name;
  12320. else {
  12321. var ixtidata = (get_ixti_raw(supbooks, bookidx, opts)||"").split(";;");
  12322. if(ixtidata[nameidx - 1]) o = ixtidata[nameidx - 1]; // TODO: confirm this is correct
  12323. else o += "SH33TJSERRX";
  12324. }
  12325. stack.push(o);
  12326. break;
  12327. }
  12328. if(!externbook) externbook = {Name: "SH33TJSERRY"};
  12329. stack.push(externbook.Name);
  12330. break;
  12331. case 'PtgParen': /* [MS-XLS] 2.5.198.80 */
  12332. var lp = '(', rp = ')';
  12333. if(last_sp >= 0) {
  12334. sp = "";
  12335. switch(formula[0][last_sp][1][0]) {
  12336. // $FlowIgnore
  12337. case 2: lp = fill(" ", formula[0][last_sp][1][1]) + lp; break;
  12338. // $FlowIgnore
  12339. case 3: lp = fill("\r", formula[0][last_sp][1][1]) + lp; break;
  12340. // $FlowIgnore
  12341. case 4: rp = fill(" ", formula[0][last_sp][1][1]) + rp; break;
  12342. // $FlowIgnore
  12343. case 5: rp = fill("\r", formula[0][last_sp][1][1]) + rp; break;
  12344. default:
  12345. // $FlowIgnore
  12346. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  12347. }
  12348. last_sp = -1;
  12349. }
  12350. stack.push(lp + stack.pop() + rp); break;
  12351. case 'PtgRefErr': /* [MS-XLS] 2.5.198.86 */
  12352. stack.push('#REF!'); break;
  12353. case 'PtgRefErr3d': /* [MS-XLS] 2.5.198.87 */
  12354. stack.push('#REF!'); break;
  12355. case 'PtgExp': /* [MS-XLS] 2.5.198.58 TODO */
  12356. c = {c:(f[1][1]),r:(f[1][0])};
  12357. var q = ({c: cell.c, r:cell.r});
  12358. if(supbooks.sharedf[encode_cell(c)]) {
  12359. var parsedf = (supbooks.sharedf[encode_cell(c)]);
  12360. stack.push(stringify_formula(parsedf, _range, q, supbooks, opts));
  12361. } else {
  12362. var fnd = false;
  12363. for(e1=0;e1!=supbooks.arrayf.length; ++e1) {
  12364. /* TODO: should be something like range_has */
  12365. e2 = supbooks.arrayf[e1];
  12366. if(c.c < e2[0].s.c || c.c > e2[0].e.c) continue;
  12367. if(c.r < e2[0].s.r || c.r > e2[0].e.r) continue;
  12368. stack.push(stringify_formula(e2[1], _range, q, supbooks, opts));
  12369. fnd = true;
  12370. break;
  12371. }
  12372. if(!fnd) stack.push(f[1]);
  12373. }
  12374. break;
  12375. case 'PtgArray': /* [MS-XLS] 2.5.198.32 TODO */
  12376. stack.push("{" + stringify_array(f[1]) + "}");
  12377. break;
  12378. case 'PtgMemArea': /* [MS-XLS] 2.5.198.70 TODO: confirm this is a non-display */
  12379. //stack.push("(" + f[2].map(encode_range).join(",") + ")");
  12380. break;
  12381. case 'PtgAttrSpace': /* [MS-XLS] 2.5.198.38 */
  12382. case 'PtgAttrSpaceSemi': /* [MS-XLS] 2.5.198.39 */
  12383. last_sp = ff;
  12384. break;
  12385. case 'PtgTbl': /* [MS-XLS] 2.5.198.92 TODO */
  12386. break;
  12387. case 'PtgMemErr': /* [MS-XLS] 2.5.198.71 */
  12388. break;
  12389. case 'PtgMissArg': /* [MS-XLS] 2.5.198.74 */
  12390. stack.push("");
  12391. break;
  12392. case 'PtgAreaErr': /* [MS-XLS] 2.5.198.29 */
  12393. stack.push("#REF!"); break;
  12394. case 'PtgAreaErr3d': /* [MS-XLS] 2.5.198.30 */
  12395. stack.push("#REF!"); break;
  12396. case 'PtgList': /* [MS-XLSB] 2.5.97.52 */
  12397. // $FlowIgnore
  12398. stack.push("Table" + f[1].idx + "[#" + f[1].rt + "]");
  12399. break;
  12400. case 'PtgMemAreaN':
  12401. case 'PtgMemNoMemN':
  12402. case 'PtgAttrNoop':
  12403. case 'PtgSheet':
  12404. case 'PtgEndSheet':
  12405. break;
  12406. case 'PtgMemFunc': /* [MS-XLS] 2.5.198.72 TODO */
  12407. break;
  12408. case 'PtgMemNoMem': /* [MS-XLS] 2.5.198.73 TODO */
  12409. break;
  12410. case 'PtgElfCol': /* [MS-XLS] 2.5.198.46 */
  12411. case 'PtgElfColS': /* [MS-XLS] 2.5.198.47 */
  12412. case 'PtgElfColSV': /* [MS-XLS] 2.5.198.48 */
  12413. case 'PtgElfColV': /* [MS-XLS] 2.5.198.49 */
  12414. case 'PtgElfLel': /* [MS-XLS] 2.5.198.50 */
  12415. case 'PtgElfRadical': /* [MS-XLS] 2.5.198.51 */
  12416. case 'PtgElfRadicalLel': /* [MS-XLS] 2.5.198.52 */
  12417. case 'PtgElfRadicalS': /* [MS-XLS] 2.5.198.53 */
  12418. case 'PtgElfRw': /* [MS-XLS] 2.5.198.54 */
  12419. case 'PtgElfRwV': /* [MS-XLS] 2.5.198.55 */
  12420. throw new Error("Unsupported ELFs");
  12421. case 'PtgSxName': /* [MS-XLS] 2.5.198.91 TODO -- find a test case */
  12422. throw new Error('Unrecognized Formula Token: ' + String(f));
  12423. default: throw new Error('Unrecognized Formula Token: ' + String(f));
  12424. }
  12425. var PtgNonDisp = ['PtgAttrSpace', 'PtgAttrSpaceSemi', 'PtgAttrGoto'];
  12426. if(opts.biff != 3) if(last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
  12427. f = formula[0][last_sp];
  12428. var _left = true;
  12429. switch(f[1][0]) {
  12430. /* note: some bad XLSB files omit the PtgParen */
  12431. case 4: _left = false;
  12432. /* falls through */
  12433. case 0:
  12434. // $FlowIgnore
  12435. sp = fill(" ", f[1][1]); break;
  12436. case 5: _left = false;
  12437. /* falls through */
  12438. case 1:
  12439. // $FlowIgnore
  12440. sp = fill("\r", f[1][1]); break;
  12441. default:
  12442. sp = "";
  12443. // $FlowIgnore
  12444. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f[1][0]);
  12445. }
  12446. stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
  12447. last_sp = -1;
  12448. }
  12449. }
  12450. if(stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
  12451. if(stack[0] == "TRUE") return true; if(stack[0] == "FALSE") return false;
  12452. return stack[0];
  12453. }
  12454. /* [MS-XLS] 2.5.198.1 TODO */
  12455. function parse_ArrayParsedFormula(blob, length, opts) {
  12456. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  12457. var rgcb, cce = blob.read_shift(len); // length of rgce
  12458. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  12459. var rgce = parse_Rgce(blob, cce, opts);
  12460. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  12461. blob.l = target;
  12462. return [rgce, rgcb];
  12463. }
  12464. /* [MS-XLS] 2.5.198.3 TODO */
  12465. function parse_XLSCellParsedFormula(blob, length, opts) {
  12466. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  12467. var rgcb, cce = blob.read_shift(len); // length of rgce
  12468. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  12469. var rgce = parse_Rgce(blob, cce, opts);
  12470. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  12471. blob.l = target;
  12472. return [rgce, rgcb];
  12473. }
  12474. /* [MS-XLS] 2.5.198.21 */
  12475. function parse_NameParsedFormula(blob, length, opts, cce) {
  12476. var target = blob.l + length;
  12477. var rgce = parse_Rgce(blob, cce, opts);
  12478. var rgcb;
  12479. if(target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
  12480. return [rgce, rgcb];
  12481. }
  12482. /* [MS-XLS] 2.5.198.118 TODO */
  12483. function parse_SharedParsedFormula(blob, length, opts) {
  12484. var target = blob.l + length;
  12485. var rgcb, cce = blob.read_shift(2); // length of rgce
  12486. var rgce = parse_Rgce(blob, cce, opts);
  12487. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  12488. if(length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
  12489. return [rgce, rgcb];
  12490. }
  12491. /* [MS-XLS] 2.5.133 TODO: how to emit empty strings? */
  12492. function parse_FormulaValue(blob) {
  12493. var b;
  12494. if(__readUInt16LE(blob,blob.l + 6) !== 0xFFFF) return [parse_Xnum(blob),'n'];
  12495. switch(blob[blob.l]) {
  12496. case 0x00: blob.l += 8; return ["String", 's'];
  12497. case 0x01: b = blob[blob.l+2] === 0x1; blob.l += 8; return [b,'b'];
  12498. case 0x02: b = blob[blob.l+2]; blob.l += 8; return [b,'e'];
  12499. case 0x03: blob.l += 8; return ["",'s'];
  12500. }
  12501. return [];
  12502. }
  12503. function write_FormulaValue(value) {
  12504. if(value == null) {
  12505. // Blank String Value
  12506. var o = new_buf(8);
  12507. o.write_shift(1, 0x03);
  12508. o.write_shift(1, 0);
  12509. o.write_shift(2, 0);
  12510. o.write_shift(2, 0);
  12511. o.write_shift(2, 0xFFFF);
  12512. return o;
  12513. } else if(typeof value == "number") return write_Xnum(value);
  12514. return write_Xnum(0);
  12515. }
  12516. /* [MS-XLS] 2.4.127 TODO */
  12517. function parse_Formula(blob, length, opts) {
  12518. var end = blob.l + length;
  12519. var cell = parse_XLSCell(blob, 6);
  12520. if(opts.biff == 2) ++blob.l;
  12521. var val = parse_FormulaValue(blob,8);
  12522. var flags = blob.read_shift(1);
  12523. if(opts.biff != 2) {
  12524. blob.read_shift(1);
  12525. if(opts.biff >= 5) {
  12526. /*var chn = */blob.read_shift(4);
  12527. }
  12528. }
  12529. var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
  12530. return {cell:cell, val:val[0], formula:cbf, shared: (flags >> 3) & 1, tt:val[1]};
  12531. }
  12532. function write_Formula(cell, R, C, opts, os) {
  12533. // Cell
  12534. var o1 = write_XLSCell(R, C, os);
  12535. // FormulaValue
  12536. var o2 = write_FormulaValue(cell.v);
  12537. // flags + cache
  12538. var o3 = new_buf(6);
  12539. var flags = 0x01 | 0x20;
  12540. o3.write_shift(2, flags);
  12541. o3.write_shift(4, 0);
  12542. // CellParsedFormula
  12543. var bf = new_buf(cell.bf.length);
  12544. for(var i = 0; i < cell.bf.length; ++i) bf[i] = cell.bf[i];
  12545. var out = bconcat([o1, o2, o3, bf]);
  12546. return out;
  12547. }
  12548. /* XLSB Parsed Formula records have the same shape */
  12549. function parse_XLSBParsedFormula(data, length, opts) {
  12550. var cce = data.read_shift(4);
  12551. var rgce = parse_Rgce(data, cce, opts);
  12552. var cb = data.read_shift(4);
  12553. var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
  12554. return [rgce, rgcb];
  12555. }
  12556. /* [MS-XLSB] 2.5.97.1 ArrayParsedFormula */
  12557. var parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
  12558. /* [MS-XLSB] 2.5.97.4 CellParsedFormula */
  12559. var parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
  12560. /* [MS-XLSB] 2.5.97.8 DVParsedFormula */
  12561. //var parse_XLSBDVParsedFormula = parse_XLSBParsedFormula;
  12562. /* [MS-XLSB] 2.5.97.9 FRTParsedFormula */
  12563. //var parse_XLSBFRTParsedFormula = parse_XLSBParsedFormula2;
  12564. /* [MS-XLSB] 2.5.97.12 NameParsedFormula */
  12565. var parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
  12566. /* [MS-XLSB] 2.5.97.98 SharedParsedFormula */
  12567. var parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
  12568. /* Writes a PtgNum or PtgInt */
  12569. function write_XLSBFormulaNum(val) {
  12570. if((val | 0) == val && val < Math.pow(2,16) && val >= 0) {
  12571. var oint = new_buf(11);
  12572. oint.write_shift(4, 3);
  12573. oint.write_shift(1, 0x1e);
  12574. oint.write_shift(2, val);
  12575. oint.write_shift(4, 0);
  12576. return oint;
  12577. }
  12578. var num = new_buf(17);
  12579. num.write_shift(4, 11);
  12580. num.write_shift(1, 0x1f);
  12581. num.write_shift(8, val);
  12582. num.write_shift(4, 0);
  12583. return num;
  12584. }
  12585. /* Writes a PtgErr */
  12586. function write_XLSBFormulaErr(val) {
  12587. var oint = new_buf(10);
  12588. oint.write_shift(4, 2);
  12589. oint.write_shift(1, 0x1C);
  12590. oint.write_shift(1, val);
  12591. oint.write_shift(4, 0);
  12592. return oint;
  12593. }
  12594. /* Writes a PtgBool */
  12595. function write_XLSBFormulaBool(val) {
  12596. var oint = new_buf(10);
  12597. oint.write_shift(4, 2);
  12598. oint.write_shift(1, 0x1D);
  12599. oint.write_shift(1, val?1:0);
  12600. oint.write_shift(4, 0);
  12601. return oint;
  12602. }
  12603. /* Writes a PtgStr */
  12604. function write_XLSBFormulaStr(val) {
  12605. var preamble = new_buf(7);
  12606. preamble.write_shift(4, 3 + 2 * val.length);
  12607. preamble.write_shift(1, 0x17);
  12608. preamble.write_shift(2, val.length);
  12609. var body = new_buf(2 * val.length);
  12610. body.write_shift(2 * val.length, val, "utf16le");
  12611. var postamble = new_buf(4);
  12612. postamble.write_shift(4, 0);
  12613. return bconcat([preamble, body, postamble]);
  12614. }
  12615. /* Writes a PtgRef */
  12616. function write_XLSBFormulaRef(str) {
  12617. var cell = decode_cell(str);
  12618. var out = new_buf(15);
  12619. out.write_shift(4, 7);
  12620. out.write_shift(1, 0x04 | ((1)<<5));
  12621. out.write_shift(4, cell.r);
  12622. out.write_shift(2, cell.c | ((str.charAt(0) == "$" ? 0 : 1)<<14) | ((str.match(/\$\d/) ? 0 : 1)<<15)); // <== ColRelShort
  12623. out.write_shift(4, 0);
  12624. return out;
  12625. }
  12626. /* Writes a PtgRef3d */
  12627. function write_XLSBFormulaRef3D(str, wb) {
  12628. var lastbang = str.lastIndexOf("!");
  12629. var sname = str.slice(0, lastbang);
  12630. str = str.slice(lastbang+1);
  12631. var cell = decode_cell(str);
  12632. if(sname.charAt(0) == "'") sname = sname.slice(1, -1).replace(/''/g, "'");
  12633. var out = new_buf(17);
  12634. out.write_shift(4, 9);
  12635. out.write_shift(1, 0x1A | ((1)<<5));
  12636. out.write_shift(2, 2 + wb.SheetNames.map(function(n) { return n.toLowerCase(); }).indexOf(sname.toLowerCase()));
  12637. out.write_shift(4, cell.r);
  12638. out.write_shift(2, cell.c | ((str.charAt(0) == "$" ? 0 : 1)<<14) | ((str.match(/\$\d/) ? 0 : 1)<<15)); // <== ColRelShort
  12639. out.write_shift(4, 0);
  12640. return out;
  12641. }
  12642. /* Writes a PtgRefErr3d */
  12643. function write_XLSBFormulaRefErr3D(str, wb) {
  12644. var lastbang = str.lastIndexOf("!");
  12645. var sname = str.slice(0, lastbang);
  12646. str = str.slice(lastbang+1);
  12647. if(sname.charAt(0) == "'") sname = sname.slice(1, -1).replace(/''/g, "'");
  12648. var out = new_buf(17);
  12649. out.write_shift(4, 9);
  12650. out.write_shift(1, 0x1C | ((1)<<5));
  12651. out.write_shift(2, 2 + wb.SheetNames.map(function(n) { return n.toLowerCase(); }).indexOf(sname.toLowerCase()));
  12652. out.write_shift(4, 0);
  12653. out.write_shift(2, 0); // <== ColRelShort
  12654. out.write_shift(4, 0);
  12655. return out;
  12656. }
  12657. /* Writes a single sheet range [PtgRef PtgRef PtgRange] */
  12658. function write_XLSBFormulaRange(_str) {
  12659. var parts = _str.split(":"), str = parts[0];
  12660. var out = new_buf(23);
  12661. out.write_shift(4, 15);
  12662. /* start cell */
  12663. str = parts[0]; var cell = decode_cell(str);
  12664. out.write_shift(1, 0x04 | ((1)<<5));
  12665. out.write_shift(4, cell.r);
  12666. out.write_shift(2, cell.c | ((str.charAt(0) == "$" ? 0 : 1)<<14) | ((str.match(/\$\d/) ? 0 : 1)<<15)); // <== ColRelShort
  12667. out.write_shift(4, 0);
  12668. /* end cell */
  12669. str = parts[1]; cell = decode_cell(str);
  12670. out.write_shift(1, 0x04 | ((1)<<5));
  12671. out.write_shift(4, cell.r);
  12672. out.write_shift(2, cell.c | ((str.charAt(0) == "$" ? 0 : 1)<<14) | ((str.match(/\$\d/) ? 0 : 1)<<15)); // <== ColRelShort
  12673. out.write_shift(4, 0);
  12674. /* PtgRange */
  12675. out.write_shift(1, 0x11);
  12676. out.write_shift(4, 0);
  12677. return out;
  12678. }
  12679. /* Writes a range with explicit sheet name [PtgRef3D PtgRef3D PtgRange] */
  12680. function write_XLSBFormulaRangeWS(_str, wb) {
  12681. var lastbang = _str.lastIndexOf("!");
  12682. var sname = _str.slice(0, lastbang);
  12683. _str = _str.slice(lastbang+1);
  12684. if(sname.charAt(0) == "'") sname = sname.slice(1, -1).replace(/''/g, "'");
  12685. var parts = _str.split(":"); str = parts[0];
  12686. var out = new_buf(27);
  12687. out.write_shift(4, 19);
  12688. /* start cell */
  12689. var str = parts[0], cell = decode_cell(str);
  12690. out.write_shift(1, 0x1A | ((1)<<5));
  12691. out.write_shift(2, 2 + wb.SheetNames.map(function(n) { return n.toLowerCase(); }).indexOf(sname.toLowerCase()));
  12692. out.write_shift(4, cell.r);
  12693. out.write_shift(2, cell.c | ((str.charAt(0) == "$" ? 0 : 1)<<14) | ((str.match(/\$\d/) ? 0 : 1)<<15)); // <== ColRelShort
  12694. /* end cell */
  12695. str = parts[1]; cell = decode_cell(str);
  12696. out.write_shift(1, 0x1A | ((1)<<5));
  12697. out.write_shift(2, 2 + wb.SheetNames.map(function(n) { return n.toLowerCase(); }).indexOf(sname.toLowerCase()));
  12698. out.write_shift(4, cell.r);
  12699. out.write_shift(2, cell.c | ((str.charAt(0) == "$" ? 0 : 1)<<14) | ((str.match(/\$\d/) ? 0 : 1)<<15)); // <== ColRelShort
  12700. /* PtgRange */
  12701. out.write_shift(1, 0x11);
  12702. out.write_shift(4, 0);
  12703. return out;
  12704. }
  12705. /* Writes a range with explicit sheet name [PtgArea3d] */
  12706. function write_XLSBFormulaArea3D(_str, wb) {
  12707. var lastbang = _str.lastIndexOf("!");
  12708. var sname = _str.slice(0, lastbang);
  12709. _str = _str.slice(lastbang+1);
  12710. if(sname.charAt(0) == "'") sname = sname.slice(1, -1).replace(/''/g, "'");
  12711. var range = decode_range(_str);
  12712. var out = new_buf(23);
  12713. out.write_shift(4, 15);
  12714. out.write_shift(1, 0x1B | ((1)<<5));
  12715. out.write_shift(2, 2 + wb.SheetNames.map(function(n) { return n.toLowerCase(); }).indexOf(sname.toLowerCase()));
  12716. out.write_shift(4, range.s.r);
  12717. out.write_shift(4, range.e.r);
  12718. out.write_shift(2, range.s.c);
  12719. out.write_shift(2, range.e.c);
  12720. out.write_shift(4, 0);
  12721. return out;
  12722. }
  12723. /* General Formula */
  12724. function write_XLSBFormula(val, wb) {
  12725. if(typeof val == "number") return write_XLSBFormulaNum(val);
  12726. if(typeof val == "boolean") return write_XLSBFormulaBool(val);
  12727. if(/^#(DIV\/0!|GETTING_DATA|N\/A|NAME\?|NULL!|NUM!|REF!|VALUE!)$/.test(val)) return write_XLSBFormulaErr(+RBErr[val]);
  12728. if(val.match(/^\$?(?:[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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})$/)) return write_XLSBFormulaRef(val);
  12729. if(val.match(/^\$?(?:[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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})$/)) return write_XLSBFormulaRange(val);
  12730. if(val.match(/^#REF!\$?(?:[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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})$/)) return write_XLSBFormulaArea3D(val, wb);
  12731. if(val.match(/^(?:'[^\\\/?*\[\]:]*'|[^'][^\\\/?*\[\]:'`~!@#$%^()\-=+{}|;,<.>]*)!\$?(?:[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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})$/)) return write_XLSBFormulaRef3D(val, wb);
  12732. if(val.match(/^(?:'[^\\\/?*\[\]:]*'|[^'][^\\\/?*\[\]:'`~!@#$%^()\-=+{}|;,<.>]*)!\$?(?:[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D]|[A-Z]{1,2})\$?(?: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})$/)) return write_XLSBFormulaRangeWS(val, wb);
  12733. if(/^(?:'[^\\\/?*\[\]:]*'|[^'][^\\\/?*\[\]:'`~!@#$%^()\-=+{}|;,<.>]*)!#REF!$/.test(val)) return write_XLSBFormulaRefErr3D(val, wb);
  12734. if(/^".*"$/.test(val)) return write_XLSBFormulaStr(val);
  12735. if(/^[+-]\d+$/.test(val)) return write_XLSBFormulaNum(parseInt(val, 10));
  12736. throw "Formula |" + val + "| not supported for XLSB";
  12737. }
  12738. var write_XLSBNameParsedFormula = write_XLSBFormula;
  12739. var Cetab = {
  12740. 0: "BEEP",
  12741. 1: "OPEN",
  12742. 2: "OPEN.LINKS",
  12743. 3: "CLOSE.ALL",
  12744. 4: "SAVE",
  12745. 5: "SAVE.AS",
  12746. 6: "FILE.DELETE",
  12747. 7: "PAGE.SETUP",
  12748. 8: "PRINT",
  12749. 9: "PRINTER.SETUP",
  12750. 10: "QUIT",
  12751. 11: "NEW.WINDOW",
  12752. 12: "ARRANGE.ALL",
  12753. 13: "WINDOW.SIZE",
  12754. 14: "WINDOW.MOVE",
  12755. 15: "FULL",
  12756. 16: "CLOSE",
  12757. 17: "RUN",
  12758. 22: "SET.PRINT.AREA",
  12759. 23: "SET.PRINT.TITLES",
  12760. 24: "SET.PAGE.BREAK",
  12761. 25: "REMOVE.PAGE.BREAK",
  12762. 26: "FONT",
  12763. 27: "DISPLAY",
  12764. 28: "PROTECT.DOCUMENT",
  12765. 29: "PRECISION",
  12766. 30: "A1.R1C1",
  12767. 31: "CALCULATE.NOW",
  12768. 32: "CALCULATION",
  12769. 34: "DATA.FIND",
  12770. 35: "EXTRACT",
  12771. 36: "DATA.DELETE",
  12772. 37: "SET.DATABASE",
  12773. 38: "SET.CRITERIA",
  12774. 39: "SORT",
  12775. 40: "DATA.SERIES",
  12776. 41: "TABLE",
  12777. 42: "FORMAT.NUMBER",
  12778. 43: "ALIGNMENT",
  12779. 44: "STYLE",
  12780. 45: "BORDER",
  12781. 46: "CELL.PROTECTION",
  12782. 47: "COLUMN.WIDTH",
  12783. 48: "UNDO",
  12784. 49: "CUT",
  12785. 50: "COPY",
  12786. 51: "PASTE",
  12787. 52: "CLEAR",
  12788. 53: "PASTE.SPECIAL",
  12789. 54: "EDIT.DELETE",
  12790. 55: "INSERT",
  12791. 56: "FILL.RIGHT",
  12792. 57: "FILL.DOWN",
  12793. 61: "DEFINE.NAME",
  12794. 62: "CREATE.NAMES",
  12795. 63: "FORMULA.GOTO",
  12796. 64: "FORMULA.FIND",
  12797. 65: "SELECT.LAST.CELL",
  12798. 66: "SHOW.ACTIVE.CELL",
  12799. 67: "GALLERY.AREA",
  12800. 68: "GALLERY.BAR",
  12801. 69: "GALLERY.COLUMN",
  12802. 70: "GALLERY.LINE",
  12803. 71: "GALLERY.PIE",
  12804. 72: "GALLERY.SCATTER",
  12805. 73: "COMBINATION",
  12806. 74: "PREFERRED",
  12807. 75: "ADD.OVERLAY",
  12808. 76: "GRIDLINES",
  12809. 77: "SET.PREFERRED",
  12810. 78: "AXES",
  12811. 79: "LEGEND",
  12812. 80: "ATTACH.TEXT",
  12813. 81: "ADD.ARROW",
  12814. 82: "SELECT.CHART",
  12815. 83: "SELECT.PLOT.AREA",
  12816. 84: "PATTERNS",
  12817. 85: "MAIN.CHART",
  12818. 86: "OVERLAY",
  12819. 87: "SCALE",
  12820. 88: "FORMAT.LEGEND",
  12821. 89: "FORMAT.TEXT",
  12822. 90: "EDIT.REPEAT",
  12823. 91: "PARSE",
  12824. 92: "JUSTIFY",
  12825. 93: "HIDE",
  12826. 94: "UNHIDE",
  12827. 95: "WORKSPACE",
  12828. 96: "FORMULA",
  12829. 97: "FORMULA.FILL",
  12830. 98: "FORMULA.ARRAY",
  12831. 99: "DATA.FIND.NEXT",
  12832. 100: "DATA.FIND.PREV",
  12833. 101: "FORMULA.FIND.NEXT",
  12834. 102: "FORMULA.FIND.PREV",
  12835. 103: "ACTIVATE",
  12836. 104: "ACTIVATE.NEXT",
  12837. 105: "ACTIVATE.PREV",
  12838. 106: "UNLOCKED.NEXT",
  12839. 107: "UNLOCKED.PREV",
  12840. 108: "COPY.PICTURE",
  12841. 109: "SELECT",
  12842. 110: "DELETE.NAME",
  12843. 111: "DELETE.FORMAT",
  12844. 112: "VLINE",
  12845. 113: "HLINE",
  12846. 114: "VPAGE",
  12847. 115: "HPAGE",
  12848. 116: "VSCROLL",
  12849. 117: "HSCROLL",
  12850. 118: "ALERT",
  12851. 119: "NEW",
  12852. 120: "CANCEL.COPY",
  12853. 121: "SHOW.CLIPBOARD",
  12854. 122: "MESSAGE",
  12855. 124: "PASTE.LINK",
  12856. 125: "APP.ACTIVATE",
  12857. 126: "DELETE.ARROW",
  12858. 127: "ROW.HEIGHT",
  12859. 128: "FORMAT.MOVE",
  12860. 129: "FORMAT.SIZE",
  12861. 130: "FORMULA.REPLACE",
  12862. 131: "SEND.KEYS",
  12863. 132: "SELECT.SPECIAL",
  12864. 133: "APPLY.NAMES",
  12865. 134: "REPLACE.FONT",
  12866. 135: "FREEZE.PANES",
  12867. 136: "SHOW.INFO",
  12868. 137: "SPLIT",
  12869. 138: "ON.WINDOW",
  12870. 139: "ON.DATA",
  12871. 140: "DISABLE.INPUT",
  12872. 142: "OUTLINE",
  12873. 143: "LIST.NAMES",
  12874. 144: "FILE.CLOSE",
  12875. 145: "SAVE.WORKBOOK",
  12876. 146: "DATA.FORM",
  12877. 147: "COPY.CHART",
  12878. 148: "ON.TIME",
  12879. 149: "WAIT",
  12880. 150: "FORMAT.FONT",
  12881. 151: "FILL.UP",
  12882. 152: "FILL.LEFT",
  12883. 153: "DELETE.OVERLAY",
  12884. 155: "SHORT.MENUS",
  12885. 159: "SET.UPDATE.STATUS",
  12886. 161: "COLOR.PALETTE",
  12887. 162: "DELETE.STYLE",
  12888. 163: "WINDOW.RESTORE",
  12889. 164: "WINDOW.MAXIMIZE",
  12890. 166: "CHANGE.LINK",
  12891. 167: "CALCULATE.DOCUMENT",
  12892. 168: "ON.KEY",
  12893. 169: "APP.RESTORE",
  12894. 170: "APP.MOVE",
  12895. 171: "APP.SIZE",
  12896. 172: "APP.MINIMIZE",
  12897. 173: "APP.MAXIMIZE",
  12898. 174: "BRING.TO.FRONT",
  12899. 175: "SEND.TO.BACK",
  12900. 185: "MAIN.CHART.TYPE",
  12901. 186: "OVERLAY.CHART.TYPE",
  12902. 187: "SELECT.END",
  12903. 188: "OPEN.MAIL",
  12904. 189: "SEND.MAIL",
  12905. 190: "STANDARD.FONT",
  12906. 191: "CONSOLIDATE",
  12907. 192: "SORT.SPECIAL",
  12908. 193: "GALLERY.3D.AREA",
  12909. 194: "GALLERY.3D.COLUMN",
  12910. 195: "GALLERY.3D.LINE",
  12911. 196: "GALLERY.3D.PIE",
  12912. 197: "VIEW.3D",
  12913. 198: "GOAL.SEEK",
  12914. 199: "WORKGROUP",
  12915. 200: "FILL.GROUP",
  12916. 201: "UPDATE.LINK",
  12917. 202: "PROMOTE",
  12918. 203: "DEMOTE",
  12919. 204: "SHOW.DETAIL",
  12920. 206: "UNGROUP",
  12921. 207: "OBJECT.PROPERTIES",
  12922. 208: "SAVE.NEW.OBJECT",
  12923. 209: "SHARE",
  12924. 210: "SHARE.NAME",
  12925. 211: "DUPLICATE",
  12926. 212: "APPLY.STYLE",
  12927. 213: "ASSIGN.TO.OBJECT",
  12928. 214: "OBJECT.PROTECTION",
  12929. 215: "HIDE.OBJECT",
  12930. 216: "SET.EXTRACT",
  12931. 217: "CREATE.PUBLISHER",
  12932. 218: "SUBSCRIBE.TO",
  12933. 219: "ATTRIBUTES",
  12934. 220: "SHOW.TOOLBAR",
  12935. 222: "PRINT.PREVIEW",
  12936. 223: "EDIT.COLOR",
  12937. 224: "SHOW.LEVELS",
  12938. 225: "FORMAT.MAIN",
  12939. 226: "FORMAT.OVERLAY",
  12940. 227: "ON.RECALC",
  12941. 228: "EDIT.SERIES",
  12942. 229: "DEFINE.STYLE",
  12943. 240: "LINE.PRINT",
  12944. 243: "ENTER.DATA",
  12945. 249: "GALLERY.RADAR",
  12946. 250: "MERGE.STYLES",
  12947. 251: "EDITION.OPTIONS",
  12948. 252: "PASTE.PICTURE",
  12949. 253: "PASTE.PICTURE.LINK",
  12950. 254: "SPELLING",
  12951. 256: "ZOOM",
  12952. 259: "INSERT.OBJECT",
  12953. 260: "WINDOW.MINIMIZE",
  12954. 265: "SOUND.NOTE",
  12955. 266: "SOUND.PLAY",
  12956. 267: "FORMAT.SHAPE",
  12957. 268: "EXTEND.POLYGON",
  12958. 269: "FORMAT.AUTO",
  12959. 272: "GALLERY.3D.BAR",
  12960. 273: "GALLERY.3D.SURFACE",
  12961. 274: "FILL.AUTO",
  12962. 276: "CUSTOMIZE.TOOLBAR",
  12963. 277: "ADD.TOOL",
  12964. 278: "EDIT.OBJECT",
  12965. 279: "ON.DOUBLECLICK",
  12966. 280: "ON.ENTRY",
  12967. 281: "WORKBOOK.ADD",
  12968. 282: "WORKBOOK.MOVE",
  12969. 283: "WORKBOOK.COPY",
  12970. 284: "WORKBOOK.OPTIONS",
  12971. 285: "SAVE.WORKSPACE",
  12972. 288: "CHART.WIZARD",
  12973. 289: "DELETE.TOOL",
  12974. 290: "MOVE.TOOL",
  12975. 291: "WORKBOOK.SELECT",
  12976. 292: "WORKBOOK.ACTIVATE",
  12977. 293: "ASSIGN.TO.TOOL",
  12978. 295: "COPY.TOOL",
  12979. 296: "RESET.TOOL",
  12980. 297: "CONSTRAIN.NUMERIC",
  12981. 298: "PASTE.TOOL",
  12982. 302: "WORKBOOK.NEW",
  12983. 305: "SCENARIO.CELLS",
  12984. 306: "SCENARIO.DELETE",
  12985. 307: "SCENARIO.ADD",
  12986. 308: "SCENARIO.EDIT",
  12987. 309: "SCENARIO.SHOW",
  12988. 310: "SCENARIO.SHOW.NEXT",
  12989. 311: "SCENARIO.SUMMARY",
  12990. 312: "PIVOT.TABLE.WIZARD",
  12991. 313: "PIVOT.FIELD.PROPERTIES",
  12992. 314: "PIVOT.FIELD",
  12993. 315: "PIVOT.ITEM",
  12994. 316: "PIVOT.ADD.FIELDS",
  12995. 318: "OPTIONS.CALCULATION",
  12996. 319: "OPTIONS.EDIT",
  12997. 320: "OPTIONS.VIEW",
  12998. 321: "ADDIN.MANAGER",
  12999. 322: "MENU.EDITOR",
  13000. 323: "ATTACH.TOOLBARS",
  13001. 324: "VBAActivate",
  13002. 325: "OPTIONS.CHART",
  13003. 328: "VBA.INSERT.FILE",
  13004. 330: "VBA.PROCEDURE.DEFINITION",
  13005. 336: "ROUTING.SLIP",
  13006. 338: "ROUTE.DOCUMENT",
  13007. 339: "MAIL.LOGON",
  13008. 342: "INSERT.PICTURE",
  13009. 343: "EDIT.TOOL",
  13010. 344: "GALLERY.DOUGHNUT",
  13011. 350: "CHART.TREND",
  13012. 352: "PIVOT.ITEM.PROPERTIES",
  13013. 354: "WORKBOOK.INSERT",
  13014. 355: "OPTIONS.TRANSITION",
  13015. 356: "OPTIONS.GENERAL",
  13016. 370: "FILTER.ADVANCED",
  13017. 373: "MAIL.ADD.MAILER",
  13018. 374: "MAIL.DELETE.MAILER",
  13019. 375: "MAIL.REPLY",
  13020. 376: "MAIL.REPLY.ALL",
  13021. 377: "MAIL.FORWARD",
  13022. 378: "MAIL.NEXT.LETTER",
  13023. 379: "DATA.LABEL",
  13024. 380: "INSERT.TITLE",
  13025. 381: "FONT.PROPERTIES",
  13026. 382: "MACRO.OPTIONS",
  13027. 383: "WORKBOOK.HIDE",
  13028. 384: "WORKBOOK.UNHIDE",
  13029. 385: "WORKBOOK.DELETE",
  13030. 386: "WORKBOOK.NAME",
  13031. 388: "GALLERY.CUSTOM",
  13032. 390: "ADD.CHART.AUTOFORMAT",
  13033. 391: "DELETE.CHART.AUTOFORMAT",
  13034. 392: "CHART.ADD.DATA",
  13035. 393: "AUTO.OUTLINE",
  13036. 394: "TAB.ORDER",
  13037. 395: "SHOW.DIALOG",
  13038. 396: "SELECT.ALL",
  13039. 397: "UNGROUP.SHEETS",
  13040. 398: "SUBTOTAL.CREATE",
  13041. 399: "SUBTOTAL.REMOVE",
  13042. 400: "RENAME.OBJECT",
  13043. 412: "WORKBOOK.SCROLL",
  13044. 413: "WORKBOOK.NEXT",
  13045. 414: "WORKBOOK.PREV",
  13046. 415: "WORKBOOK.TAB.SPLIT",
  13047. 416: "FULL.SCREEN",
  13048. 417: "WORKBOOK.PROTECT",
  13049. 420: "SCROLLBAR.PROPERTIES",
  13050. 421: "PIVOT.SHOW.PAGES",
  13051. 422: "TEXT.TO.COLUMNS",
  13052. 423: "FORMAT.CHARTTYPE",
  13053. 424: "LINK.FORMAT",
  13054. 425: "TRACER.DISPLAY",
  13055. 430: "TRACER.NAVIGATE",
  13056. 431: "TRACER.CLEAR",
  13057. 432: "TRACER.ERROR",
  13058. 433: "PIVOT.FIELD.GROUP",
  13059. 434: "PIVOT.FIELD.UNGROUP",
  13060. 435: "CHECKBOX.PROPERTIES",
  13061. 436: "LABEL.PROPERTIES",
  13062. 437: "LISTBOX.PROPERTIES",
  13063. 438: "EDITBOX.PROPERTIES",
  13064. 439: "PIVOT.REFRESH",
  13065. 440: "LINK.COMBO",
  13066. 441: "OPEN.TEXT",
  13067. 442: "HIDE.DIALOG",
  13068. 443: "SET.DIALOG.FOCUS",
  13069. 444: "ENABLE.OBJECT",
  13070. 445: "PUSHBUTTON.PROPERTIES",
  13071. 446: "SET.DIALOG.DEFAULT",
  13072. 447: "FILTER",
  13073. 448: "FILTER.SHOW.ALL",
  13074. 449: "CLEAR.OUTLINE",
  13075. 450: "FUNCTION.WIZARD",
  13076. 451: "ADD.LIST.ITEM",
  13077. 452: "SET.LIST.ITEM",
  13078. 453: "REMOVE.LIST.ITEM",
  13079. 454: "SELECT.LIST.ITEM",
  13080. 455: "SET.CONTROL.VALUE",
  13081. 456: "SAVE.COPY.AS",
  13082. 458: "OPTIONS.LISTS.ADD",
  13083. 459: "OPTIONS.LISTS.DELETE",
  13084. 460: "SERIES.AXES",
  13085. 461: "SERIES.X",
  13086. 462: "SERIES.Y",
  13087. 463: "ERRORBAR.X",
  13088. 464: "ERRORBAR.Y",
  13089. 465: "FORMAT.CHART",
  13090. 466: "SERIES.ORDER",
  13091. 467: "MAIL.LOGOFF",
  13092. 468: "CLEAR.ROUTING.SLIP",
  13093. 469: "APP.ACTIVATE.MICROSOFT",
  13094. 470: "MAIL.EDIT.MAILER",
  13095. 471: "ON.SHEET",
  13096. 472: "STANDARD.WIDTH",
  13097. 473: "SCENARIO.MERGE",
  13098. 474: "SUMMARY.INFO",
  13099. 475: "FIND.FILE",
  13100. 476: "ACTIVE.CELL.FONT",
  13101. 477: "ENABLE.TIPWIZARD",
  13102. 478: "VBA.MAKE.ADDIN",
  13103. 480: "INSERTDATATABLE",
  13104. 481: "WORKGROUP.OPTIONS",
  13105. 482: "MAIL.SEND.MAILER",
  13106. 485: "AUTOCORRECT",
  13107. 489: "POST.DOCUMENT",
  13108. 491: "PICKLIST",
  13109. 493: "VIEW.SHOW",
  13110. 494: "VIEW.DEFINE",
  13111. 495: "VIEW.DELETE",
  13112. 509: "SHEET.BACKGROUND",
  13113. 510: "INSERT.MAP.OBJECT",
  13114. 511: "OPTIONS.MENONO",
  13115. 517: "MSOCHECKS",
  13116. 518: "NORMAL",
  13117. 519: "LAYOUT",
  13118. 520: "RM.PRINT.AREA",
  13119. 521: "CLEAR.PRINT.AREA",
  13120. 522: "ADD.PRINT.AREA",
  13121. 523: "MOVE.BRK",
  13122. 545: "HIDECURR.NOTE",
  13123. 546: "HIDEALL.NOTES",
  13124. 547: "DELETE.NOTE",
  13125. 548: "TRAVERSE.NOTES",
  13126. 549: "ACTIVATE.NOTES",
  13127. 620: "PROTECT.REVISIONS",
  13128. 621: "UNPROTECT.REVISIONS",
  13129. 647: "OPTIONS.ME",
  13130. 653: "WEB.PUBLISH",
  13131. 667: "NEWWEBQUERY",
  13132. 673: "PIVOT.TABLE.CHART",
  13133. 753: "OPTIONS.SAVE",
  13134. 755: "OPTIONS.SPELL",
  13135. 808: "HIDEALL.INKANNOTS"
  13136. };
  13137. var Ftab = {
  13138. 0: "COUNT",
  13139. 1: "IF",
  13140. 2: "ISNA",
  13141. 3: "ISERROR",
  13142. 4: "SUM",
  13143. 5: "AVERAGE",
  13144. 6: "MIN",
  13145. 7: "MAX",
  13146. 8: "ROW",
  13147. 9: "COLUMN",
  13148. 10: "NA",
  13149. 11: "NPV",
  13150. 12: "STDEV",
  13151. 13: "DOLLAR",
  13152. 14: "FIXED",
  13153. 15: "SIN",
  13154. 16: "COS",
  13155. 17: "TAN",
  13156. 18: "ATAN",
  13157. 19: "PI",
  13158. 20: "SQRT",
  13159. 21: "EXP",
  13160. 22: "LN",
  13161. 23: "LOG10",
  13162. 24: "ABS",
  13163. 25: "INT",
  13164. 26: "SIGN",
  13165. 27: "ROUND",
  13166. 28: "LOOKUP",
  13167. 29: "INDEX",
  13168. 30: "REPT",
  13169. 31: "MID",
  13170. 32: "LEN",
  13171. 33: "VALUE",
  13172. 34: "TRUE",
  13173. 35: "FALSE",
  13174. 36: "AND",
  13175. 37: "OR",
  13176. 38: "NOT",
  13177. 39: "MOD",
  13178. 40: "DCOUNT",
  13179. 41: "DSUM",
  13180. 42: "DAVERAGE",
  13181. 43: "DMIN",
  13182. 44: "DMAX",
  13183. 45: "DSTDEV",
  13184. 46: "VAR",
  13185. 47: "DVAR",
  13186. 48: "TEXT",
  13187. 49: "LINEST",
  13188. 50: "TREND",
  13189. 51: "LOGEST",
  13190. 52: "GROWTH",
  13191. 53: "GOTO",
  13192. 54: "HALT",
  13193. 55: "RETURN",
  13194. 56: "PV",
  13195. 57: "FV",
  13196. 58: "NPER",
  13197. 59: "PMT",
  13198. 60: "RATE",
  13199. 61: "MIRR",
  13200. 62: "IRR",
  13201. 63: "RAND",
  13202. 64: "MATCH",
  13203. 65: "DATE",
  13204. 66: "TIME",
  13205. 67: "DAY",
  13206. 68: "MONTH",
  13207. 69: "YEAR",
  13208. 70: "WEEKDAY",
  13209. 71: "HOUR",
  13210. 72: "MINUTE",
  13211. 73: "SECOND",
  13212. 74: "NOW",
  13213. 75: "AREAS",
  13214. 76: "ROWS",
  13215. 77: "COLUMNS",
  13216. 78: "OFFSET",
  13217. 79: "ABSREF",
  13218. 80: "RELREF",
  13219. 81: "ARGUMENT",
  13220. 82: "SEARCH",
  13221. 83: "TRANSPOSE",
  13222. 84: "ERROR",
  13223. 85: "STEP",
  13224. 86: "TYPE",
  13225. 87: "ECHO",
  13226. 88: "SET.NAME",
  13227. 89: "CALLER",
  13228. 90: "DEREF",
  13229. 91: "WINDOWS",
  13230. 92: "SERIES",
  13231. 93: "DOCUMENTS",
  13232. 94: "ACTIVE.CELL",
  13233. 95: "SELECTION",
  13234. 96: "RESULT",
  13235. 97: "ATAN2",
  13236. 98: "ASIN",
  13237. 99: "ACOS",
  13238. 100: "CHOOSE",
  13239. 101: "HLOOKUP",
  13240. 102: "VLOOKUP",
  13241. 103: "LINKS",
  13242. 104: "INPUT",
  13243. 105: "ISREF",
  13244. 106: "GET.FORMULA",
  13245. 107: "GET.NAME",
  13246. 108: "SET.VALUE",
  13247. 109: "LOG",
  13248. 110: "EXEC",
  13249. 111: "CHAR",
  13250. 112: "LOWER",
  13251. 113: "UPPER",
  13252. 114: "PROPER",
  13253. 115: "LEFT",
  13254. 116: "RIGHT",
  13255. 117: "EXACT",
  13256. 118: "TRIM",
  13257. 119: "REPLACE",
  13258. 120: "SUBSTITUTE",
  13259. 121: "CODE",
  13260. 122: "NAMES",
  13261. 123: "DIRECTORY",
  13262. 124: "FIND",
  13263. 125: "CELL",
  13264. 126: "ISERR",
  13265. 127: "ISTEXT",
  13266. 128: "ISNUMBER",
  13267. 129: "ISBLANK",
  13268. 130: "T",
  13269. 131: "N",
  13270. 132: "FOPEN",
  13271. 133: "FCLOSE",
  13272. 134: "FSIZE",
  13273. 135: "FREADLN",
  13274. 136: "FREAD",
  13275. 137: "FWRITELN",
  13276. 138: "FWRITE",
  13277. 139: "FPOS",
  13278. 140: "DATEVALUE",
  13279. 141: "TIMEVALUE",
  13280. 142: "SLN",
  13281. 143: "SYD",
  13282. 144: "DDB",
  13283. 145: "GET.DEF",
  13284. 146: "REFTEXT",
  13285. 147: "TEXTREF",
  13286. 148: "INDIRECT",
  13287. 149: "REGISTER",
  13288. 150: "CALL",
  13289. 151: "ADD.BAR",
  13290. 152: "ADD.MENU",
  13291. 153: "ADD.COMMAND",
  13292. 154: "ENABLE.COMMAND",
  13293. 155: "CHECK.COMMAND",
  13294. 156: "RENAME.COMMAND",
  13295. 157: "SHOW.BAR",
  13296. 158: "DELETE.MENU",
  13297. 159: "DELETE.COMMAND",
  13298. 160: "GET.CHART.ITEM",
  13299. 161: "DIALOG.BOX",
  13300. 162: "CLEAN",
  13301. 163: "MDETERM",
  13302. 164: "MINVERSE",
  13303. 165: "MMULT",
  13304. 166: "FILES",
  13305. 167: "IPMT",
  13306. 168: "PPMT",
  13307. 169: "COUNTA",
  13308. 170: "CANCEL.KEY",
  13309. 171: "FOR",
  13310. 172: "WHILE",
  13311. 173: "BREAK",
  13312. 174: "NEXT",
  13313. 175: "INITIATE",
  13314. 176: "REQUEST",
  13315. 177: "POKE",
  13316. 178: "EXECUTE",
  13317. 179: "TERMINATE",
  13318. 180: "RESTART",
  13319. 181: "HELP",
  13320. 182: "GET.BAR",
  13321. 183: "PRODUCT",
  13322. 184: "FACT",
  13323. 185: "GET.CELL",
  13324. 186: "GET.WORKSPACE",
  13325. 187: "GET.WINDOW",
  13326. 188: "GET.DOCUMENT",
  13327. 189: "DPRODUCT",
  13328. 190: "ISNONTEXT",
  13329. 191: "GET.NOTE",
  13330. 192: "NOTE",
  13331. 193: "STDEVP",
  13332. 194: "VARP",
  13333. 195: "DSTDEVP",
  13334. 196: "DVARP",
  13335. 197: "TRUNC",
  13336. 198: "ISLOGICAL",
  13337. 199: "DCOUNTA",
  13338. 200: "DELETE.BAR",
  13339. 201: "UNREGISTER",
  13340. 204: "USDOLLAR",
  13341. 205: "FINDB",
  13342. 206: "SEARCHB",
  13343. 207: "REPLACEB",
  13344. 208: "LEFTB",
  13345. 209: "RIGHTB",
  13346. 210: "MIDB",
  13347. 211: "LENB",
  13348. 212: "ROUNDUP",
  13349. 213: "ROUNDDOWN",
  13350. 214: "ASC",
  13351. 215: "DBCS",
  13352. 216: "RANK",
  13353. 219: "ADDRESS",
  13354. 220: "DAYS360",
  13355. 221: "TODAY",
  13356. 222: "VDB",
  13357. 223: "ELSE",
  13358. 224: "ELSE.IF",
  13359. 225: "END.IF",
  13360. 226: "FOR.CELL",
  13361. 227: "MEDIAN",
  13362. 228: "SUMPRODUCT",
  13363. 229: "SINH",
  13364. 230: "COSH",
  13365. 231: "TANH",
  13366. 232: "ASINH",
  13367. 233: "ACOSH",
  13368. 234: "ATANH",
  13369. 235: "DGET",
  13370. 236: "CREATE.OBJECT",
  13371. 237: "VOLATILE",
  13372. 238: "LAST.ERROR",
  13373. 239: "CUSTOM.UNDO",
  13374. 240: "CUSTOM.REPEAT",
  13375. 241: "FORMULA.CONVERT",
  13376. 242: "GET.LINK.INFO",
  13377. 243: "TEXT.BOX",
  13378. 244: "INFO",
  13379. 245: "GROUP",
  13380. 246: "GET.OBJECT",
  13381. 247: "DB",
  13382. 248: "PAUSE",
  13383. 251: "RESUME",
  13384. 252: "FREQUENCY",
  13385. 253: "ADD.TOOLBAR",
  13386. 254: "DELETE.TOOLBAR",
  13387. 255: "User",
  13388. 256: "RESET.TOOLBAR",
  13389. 257: "EVALUATE",
  13390. 258: "GET.TOOLBAR",
  13391. 259: "GET.TOOL",
  13392. 260: "SPELLING.CHECK",
  13393. 261: "ERROR.TYPE",
  13394. 262: "APP.TITLE",
  13395. 263: "WINDOW.TITLE",
  13396. 264: "SAVE.TOOLBAR",
  13397. 265: "ENABLE.TOOL",
  13398. 266: "PRESS.TOOL",
  13399. 267: "REGISTER.ID",
  13400. 268: "GET.WORKBOOK",
  13401. 269: "AVEDEV",
  13402. 270: "BETADIST",
  13403. 271: "GAMMALN",
  13404. 272: "BETAINV",
  13405. 273: "BINOMDIST",
  13406. 274: "CHIDIST",
  13407. 275: "CHIINV",
  13408. 276: "COMBIN",
  13409. 277: "CONFIDENCE",
  13410. 278: "CRITBINOM",
  13411. 279: "EVEN",
  13412. 280: "EXPONDIST",
  13413. 281: "FDIST",
  13414. 282: "FINV",
  13415. 283: "FISHER",
  13416. 284: "FISHERINV",
  13417. 285: "FLOOR",
  13418. 286: "GAMMADIST",
  13419. 287: "GAMMAINV",
  13420. 288: "CEILING",
  13421. 289: "HYPGEOMDIST",
  13422. 290: "LOGNORMDIST",
  13423. 291: "LOGINV",
  13424. 292: "NEGBINOMDIST",
  13425. 293: "NORMDIST",
  13426. 294: "NORMSDIST",
  13427. 295: "NORMINV",
  13428. 296: "NORMSINV",
  13429. 297: "STANDARDIZE",
  13430. 298: "ODD",
  13431. 299: "PERMUT",
  13432. 300: "POISSON",
  13433. 301: "TDIST",
  13434. 302: "WEIBULL",
  13435. 303: "SUMXMY2",
  13436. 304: "SUMX2MY2",
  13437. 305: "SUMX2PY2",
  13438. 306: "CHITEST",
  13439. 307: "CORREL",
  13440. 308: "COVAR",
  13441. 309: "FORECAST",
  13442. 310: "FTEST",
  13443. 311: "INTERCEPT",
  13444. 312: "PEARSON",
  13445. 313: "RSQ",
  13446. 314: "STEYX",
  13447. 315: "SLOPE",
  13448. 316: "TTEST",
  13449. 317: "PROB",
  13450. 318: "DEVSQ",
  13451. 319: "GEOMEAN",
  13452. 320: "HARMEAN",
  13453. 321: "SUMSQ",
  13454. 322: "KURT",
  13455. 323: "SKEW",
  13456. 324: "ZTEST",
  13457. 325: "LARGE",
  13458. 326: "SMALL",
  13459. 327: "QUARTILE",
  13460. 328: "PERCENTILE",
  13461. 329: "PERCENTRANK",
  13462. 330: "MODE",
  13463. 331: "TRIMMEAN",
  13464. 332: "TINV",
  13465. 334: "MOVIE.COMMAND",
  13466. 335: "GET.MOVIE",
  13467. 336: "CONCATENATE",
  13468. 337: "POWER",
  13469. 338: "PIVOT.ADD.DATA",
  13470. 339: "GET.PIVOT.TABLE",
  13471. 340: "GET.PIVOT.FIELD",
  13472. 341: "GET.PIVOT.ITEM",
  13473. 342: "RADIANS",
  13474. 343: "DEGREES",
  13475. 344: "SUBTOTAL",
  13476. 345: "SUMIF",
  13477. 346: "COUNTIF",
  13478. 347: "COUNTBLANK",
  13479. 348: "SCENARIO.GET",
  13480. 349: "OPTIONS.LISTS.GET",
  13481. 350: "ISPMT",
  13482. 351: "DATEDIF",
  13483. 352: "DATESTRING",
  13484. 353: "NUMBERSTRING",
  13485. 354: "ROMAN",
  13486. 355: "OPEN.DIALOG",
  13487. 356: "SAVE.DIALOG",
  13488. 357: "VIEW.GET",
  13489. 358: "GETPIVOTDATA",
  13490. 359: "HYPERLINK",
  13491. 360: "PHONETIC",
  13492. 361: "AVERAGEA",
  13493. 362: "MAXA",
  13494. 363: "MINA",
  13495. 364: "STDEVPA",
  13496. 365: "VARPA",
  13497. 366: "STDEVA",
  13498. 367: "VARA",
  13499. 368: "BAHTTEXT",
  13500. 369: "THAIDAYOFWEEK",
  13501. 370: "THAIDIGIT",
  13502. 371: "THAIMONTHOFYEAR",
  13503. 372: "THAINUMSOUND",
  13504. 373: "THAINUMSTRING",
  13505. 374: "THAISTRINGLENGTH",
  13506. 375: "ISTHAIDIGIT",
  13507. 376: "ROUNDBAHTDOWN",
  13508. 377: "ROUNDBAHTUP",
  13509. 378: "THAIYEAR",
  13510. 379: "RTD",
  13511. 380: "CUBEVALUE",
  13512. 381: "CUBEMEMBER",
  13513. 382: "CUBEMEMBERPROPERTY",
  13514. 383: "CUBERANKEDMEMBER",
  13515. 384: "HEX2BIN",
  13516. 385: "HEX2DEC",
  13517. 386: "HEX2OCT",
  13518. 387: "DEC2BIN",
  13519. 388: "DEC2HEX",
  13520. 389: "DEC2OCT",
  13521. 390: "OCT2BIN",
  13522. 391: "OCT2HEX",
  13523. 392: "OCT2DEC",
  13524. 393: "BIN2DEC",
  13525. 394: "BIN2OCT",
  13526. 395: "BIN2HEX",
  13527. 396: "IMSUB",
  13528. 397: "IMDIV",
  13529. 398: "IMPOWER",
  13530. 399: "IMABS",
  13531. 400: "IMSQRT",
  13532. 401: "IMLN",
  13533. 402: "IMLOG2",
  13534. 403: "IMLOG10",
  13535. 404: "IMSIN",
  13536. 405: "IMCOS",
  13537. 406: "IMEXP",
  13538. 407: "IMARGUMENT",
  13539. 408: "IMCONJUGATE",
  13540. 409: "IMAGINARY",
  13541. 410: "IMREAL",
  13542. 411: "COMPLEX",
  13543. 412: "IMSUM",
  13544. 413: "IMPRODUCT",
  13545. 414: "SERIESSUM",
  13546. 415: "FACTDOUBLE",
  13547. 416: "SQRTPI",
  13548. 417: "QUOTIENT",
  13549. 418: "DELTA",
  13550. 419: "GESTEP",
  13551. 420: "ISEVEN",
  13552. 421: "ISODD",
  13553. 422: "MROUND",
  13554. 423: "ERF",
  13555. 424: "ERFC",
  13556. 425: "BESSELJ",
  13557. 426: "BESSELK",
  13558. 427: "BESSELY",
  13559. 428: "BESSELI",
  13560. 429: "XIRR",
  13561. 430: "XNPV",
  13562. 431: "PRICEMAT",
  13563. 432: "YIELDMAT",
  13564. 433: "INTRATE",
  13565. 434: "RECEIVED",
  13566. 435: "DISC",
  13567. 436: "PRICEDISC",
  13568. 437: "YIELDDISC",
  13569. 438: "TBILLEQ",
  13570. 439: "TBILLPRICE",
  13571. 440: "TBILLYIELD",
  13572. 441: "PRICE",
  13573. 442: "YIELD",
  13574. 443: "DOLLARDE",
  13575. 444: "DOLLARFR",
  13576. 445: "NOMINAL",
  13577. 446: "EFFECT",
  13578. 447: "CUMPRINC",
  13579. 448: "CUMIPMT",
  13580. 449: "EDATE",
  13581. 450: "EOMONTH",
  13582. 451: "YEARFRAC",
  13583. 452: "COUPDAYBS",
  13584. 453: "COUPDAYS",
  13585. 454: "COUPDAYSNC",
  13586. 455: "COUPNCD",
  13587. 456: "COUPNUM",
  13588. 457: "COUPPCD",
  13589. 458: "DURATION",
  13590. 459: "MDURATION",
  13591. 460: "ODDLPRICE",
  13592. 461: "ODDLYIELD",
  13593. 462: "ODDFPRICE",
  13594. 463: "ODDFYIELD",
  13595. 464: "RANDBETWEEN",
  13596. 465: "WEEKNUM",
  13597. 466: "AMORDEGRC",
  13598. 467: "AMORLINC",
  13599. 468: "CONVERT",
  13600. 724: "SHEETJS",
  13601. 469: "ACCRINT",
  13602. 470: "ACCRINTM",
  13603. 471: "WORKDAY",
  13604. 472: "NETWORKDAYS",
  13605. 473: "GCD",
  13606. 474: "MULTINOMIAL",
  13607. 475: "LCM",
  13608. 476: "FVSCHEDULE",
  13609. 477: "CUBEKPIMEMBER",
  13610. 478: "CUBESET",
  13611. 479: "CUBESETCOUNT",
  13612. 480: "IFERROR",
  13613. 481: "COUNTIFS",
  13614. 482: "SUMIFS",
  13615. 483: "AVERAGEIF",
  13616. 484: "AVERAGEIFS"
  13617. };
  13618. var FtabArgc = {
  13619. 2: 1,
  13620. 3: 1,
  13621. 10: 0,
  13622. 15: 1,
  13623. 16: 1,
  13624. 17: 1,
  13625. 18: 1,
  13626. 19: 0,
  13627. 20: 1,
  13628. 21: 1,
  13629. 22: 1,
  13630. 23: 1,
  13631. 24: 1,
  13632. 25: 1,
  13633. 26: 1,
  13634. 27: 2,
  13635. 30: 2,
  13636. 31: 3,
  13637. 32: 1,
  13638. 33: 1,
  13639. 34: 0,
  13640. 35: 0,
  13641. 38: 1,
  13642. 39: 2,
  13643. 40: 3,
  13644. 41: 3,
  13645. 42: 3,
  13646. 43: 3,
  13647. 44: 3,
  13648. 45: 3,
  13649. 47: 3,
  13650. 48: 2,
  13651. 53: 1,
  13652. 61: 3,
  13653. 63: 0,
  13654. 65: 3,
  13655. 66: 3,
  13656. 67: 1,
  13657. 68: 1,
  13658. 69: 1,
  13659. 70: 1,
  13660. 71: 1,
  13661. 72: 1,
  13662. 73: 1,
  13663. 74: 0,
  13664. 75: 1,
  13665. 76: 1,
  13666. 77: 1,
  13667. 79: 2,
  13668. 80: 2,
  13669. 83: 1,
  13670. 85: 0,
  13671. 86: 1,
  13672. 89: 0,
  13673. 90: 1,
  13674. 94: 0,
  13675. 95: 0,
  13676. 97: 2,
  13677. 98: 1,
  13678. 99: 1,
  13679. 101: 3,
  13680. 102: 3,
  13681. 105: 1,
  13682. 106: 1,
  13683. 108: 2,
  13684. 111: 1,
  13685. 112: 1,
  13686. 113: 1,
  13687. 114: 1,
  13688. 117: 2,
  13689. 118: 1,
  13690. 119: 4,
  13691. 121: 1,
  13692. 126: 1,
  13693. 127: 1,
  13694. 128: 1,
  13695. 129: 1,
  13696. 130: 1,
  13697. 131: 1,
  13698. 133: 1,
  13699. 134: 1,
  13700. 135: 1,
  13701. 136: 2,
  13702. 137: 2,
  13703. 138: 2,
  13704. 140: 1,
  13705. 141: 1,
  13706. 142: 3,
  13707. 143: 4,
  13708. 144: 4,
  13709. 161: 1,
  13710. 162: 1,
  13711. 163: 1,
  13712. 164: 1,
  13713. 165: 2,
  13714. 172: 1,
  13715. 175: 2,
  13716. 176: 2,
  13717. 177: 3,
  13718. 178: 2,
  13719. 179: 1,
  13720. 184: 1,
  13721. 186: 1,
  13722. 189: 3,
  13723. 190: 1,
  13724. 195: 3,
  13725. 196: 3,
  13726. 197: 1,
  13727. 198: 1,
  13728. 199: 3,
  13729. 201: 1,
  13730. 207: 4,
  13731. 210: 3,
  13732. 211: 1,
  13733. 212: 2,
  13734. 213: 2,
  13735. 214: 1,
  13736. 215: 1,
  13737. 225: 0,
  13738. 229: 1,
  13739. 230: 1,
  13740. 231: 1,
  13741. 232: 1,
  13742. 233: 1,
  13743. 234: 1,
  13744. 235: 3,
  13745. 244: 1,
  13746. 247: 4,
  13747. 252: 2,
  13748. 257: 1,
  13749. 261: 1,
  13750. 271: 1,
  13751. 273: 4,
  13752. 274: 2,
  13753. 275: 2,
  13754. 276: 2,
  13755. 277: 3,
  13756. 278: 3,
  13757. 279: 1,
  13758. 280: 3,
  13759. 281: 3,
  13760. 282: 3,
  13761. 283: 1,
  13762. 284: 1,
  13763. 285: 2,
  13764. 286: 4,
  13765. 287: 3,
  13766. 288: 2,
  13767. 289: 4,
  13768. 290: 3,
  13769. 291: 3,
  13770. 292: 3,
  13771. 293: 4,
  13772. 294: 1,
  13773. 295: 3,
  13774. 296: 1,
  13775. 297: 3,
  13776. 298: 1,
  13777. 299: 2,
  13778. 300: 3,
  13779. 301: 3,
  13780. 302: 4,
  13781. 303: 2,
  13782. 304: 2,
  13783. 305: 2,
  13784. 306: 2,
  13785. 307: 2,
  13786. 308: 2,
  13787. 309: 3,
  13788. 310: 2,
  13789. 311: 2,
  13790. 312: 2,
  13791. 313: 2,
  13792. 314: 2,
  13793. 315: 2,
  13794. 316: 4,
  13795. 325: 2,
  13796. 326: 2,
  13797. 327: 2,
  13798. 328: 2,
  13799. 331: 2,
  13800. 332: 2,
  13801. 337: 2,
  13802. 342: 1,
  13803. 343: 1,
  13804. 346: 2,
  13805. 347: 1,
  13806. 350: 4,
  13807. 351: 3,
  13808. 352: 1,
  13809. 353: 2,
  13810. 360: 1,
  13811. 368: 1,
  13812. 369: 1,
  13813. 370: 1,
  13814. 371: 1,
  13815. 372: 1,
  13816. 373: 1,
  13817. 374: 1,
  13818. 375: 1,
  13819. 376: 1,
  13820. 377: 1,
  13821. 378: 1,
  13822. 382: 3,
  13823. 385: 1,
  13824. 392: 1,
  13825. 393: 1,
  13826. 396: 2,
  13827. 397: 2,
  13828. 398: 2,
  13829. 399: 1,
  13830. 400: 1,
  13831. 401: 1,
  13832. 402: 1,
  13833. 403: 1,
  13834. 404: 1,
  13835. 405: 1,
  13836. 406: 1,
  13837. 407: 1,
  13838. 408: 1,
  13839. 409: 1,
  13840. 410: 1,
  13841. 414: 4,
  13842. 415: 1,
  13843. 416: 1,
  13844. 417: 2,
  13845. 420: 1,
  13846. 421: 1,
  13847. 422: 2,
  13848. 424: 1,
  13849. 425: 2,
  13850. 426: 2,
  13851. 427: 2,
  13852. 428: 2,
  13853. 430: 3,
  13854. 438: 3,
  13855. 439: 3,
  13856. 440: 3,
  13857. 443: 2,
  13858. 444: 2,
  13859. 445: 2,
  13860. 446: 2,
  13861. 447: 6,
  13862. 448: 6,
  13863. 449: 2,
  13864. 450: 2,
  13865. 464: 2,
  13866. 468: 3,
  13867. 476: 2,
  13868. 479: 1,
  13869. 480: 2,
  13870. 65535: 0
  13871. };
  13872. /* Part 3 TODO: actually parse formulae */
  13873. function ods_to_csf_formula(f) {
  13874. if(f.slice(0,3) == "of:") f = f.slice(3);
  13875. /* 5.2 Basic Expressions */
  13876. if(f.charCodeAt(0) == 61) {
  13877. f = f.slice(1);
  13878. if(f.charCodeAt(0) == 61) f = f.slice(1);
  13879. }
  13880. f = f.replace(/COM\.MICROSOFT\./g, "");
  13881. /* Part 3 Section 5.8 References */
  13882. f = f.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) { return $1.replace(/\./g,""); });
  13883. f = f.replace(/\$'([^']|'')+'/g, function($$) { return $$.slice(1); });
  13884. f = f.replace(/\$([^\]\. #$]+)/g, function($$, $1) { return ($1).match(/^([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})?$/) ? $$ : $1; });
  13885. /* TODO: something other than this */
  13886. f = f.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
  13887. return f.replace(/[;~]/g,",").replace(/\|/g,";");
  13888. }
  13889. function csf_to_ods_formula(f) {
  13890. var o = "of:=" + f.replace(crefregex, "$1[.$2$3$4$5]").replace(/\]:\[/g,":");
  13891. /* TODO: something other than this */
  13892. return o.replace(/;/g, "|").replace(/,/g,";");
  13893. }
  13894. function ods_to_csf_3D(r) {
  13895. r = r.replace(/\$'([^']|'')+'/g, function($$) { return $$.slice(1); });
  13896. r = r.replace(/\$([^\]\. #$]+)/g, function($$, $1) { return ($1).match(/^([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})?$/) ? $$ : $1; });
  13897. var a = r.split(":");
  13898. var s = a[0].split(".")[0];
  13899. return [s, a[0].split(".")[1] + (a.length > 1 ? (":" + (a[1].split(".")[1] || a[1].split(".")[0])) : "")];
  13900. }
  13901. function csf_to_ods_3D(r) {
  13902. return r.replace(/!/,".");
  13903. }
  13904. var strs = {}; // shared strings
  13905. var _ssfopts = {}; // spreadsheet formatting options
  13906. /*global Map */
  13907. var browser_has_Map = typeof Map !== 'undefined';
  13908. function get_sst_id(sst, str, rev) {
  13909. var i = 0, len = sst.length;
  13910. if(rev) {
  13911. if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
  13912. var revarr = browser_has_Map ? rev.get(str) : rev[str];
  13913. for(; i < revarr.length; ++i) {
  13914. if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
  13915. }
  13916. }
  13917. } else for(; i < len; ++i) {
  13918. if(sst[i].t === str) { sst.Count ++; return i; }
  13919. }
  13920. sst[len] = ({t:str}); sst.Count ++; sst.Unique ++;
  13921. if(rev) {
  13922. if(browser_has_Map) {
  13923. if(!rev.has(str)) rev.set(str, []);
  13924. rev.get(str).push(len);
  13925. } else {
  13926. if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
  13927. rev[str].push(len);
  13928. }
  13929. }
  13930. return len;
  13931. }
  13932. function col_obj_w(C, col) {
  13933. var p = ({min:C+1,max:C+1});
  13934. /* wch (chars), wpx (pixels) */
  13935. var wch = -1;
  13936. if(col.MDW) MDW = col.MDW;
  13937. if(col.width != null) p.customWidth = 1;
  13938. else if(col.wpx != null) wch = px2char(col.wpx);
  13939. else if(col.wch != null) wch = col.wch;
  13940. if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
  13941. else if(col.width != null) p.width = col.width;
  13942. if(col.hidden) p.hidden = true;
  13943. if(col.level != null) { p.outlineLevel = p.level = col.level; }
  13944. return p;
  13945. }
  13946. function default_margins(margins, mode) {
  13947. if(!margins) return;
  13948. var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  13949. if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
  13950. if(margins.left == null) margins.left = defs[0];
  13951. if(margins.right == null) margins.right = defs[1];
  13952. if(margins.top == null) margins.top = defs[2];
  13953. if(margins.bottom == null) margins.bottom = defs[3];
  13954. if(margins.header == null) margins.header = defs[4];
  13955. if(margins.footer == null) margins.footer = defs[5];
  13956. }
  13957. function get_cell_style(styles, cell, opts) {
  13958. var z = opts.revssf[cell.z != null ? cell.z : "General"];
  13959. var i = 0x3c, len = styles.length;
  13960. if(z == null && opts.ssf) {
  13961. for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
  13962. SSF__load(cell.z, i);
  13963. // $FlowIgnore
  13964. opts.ssf[i] = cell.z;
  13965. opts.revssf[cell.z] = z = i;
  13966. break;
  13967. }
  13968. }
  13969. for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
  13970. styles[len] = {
  13971. numFmtId:z,
  13972. fontId:0,
  13973. fillId:0,
  13974. borderId:0,
  13975. xfId:0,
  13976. applyNumberFormat:1
  13977. };
  13978. return len;
  13979. }
  13980. function safe_format(p, fmtid, fillid, opts, themes, styles) {
  13981. try {
  13982. if(opts.cellNF) p.z = table_fmt[fmtid];
  13983. } catch(e) { if(opts.WTF) throw e; }
  13984. if(p.t === 'z' && !opts.cellStyles) return;
  13985. if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
  13986. if((!opts || opts.cellText !== false) && p.t !== 'z') try {
  13987. if(table_fmt[fmtid] == null) SSF__load(SSFImplicit[fmtid] || "General", fmtid);
  13988. if(p.t === 'e') p.w = p.w || BErr[p.v];
  13989. else if(fmtid === 0) {
  13990. if(p.t === 'n') {
  13991. if((p.v|0) === p.v) p.w = p.v.toString(10);
  13992. else p.w = SSF_general_num(p.v);
  13993. }
  13994. else if(p.t === 'd') {
  13995. var dd = datenum(p.v);
  13996. if((dd|0) === dd) p.w = dd.toString(10);
  13997. else p.w = SSF_general_num(dd);
  13998. }
  13999. else if(p.v === undefined) return "";
  14000. else p.w = SSF_general(p.v,_ssfopts);
  14001. }
  14002. else if(p.t === 'd') p.w = SSF_format(fmtid,datenum(p.v),_ssfopts);
  14003. else p.w = SSF_format(fmtid,p.v,_ssfopts);
  14004. } catch(e) { if(opts.WTF) throw e; }
  14005. if(!opts.cellStyles) return;
  14006. if(fillid != null) try {
  14007. p.s = styles.Fills[fillid];
  14008. if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
  14009. p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
  14010. if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
  14011. }
  14012. if (p.s.bgColor && p.s.bgColor.theme) {
  14013. p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
  14014. if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
  14015. }
  14016. } catch(e) { if(opts.WTF && styles.Fills) throw e; }
  14017. }
  14018. function check_ws(ws, sname, i) {
  14019. if(ws && ws['!ref']) {
  14020. var range = safe_decode_range(ws['!ref']);
  14021. if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
  14022. }
  14023. }
  14024. function parse_ws_xml_dim(ws, s) {
  14025. var d = safe_decode_range(s);
  14026. 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);
  14027. }
  14028. var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
  14029. var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
  14030. var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
  14031. var dimregex = /"(\w*:\w*)"/;
  14032. var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
  14033. var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
  14034. var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
  14035. var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
  14036. var sheetprregex2= /<(?:\w:)?sheetPr[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetPr)>/;
  14037. var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
  14038. /* 18.3 Worksheets */
  14039. function parse_ws_xml(data, opts, idx, rels, wb, themes, styles) {
  14040. if(!data) return data;
  14041. if(!rels) rels = {'!id':{}};
  14042. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  14043. /* 18.3.1.99 worksheet CT_Worksheet */
  14044. var s = opts.dense ? ([]) : ({});
  14045. var refguess = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} });
  14046. var data1 = "", data2 = "";
  14047. var mtch = data.match(sheetdataregex);
  14048. if(mtch) {
  14049. data1 = data.slice(0, mtch.index);
  14050. data2 = data.slice(mtch.index + mtch[0].length);
  14051. } else data1 = data2 = data;
  14052. /* 18.3.1.82 sheetPr CT_SheetPr */
  14053. var sheetPr = data1.match(sheetprregex);
  14054. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  14055. else if((sheetPr = data1.match(sheetprregex2))) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1]||"", s, wb, idx, styles, themes);
  14056. /* 18.3.1.35 dimension CT_SheetDimension */
  14057. var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
  14058. if(ridx > 0) {
  14059. var ref = data1.slice(ridx,ridx+50).match(dimregex);
  14060. if(ref) parse_ws_xml_dim(s, ref[1]);
  14061. }
  14062. /* 18.3.1.88 sheetViews CT_SheetViews */
  14063. var svs = data1.match(svsregex);
  14064. if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  14065. /* 18.3.1.17 cols CT_Cols */
  14066. var columns = [];
  14067. if(opts.cellStyles) {
  14068. /* 18.3.1.13 col CT_Col */
  14069. var cols = data1.match(colregex);
  14070. if(cols) parse_ws_xml_cols(columns, cols);
  14071. }
  14072. /* 18.3.1.80 sheetData CT_SheetData ? */
  14073. if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
  14074. /* 18.3.1.2 autoFilter CT_AutoFilter */
  14075. var afilter = data2.match(afregex);
  14076. if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);
  14077. /* 18.3.1.55 mergeCells CT_MergeCells */
  14078. var merges = [];
  14079. var _merge = data2.match(mergecregex);
  14080. if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
  14081. merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
  14082. /* 18.3.1.48 hyperlinks CT_Hyperlinks */
  14083. var hlink = data2.match(hlinkregex);
  14084. if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
  14085. /* 18.3.1.62 pageMargins CT_PageMargins */
  14086. var margins = data2.match(marginregex);
  14087. if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));
  14088. if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
  14089. if(opts.sheetRows > 0 && s["!ref"]) {
  14090. var tmpref = safe_decode_range(s["!ref"]);
  14091. if(opts.sheetRows <= +tmpref.e.r) {
  14092. tmpref.e.r = opts.sheetRows - 1;
  14093. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  14094. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  14095. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  14096. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  14097. s["!fullref"] = s["!ref"];
  14098. s["!ref"] = encode_range(tmpref);
  14099. }
  14100. }
  14101. if(columns.length > 0) s["!cols"] = columns;
  14102. if(merges.length > 0) s["!merges"] = merges;
  14103. return s;
  14104. }
  14105. function write_ws_xml_merges(merges) {
  14106. if(merges.length === 0) return "";
  14107. var o = '<mergeCells count="' + merges.length + '">';
  14108. for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
  14109. return o + '</mergeCells>';
  14110. }
  14111. /* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
  14112. function parse_ws_xml_sheetpr(sheetPr, s, wb, idx) {
  14113. var data = parsexmltag(sheetPr);
  14114. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  14115. if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
  14116. }
  14117. function parse_ws_xml_sheetpr2(sheetPr, body, s, wb, idx) {
  14118. parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s, wb, idx);
  14119. }
  14120. function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
  14121. var needed = false;
  14122. var props = {}, payload = null;
  14123. if(opts.bookType !== 'xlsx' && wb.vbaraw) {
  14124. var cname = wb.SheetNames[idx];
  14125. try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
  14126. needed = true;
  14127. props.codeName = utf8write(escapexml(cname));
  14128. }
  14129. if(ws && ws["!outline"]) {
  14130. var outlineprops = {summaryBelow:1, summaryRight:1};
  14131. if(ws["!outline"].above) outlineprops.summaryBelow = 0;
  14132. if(ws["!outline"].left) outlineprops.summaryRight = 0;
  14133. payload = (payload||"") + writextag('outlinePr', null, outlineprops);
  14134. }
  14135. if(!needed && !payload) return;
  14136. o[o.length] = (writextag('sheetPr', payload, props));
  14137. }
  14138. /* 18.3.1.85 sheetProtection CT_SheetProtection */
  14139. var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
  14140. var sheetprot_deftrue = [
  14141. "formatColumns", "formatRows", "formatCells",
  14142. "insertColumns", "insertRows", "insertHyperlinks",
  14143. "deleteColumns", "deleteRows",
  14144. "sort", "autoFilter", "pivotTables"
  14145. ];
  14146. function write_ws_xml_protection(sp) {
  14147. // algorithmName, hashValue, saltValue, spinCount
  14148. var o = ({sheet:1});
  14149. sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
  14150. sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
  14151. /* TODO: algorithm */
  14152. if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
  14153. return writextag('sheetProtection', null, o);
  14154. }
  14155. function parse_ws_xml_hlinks(s, data, rels) {
  14156. var dense = Array.isArray(s);
  14157. for(var i = 0; i != data.length; ++i) {
  14158. var val = parsexmltag(utf8read(data[i]), true);
  14159. if(!val.ref) return;
  14160. var rel = ((rels || {})['!id']||[])[val.id];
  14161. if(rel) {
  14162. val.Target = rel.Target;
  14163. if(val.location) val.Target += "#"+unescapexml(val.location);
  14164. } else {
  14165. val.Target = "#" + unescapexml(val.location);
  14166. rel = {Target: val.Target, TargetMode: 'Internal'};
  14167. }
  14168. val.Rel = rel;
  14169. if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
  14170. var rng = safe_decode_range(val.ref);
  14171. for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
  14172. var addr = encode_cell({c:C,r:R});
  14173. if(dense) {
  14174. if(!s[R]) s[R] = [];
  14175. if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
  14176. s[R][C].l = val;
  14177. } else {
  14178. if(!s[addr]) s[addr] = {t:"z",v:undefined};
  14179. s[addr].l = val;
  14180. }
  14181. }
  14182. }
  14183. }
  14184. function parse_ws_xml_margins(margin) {
  14185. var o = {};
  14186. ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
  14187. if(margin[k]) o[k] = parseFloat(margin[k]);
  14188. });
  14189. return o;
  14190. }
  14191. function write_ws_xml_margins(margin) {
  14192. default_margins(margin);
  14193. return writextag('pageMargins', null, margin);
  14194. }
  14195. function parse_ws_xml_cols(columns, cols) {
  14196. var seencol = false;
  14197. for(var coli = 0; coli != cols.length; ++coli) {
  14198. var coll = parsexmltag(cols[coli], true);
  14199. if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
  14200. var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
  14201. if(coll.outlineLevel) coll.level = (+coll.outlineLevel || 0);
  14202. delete coll.min; delete coll.max; coll.width = +coll.width;
  14203. if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
  14204. process_col(coll);
  14205. while(colm <= colM) columns[colm++] = dup(coll);
  14206. }
  14207. }
  14208. function write_ws_xml_cols(ws, cols) {
  14209. var o = ["<cols>"], col;
  14210. for(var i = 0; i != cols.length; ++i) {
  14211. if(!(col = cols[i])) continue;
  14212. o[o.length] = (writextag('col', null, col_obj_w(i, col)));
  14213. }
  14214. o[o.length] = "</cols>";
  14215. return o.join("");
  14216. }
  14217. function parse_ws_xml_autofilter(data) {
  14218. var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
  14219. return o;
  14220. }
  14221. function write_ws_xml_autofilter(data, ws, wb, idx) {
  14222. var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
  14223. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  14224. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  14225. var names = wb.Workbook.Names;
  14226. var range = decode_range(ref);
  14227. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  14228. for(var i = 0; i < names.length; ++i) {
  14229. var name = names[i];
  14230. if(name.Name != '_xlnm._FilterDatabase') continue;
  14231. if(name.Sheet != idx) continue;
  14232. name.Ref = formula_quote_sheet_name(wb.SheetNames[idx]) + "!" + fix_range(ref); break;
  14233. }
  14234. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  14235. return writextag("autoFilter", null, {ref:ref});
  14236. }
  14237. /* 18.3.1.88 sheetViews CT_SheetViews */
  14238. /* 18.3.1.87 sheetView CT_SheetView */
  14239. var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/g;
  14240. function parse_ws_xml_sheetviews(data, wb) {
  14241. if(!wb.Views) wb.Views = [{}];
  14242. (data.match(sviewregex)||[]).forEach(function(r, i) {
  14243. var tag = parsexmltag(r);
  14244. // $FlowIgnore
  14245. if(!wb.Views[i]) wb.Views[i] = {};
  14246. // $FlowIgnore
  14247. if(+tag.zoomScale) wb.Views[i].zoom = +tag.zoomScale;
  14248. // $FlowIgnore
  14249. if(tag.rightToLeft && parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
  14250. });
  14251. }
  14252. function write_ws_xml_sheetviews(ws, opts, idx, wb) {
  14253. var sview = ({workbookViewId:"0"});
  14254. // $FlowIgnore
  14255. if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
  14256. return writextag("sheetViews", writextag("sheetView", null, sview), {});
  14257. }
  14258. function write_ws_xml_cell(cell, ref, ws, opts) {
  14259. if(cell.c) ws['!comments'].push([ref, cell.c]);
  14260. if((cell.v === undefined || cell.t === "z" && !(opts||{}).sheetStubs) && typeof cell.f !== "string" && typeof cell.z == "undefined") return "";
  14261. var vv = "";
  14262. var oldt = cell.t, oldv = cell.v;
  14263. if(cell.t !== "z") switch(cell.t) {
  14264. case 'b': vv = cell.v ? "1" : "0"; break;
  14265. case 'n': vv = ''+cell.v; break;
  14266. case 'e': vv = BErr[cell.v]; break;
  14267. case 'd':
  14268. if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
  14269. else {
  14270. cell = dup(cell);
  14271. cell.t = 'n';
  14272. vv = ''+(cell.v = datenum(parseDate(cell.v)));
  14273. }
  14274. if(typeof cell.z === 'undefined') cell.z = table_fmt[14];
  14275. break;
  14276. default: vv = cell.v; break;
  14277. }
  14278. var v = (cell.t == "z" || cell.v == null)? "" : writetag('v', escapexml(vv)), o = ({r:ref});
  14279. /* TODO: cell style */
  14280. var os = get_cell_style(opts.cellXfs, cell, opts);
  14281. if(os !== 0) o.s = os;
  14282. switch(cell.t) {
  14283. case 'n': break;
  14284. case 'd': o.t = "d"; break;
  14285. case 'b': o.t = "b"; break;
  14286. case 'e': o.t = "e"; break;
  14287. case 'z': break;
  14288. default: if(cell.v == null) { delete cell.t; break; }
  14289. if(cell.v.length > 32767) throw new Error("Text length must not exceed 32767 characters");
  14290. if(opts && opts.bookSST) {
  14291. v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
  14292. o.t = "s"; break;
  14293. }
  14294. else o.t = "str"; break;
  14295. }
  14296. if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
  14297. if(typeof cell.f == "string" && cell.f) {
  14298. var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
  14299. v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
  14300. }
  14301. if(cell.l) {
  14302. cell.l.display = escapexml(vv);
  14303. ws['!links'].push([ref, cell.l]);
  14304. }
  14305. if(cell.D) o.cm = 1;
  14306. return writextag('c', v, o);
  14307. }
  14308. var parse_ws_xml_data = (function() {
  14309. var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  14310. var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
  14311. var refregex = /ref=["']([^"']*)["']/;
  14312. var match_v = matchtag("v"), match_f = matchtag("f");
  14313. return function parse_ws_xml_data(sdata, s, opts, guess, themes, styles) {
  14314. var ri = 0, x = "", cells = [], cref = [], idx=0, i=0, cc=0, d="", p;
  14315. var tag, tagr = 0, tagc = 0;
  14316. var sstr, ftag;
  14317. var fmtid = 0, fillid = 0;
  14318. var do_format = Array.isArray(styles.CellXf), cf;
  14319. var arrayf = [];
  14320. var sharedf = [];
  14321. var dense = Array.isArray(s);
  14322. var rows = [], rowobj = {}, rowrite = false;
  14323. var sheetStubs = !!opts.sheetStubs;
  14324. for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
  14325. x = marr[mt].trim();
  14326. var xlen = x.length;
  14327. if(xlen === 0) continue;
  14328. /* 18.3.1.73 row CT_Row */
  14329. var rstarti = 0;
  14330. outa: for(ri = 0; ri < xlen; ++ri) switch(/*x.charCodeAt(ri)*/x[ri]) {
  14331. case ">" /*62*/:
  14332. if(/*x.charCodeAt(ri-1) != 47*/x[ri-1] != "/") { ++ri; break outa; }
  14333. if(opts && opts.cellStyles) {
  14334. // TODO: avoid duplication
  14335. tag = parsexmltag(x.slice(rstarti,ri), true);
  14336. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  14337. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  14338. rowobj = {}; rowrite = false;
  14339. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  14340. if(tag.hidden && parsexmlbool(tag.hidden)) { rowrite = true; rowobj.hidden = true; }
  14341. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  14342. if(rowrite) rows[tagr-1] = rowobj;
  14343. }
  14344. break;
  14345. case "<" /*60*/: rstarti = ri; break;
  14346. }
  14347. if(rstarti >= ri) break;
  14348. tag = parsexmltag(x.slice(rstarti,ri), true);
  14349. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  14350. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  14351. if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
  14352. if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
  14353. if(opts && opts.cellStyles) {
  14354. rowobj = {}; rowrite = false;
  14355. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  14356. if(tag.hidden && parsexmlbool(tag.hidden)) { rowrite = true; rowobj.hidden = true; }
  14357. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  14358. if(rowrite) rows[tagr-1] = rowobj;
  14359. }
  14360. /* 18.3.1.4 c CT_Cell */
  14361. cells = x.slice(ri).split(cellregex);
  14362. for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
  14363. cells = cells.slice(rslice);
  14364. for(ri = 0; ri != cells.length; ++ri) {
  14365. x = cells[ri].trim();
  14366. if(x.length === 0) continue;
  14367. cref = x.match(rregex); idx = ri; i=0; cc=0;
  14368. x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
  14369. if(cref != null && cref.length === 2) {
  14370. idx = 0; d=cref[1];
  14371. for(i=0; i != d.length; ++i) {
  14372. if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
  14373. idx = 26*idx + cc;
  14374. }
  14375. --idx;
  14376. tagc = idx;
  14377. } else ++tagc;
  14378. for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
  14379. tag = parsexmltag(x.slice(0,i), true);
  14380. if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
  14381. d = x.slice(i);
  14382. p = ({t:""});
  14383. if((cref=d.match(match_v))!= null && cref[1] !== '') p.v=unescapexml(cref[1]);
  14384. if(opts.cellFormula) {
  14385. if((cref=d.match(match_f))!= null && cref[1] !== '') {
  14386. /* TODO: match against XLSXFutureFunctions */
  14387. p.f=unescapexml(utf8read(cref[1]), true);
  14388. if(!opts.xlfn) p.f = _xlfn(p.f);
  14389. if(cref[0].indexOf('t="array"') > -1) {
  14390. p.F = (d.match(refregex)||[])[1];
  14391. if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
  14392. } else if(cref[0].indexOf('t="shared"') > -1) {
  14393. // TODO: parse formula
  14394. ftag = parsexmltag(cref[0]);
  14395. var ___f = unescapexml(utf8read(cref[1]));
  14396. if(!opts.xlfn) ___f = _xlfn(___f);
  14397. sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
  14398. }
  14399. } else if((cref=d.match(/<f[^>]*\/>/))) {
  14400. ftag = parsexmltag(cref[0]);
  14401. if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
  14402. }
  14403. /* TODO: factor out contains logic */
  14404. var _tag = decode_cell(tag.r);
  14405. for(i = 0; i < arrayf.length; ++i)
  14406. if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
  14407. if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
  14408. p.F = arrayf[i][1];
  14409. }
  14410. if(tag.t == null && p.v === undefined) {
  14411. if(p.f || p.F) {
  14412. p.v = 0; p.t = "n";
  14413. } else if(!sheetStubs) continue;
  14414. else p.t = "z";
  14415. }
  14416. else p.t = tag.t || "n";
  14417. if(guess.s.c > tagc) guess.s.c = tagc;
  14418. if(guess.e.c < tagc) guess.e.c = tagc;
  14419. /* 18.18.11 t ST_CellType */
  14420. switch(p.t) {
  14421. case 'n':
  14422. if(p.v == "" || p.v == null) {
  14423. if(!sheetStubs) continue;
  14424. p.t = 'z';
  14425. } else p.v = parseFloat(p.v);
  14426. break;
  14427. case 's':
  14428. if(typeof p.v == 'undefined') {
  14429. if(!sheetStubs) continue;
  14430. p.t = 'z';
  14431. } else {
  14432. sstr = strs[parseInt(p.v, 10)];
  14433. p.v = sstr.t;
  14434. p.r = sstr.r;
  14435. if(opts.cellHTML) p.h = sstr.h;
  14436. }
  14437. break;
  14438. case 'str':
  14439. p.t = "s";
  14440. p.v = (p.v!=null) ? unescapexml(utf8read(p.v), true) : '';
  14441. if(opts.cellHTML) p.h = escapehtml(p.v);
  14442. break;
  14443. case 'inlineStr':
  14444. cref = d.match(isregex);
  14445. p.t = 's';
  14446. if(cref != null && (sstr = parse_si(cref[1]))) {
  14447. p.v = sstr.t;
  14448. if(opts.cellHTML) p.h = sstr.h;
  14449. } else p.v = "";
  14450. break;
  14451. case 'b': p.v = parsexmlbool(p.v); break;
  14452. case 'd':
  14453. if(opts.cellDates) p.v = parseDate(p.v, 1);
  14454. else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
  14455. break;
  14456. /* error string in .w, number in .v */
  14457. case 'e':
  14458. if(!opts || opts.cellText !== false) p.w = p.v;
  14459. p.v = RBErr[p.v]; break;
  14460. }
  14461. /* formatting */
  14462. fmtid = fillid = 0;
  14463. cf = null;
  14464. if(do_format && tag.s !== undefined) {
  14465. cf = styles.CellXf[tag.s];
  14466. if(cf != null) {
  14467. if(cf.numFmtId != null) fmtid = cf.numFmtId;
  14468. if(opts.cellStyles) {
  14469. if(cf.fillId != null) fillid = cf.fillId;
  14470. }
  14471. }
  14472. }
  14473. safe_format(p, fmtid, fillid, opts, themes, styles);
  14474. if(opts.cellDates && do_format && p.t == 'n' && fmt_is_date(table_fmt[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
  14475. if(tag.cm && opts.xlmeta) {
  14476. var cm = (opts.xlmeta.Cell||[])[+tag.cm-1];
  14477. if(cm && cm.type == 'XLDAPR') p.D = true;
  14478. }
  14479. if(dense) {
  14480. var _r = decode_cell(tag.r);
  14481. if(!s[_r.r]) s[_r.r] = [];
  14482. s[_r.r][_r.c] = p;
  14483. } else s[tag.r] = p;
  14484. }
  14485. }
  14486. if(rows.length > 0) s['!rows'] = rows;
  14487. }; })();
  14488. function write_ws_xml_data(ws, opts, idx, wb) {
  14489. var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
  14490. var dense = Array.isArray(ws);
  14491. var params = ({r:rr}), row, height = -1;
  14492. for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
  14493. for(R = range.s.r; R <= range.e.r; ++R) {
  14494. r = [];
  14495. rr = encode_row(R);
  14496. for(C = range.s.c; C <= range.e.c; ++C) {
  14497. ref = cols[C] + rr;
  14498. var _cell = dense ? (ws[R]||[])[C]: ws[ref];
  14499. if(_cell === undefined) continue;
  14500. if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
  14501. }
  14502. if(r.length > 0 || (rows && rows[R])) {
  14503. params = ({r:rr});
  14504. if(rows && rows[R]) {
  14505. row = rows[R];
  14506. if(row.hidden) params.hidden = 1;
  14507. height = -1;
  14508. if(row.hpx) height = px2pt(row.hpx);
  14509. else if(row.hpt) height = row.hpt;
  14510. if(height > -1) { params.ht = height; params.customHeight = 1; }
  14511. if(row.level) { params.outlineLevel = row.level; }
  14512. }
  14513. o[o.length] = (writextag('row', r.join(""), params));
  14514. }
  14515. }
  14516. if(rows) for(; R < rows.length; ++R) {
  14517. if(rows && rows[R]) {
  14518. params = ({r:R+1});
  14519. row = rows[R];
  14520. if(row.hidden) params.hidden = 1;
  14521. height = -1;
  14522. if (row.hpx) height = px2pt(row.hpx);
  14523. else if (row.hpt) height = row.hpt;
  14524. if (height > -1) { params.ht = height; params.customHeight = 1; }
  14525. if (row.level) { params.outlineLevel = row.level; }
  14526. o[o.length] = (writextag('row', "", params));
  14527. }
  14528. }
  14529. return o.join("");
  14530. }
  14531. function write_ws_xml(idx, opts, wb, rels) {
  14532. var o = [XML_HEADER, writextag('worksheet', null, {
  14533. 'xmlns': XMLNS_main[0],
  14534. 'xmlns:r': XMLNS.r
  14535. })];
  14536. var s = wb.SheetNames[idx], sidx = 0, rdata = "";
  14537. var ws = wb.Sheets[s];
  14538. if(ws == null) ws = {};
  14539. var ref = ws['!ref'] || 'A1';
  14540. var range = safe_decode_range(ref);
  14541. if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
  14542. if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
  14543. range.e.c = Math.min(range.e.c, 0x3FFF);
  14544. range.e.r = Math.min(range.e.c, 0xFFFFF);
  14545. ref = encode_range(range);
  14546. }
  14547. if(!rels) rels = {};
  14548. ws['!comments'] = [];
  14549. var _drawing = [];
  14550. write_ws_xml_sheetpr(ws, wb, idx, opts, o);
  14551. o[o.length] = (writextag('dimension', null, {'ref': ref}));
  14552. o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
  14553. /* TODO: store in WB, process styles */
  14554. if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
  14555. defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
  14556. baseColWidth:opts.sheetFormat.baseColWidth||'10',
  14557. outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
  14558. }));
  14559. if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
  14560. o[sidx = o.length] = '<sheetData/>';
  14561. ws['!links'] = [];
  14562. if(ws['!ref'] != null) {
  14563. rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
  14564. if(rdata.length > 0) o[o.length] = (rdata);
  14565. }
  14566. if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
  14567. /* sheetCalcPr */
  14568. if(ws['!protect']) o[o.length] = write_ws_xml_protection(ws['!protect']);
  14569. /* protectedRanges */
  14570. /* scenarios */
  14571. if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
  14572. /* sortState */
  14573. /* dataConsolidate */
  14574. /* customSheetViews */
  14575. if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
  14576. /* phoneticPr */
  14577. /* conditionalFormatting */
  14578. /* dataValidations */
  14579. var relc = -1, rel, rId = -1;
  14580. if(ws['!links'].length > 0) {
  14581. o[o.length] = "<hyperlinks>";
  14582. ws['!links'].forEach(function(l) {
  14583. if(!l[1].Target) return;
  14584. rel = ({"ref":l[0]});
  14585. if(l[1].Target.charAt(0) != "#") {
  14586. rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
  14587. rel["r:id"] = "rId"+rId;
  14588. }
  14589. if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
  14590. if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
  14591. rel.display = l[1].display;
  14592. o[o.length] = writextag("hyperlink",null,rel);
  14593. });
  14594. o[o.length] = "</hyperlinks>";
  14595. }
  14596. delete ws['!links'];
  14597. /* printOptions */
  14598. if(ws['!margins'] != null) o[o.length] = write_ws_xml_margins(ws['!margins']);
  14599. /* pageSetup */
  14600. /* headerFooter */
  14601. /* rowBreaks */
  14602. /* colBreaks */
  14603. /* customProperties */
  14604. /* cellWatches */
  14605. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
  14606. /* smartTags */
  14607. if(_drawing.length > 0) {
  14608. rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  14609. o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
  14610. ws['!drawing'] = _drawing;
  14611. }
  14612. if(ws['!comments'].length > 0) {
  14613. rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  14614. o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
  14615. ws['!legacy'] = rId;
  14616. }
  14617. /* legacyDrawingHF */
  14618. /* picture */
  14619. /* oleObjects */
  14620. /* controls */
  14621. /* webPublishItems */
  14622. /* tableParts */
  14623. /* extLst */
  14624. if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
  14625. return o.join("");
  14626. }
  14627. /* [MS-XLSB] 2.4.726 BrtRowHdr */
  14628. function parse_BrtRowHdr(data, length) {
  14629. var z = ({});
  14630. var tgt = data.l + length;
  14631. z.r = data.read_shift(4);
  14632. data.l += 4; // TODO: ixfe
  14633. var miyRw = data.read_shift(2);
  14634. data.l += 1; // TODO: top/bot padding
  14635. var flags = data.read_shift(1);
  14636. data.l = tgt;
  14637. if(flags & 0x07) z.level = flags & 0x07;
  14638. if(flags & 0x10) z.hidden = true;
  14639. if(flags & 0x20) z.hpt = miyRw / 20;
  14640. return z;
  14641. }
  14642. function write_BrtRowHdr(R, range, ws) {
  14643. var o = new_buf(17+8*16);
  14644. var row = (ws['!rows']||[])[R]||{};
  14645. o.write_shift(4, R);
  14646. o.write_shift(4, 0); /* TODO: ixfe */
  14647. var miyRw = 0x0140;
  14648. if(row.hpx) miyRw = px2pt(row.hpx) * 20;
  14649. else if(row.hpt) miyRw = row.hpt * 20;
  14650. o.write_shift(2, miyRw);
  14651. o.write_shift(1, 0); /* top/bot padding */
  14652. var flags = 0x0;
  14653. if(row.level) flags |= row.level;
  14654. if(row.hidden) flags |= 0x10;
  14655. if(row.hpx || row.hpt) flags |= 0x20;
  14656. o.write_shift(1, flags);
  14657. o.write_shift(1, 0); /* phonetic guide */
  14658. /* [MS-XLSB] 2.5.8 BrtColSpan explains the mechanism */
  14659. var ncolspan = 0, lcs = o.l;
  14660. o.l += 4;
  14661. var caddr = {r:R, c:0};
  14662. for(var i = 0; i < 16; ++i) {
  14663. if((range.s.c > ((i+1) << 10)) || (range.e.c < (i << 10))) continue;
  14664. var first = -1, last = -1;
  14665. for(var j = (i<<10); j < ((i+1)<<10); ++j) {
  14666. caddr.c = j;
  14667. var cell = Array.isArray(ws) ? (ws[caddr.r]||[])[caddr.c] : ws[encode_cell(caddr)];
  14668. if(cell) { if(first < 0) first = j; last = j; }
  14669. }
  14670. if(first < 0) continue;
  14671. ++ncolspan;
  14672. o.write_shift(4, first);
  14673. o.write_shift(4, last);
  14674. }
  14675. var l = o.l;
  14676. o.l = lcs;
  14677. o.write_shift(4, ncolspan);
  14678. o.l = l;
  14679. return o.length > o.l ? o.slice(0, o.l) : o;
  14680. }
  14681. function write_row_header(ba, ws, range, R) {
  14682. var o = write_BrtRowHdr(R, range, ws);
  14683. if((o.length > 17) || (ws['!rows']||[])[R]) write_record(ba, 0x0000 /* BrtRowHdr */, o);
  14684. }
  14685. /* [MS-XLSB] 2.4.820 BrtWsDim */
  14686. var parse_BrtWsDim = parse_UncheckedRfX;
  14687. var write_BrtWsDim = write_UncheckedRfX;
  14688. /* [MS-XLSB] 2.4.821 BrtWsFmtInfo */
  14689. function parse_BrtWsFmtInfo() {
  14690. }
  14691. //function write_BrtWsFmtInfo(ws, o) { }
  14692. /* [MS-XLSB] 2.4.823 BrtWsProp */
  14693. function parse_BrtWsProp(data, length) {
  14694. var z = {};
  14695. var f = data[data.l]; ++data.l;
  14696. z.above = !(f & 0x40);
  14697. z.left = !(f & 0x80);
  14698. /* TODO: pull flags */
  14699. data.l += 18;
  14700. z.name = parse_XLSBCodeName(data, length - 19);
  14701. return z;
  14702. }
  14703. function write_BrtWsProp(str, outl, o) {
  14704. if(o == null) o = new_buf(84+4*str.length);
  14705. var f = 0xC0;
  14706. if(outl) {
  14707. if(outl.above) f &= ~0x40;
  14708. if(outl.left) f &= ~0x80;
  14709. }
  14710. o.write_shift(1, f);
  14711. for(var i = 1; i < 3; ++i) o.write_shift(1,0);
  14712. write_BrtColor({auto:1}, o);
  14713. o.write_shift(-4,-1);
  14714. o.write_shift(-4,-1);
  14715. write_XLSBCodeName(str, o);
  14716. return o.slice(0, o.l);
  14717. }
  14718. /* [MS-XLSB] 2.4.306 BrtCellBlank */
  14719. function parse_BrtCellBlank(data) {
  14720. var cell = parse_XLSBCell(data);
  14721. return [cell];
  14722. }
  14723. function write_BrtCellBlank(cell, ncell, o) {
  14724. if(o == null) o = new_buf(8);
  14725. return write_XLSBCell(ncell, o);
  14726. }
  14727. function parse_BrtShortBlank(data) {
  14728. var cell = parse_XLSBShortCell(data);
  14729. return [cell];
  14730. }
  14731. function write_BrtShortBlank(cell, ncell, o) {
  14732. if(o == null) o = new_buf(4);
  14733. return write_XLSBShortCell(ncell, o);
  14734. }
  14735. /* [MS-XLSB] 2.4.307 BrtCellBool */
  14736. function parse_BrtCellBool(data) {
  14737. var cell = parse_XLSBCell(data);
  14738. var fBool = data.read_shift(1);
  14739. return [cell, fBool, 'b'];
  14740. }
  14741. function write_BrtCellBool(cell, ncell, o) {
  14742. if(o == null) o = new_buf(9);
  14743. write_XLSBCell(ncell, o);
  14744. o.write_shift(1, cell.v ? 1 : 0);
  14745. return o;
  14746. }
  14747. function parse_BrtShortBool(data) {
  14748. var cell = parse_XLSBShortCell(data);
  14749. var fBool = data.read_shift(1);
  14750. return [cell, fBool, 'b'];
  14751. }
  14752. function write_BrtShortBool(cell, ncell, o) {
  14753. if(o == null) o = new_buf(5);
  14754. write_XLSBShortCell(ncell, o);
  14755. o.write_shift(1, cell.v ? 1 : 0);
  14756. return o;
  14757. }
  14758. /* [MS-XLSB] 2.4.308 BrtCellError */
  14759. function parse_BrtCellError(data) {
  14760. var cell = parse_XLSBCell(data);
  14761. var bError = data.read_shift(1);
  14762. return [cell, bError, 'e'];
  14763. }
  14764. function write_BrtCellError(cell, ncell, o) {
  14765. if(o == null) o = new_buf(9);
  14766. write_XLSBCell(ncell, o);
  14767. o.write_shift(1, cell.v);
  14768. return o;
  14769. }
  14770. function parse_BrtShortError(data) {
  14771. var cell = parse_XLSBShortCell(data);
  14772. var bError = data.read_shift(1);
  14773. return [cell, bError, 'e'];
  14774. }
  14775. function write_BrtShortError(cell, ncell, o) {
  14776. if(o == null) o = new_buf(8);
  14777. write_XLSBShortCell(ncell, o);
  14778. o.write_shift(1, cell.v);
  14779. o.write_shift(2, 0);
  14780. o.write_shift(1, 0);
  14781. return o;
  14782. }
  14783. /* [MS-XLSB] 2.4.311 BrtCellIsst */
  14784. function parse_BrtCellIsst(data) {
  14785. var cell = parse_XLSBCell(data);
  14786. var isst = data.read_shift(4);
  14787. return [cell, isst, 's'];
  14788. }
  14789. function write_BrtCellIsst(cell, ncell, o) {
  14790. if(o == null) o = new_buf(12);
  14791. write_XLSBCell(ncell, o);
  14792. o.write_shift(4, ncell.v);
  14793. return o;
  14794. }
  14795. function parse_BrtShortIsst(data) {
  14796. var cell = parse_XLSBShortCell(data);
  14797. var isst = data.read_shift(4);
  14798. return [cell, isst, 's'];
  14799. }
  14800. function write_BrtShortIsst(cell, ncell, o) {
  14801. if(o == null) o = new_buf(8);
  14802. write_XLSBShortCell(ncell, o);
  14803. o.write_shift(4, ncell.v);
  14804. return o;
  14805. }
  14806. /* [MS-XLSB] 2.4.313 BrtCellReal */
  14807. function parse_BrtCellReal(data) {
  14808. var cell = parse_XLSBCell(data);
  14809. var value = parse_Xnum(data);
  14810. return [cell, value, 'n'];
  14811. }
  14812. function write_BrtCellReal(cell, ncell, o) {
  14813. if(o == null) o = new_buf(16);
  14814. write_XLSBCell(ncell, o);
  14815. write_Xnum(cell.v, o);
  14816. return o;
  14817. }
  14818. function parse_BrtShortReal(data) {
  14819. var cell = parse_XLSBShortCell(data);
  14820. var value = parse_Xnum(data);
  14821. return [cell, value, 'n'];
  14822. }
  14823. function write_BrtShortReal(cell, ncell, o) {
  14824. if(o == null) o = new_buf(12);
  14825. write_XLSBShortCell(ncell, o);
  14826. write_Xnum(cell.v, o);
  14827. return o;
  14828. }
  14829. /* [MS-XLSB] 2.4.314 BrtCellRk */
  14830. function parse_BrtCellRk(data) {
  14831. var cell = parse_XLSBCell(data);
  14832. var value = parse_RkNumber(data);
  14833. return [cell, value, 'n'];
  14834. }
  14835. function write_BrtCellRk(cell, ncell, o) {
  14836. if(o == null) o = new_buf(12);
  14837. write_XLSBCell(ncell, o);
  14838. write_RkNumber(cell.v, o);
  14839. return o;
  14840. }
  14841. function parse_BrtShortRk(data) {
  14842. var cell = parse_XLSBShortCell(data);
  14843. var value = parse_RkNumber(data);
  14844. return [cell, value, 'n'];
  14845. }
  14846. function write_BrtShortRk(cell, ncell, o) {
  14847. if(o == null) o = new_buf(8);
  14848. write_XLSBShortCell(ncell, o);
  14849. write_RkNumber(cell.v, o);
  14850. return o;
  14851. }
  14852. /* [MS-XLSB] 2.4.323 BrtCellRString */
  14853. function parse_BrtCellRString(data) {
  14854. var cell = parse_XLSBCell(data);
  14855. var value = parse_RichStr(data);
  14856. return [cell, value, 'is'];
  14857. }
  14858. /* [MS-XLSB] 2.4.317 BrtCellSt */
  14859. function parse_BrtCellSt(data) {
  14860. var cell = parse_XLSBCell(data);
  14861. var value = parse_XLWideString(data);
  14862. return [cell, value, 'str'];
  14863. }
  14864. function write_BrtCellSt(cell, ncell, o) {
  14865. var data = cell.v == null ? "" : String(cell.v);
  14866. if(o == null) o = new_buf(12 + 4 * cell.v.length);
  14867. write_XLSBCell(ncell, o);
  14868. write_XLWideString(data, o);
  14869. return o.length > o.l ? o.slice(0, o.l) : o;
  14870. }
  14871. function parse_BrtShortSt(data) {
  14872. var cell = parse_XLSBShortCell(data);
  14873. var value = parse_XLWideString(data);
  14874. return [cell, value, 'str'];
  14875. }
  14876. function write_BrtShortSt(cell, ncell, o) {
  14877. var data = cell.v == null ? "" : String(cell.v);
  14878. if(o == null) o = new_buf(8 + 4 * data.length);
  14879. write_XLSBShortCell(ncell, o);
  14880. write_XLWideString(data, o);
  14881. return o.length > o.l ? o.slice(0, o.l) : o;
  14882. }
  14883. /* [MS-XLSB] 2.4.653 BrtFmlaBool */
  14884. function parse_BrtFmlaBool(data, length, opts) {
  14885. var end = data.l + length;
  14886. var cell = parse_XLSBCell(data);
  14887. cell.r = opts['!row'];
  14888. var value = data.read_shift(1);
  14889. var o = [cell, value, 'b'];
  14890. if(opts.cellFormula) {
  14891. data.l += 2;
  14892. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14893. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14894. }
  14895. else data.l = end;
  14896. return o;
  14897. }
  14898. /* [MS-XLSB] 2.4.654 BrtFmlaError */
  14899. function parse_BrtFmlaError(data, length, opts) {
  14900. var end = data.l + length;
  14901. var cell = parse_XLSBCell(data);
  14902. cell.r = opts['!row'];
  14903. var value = data.read_shift(1);
  14904. var o = [cell, value, 'e'];
  14905. if(opts.cellFormula) {
  14906. data.l += 2;
  14907. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14908. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14909. }
  14910. else data.l = end;
  14911. return o;
  14912. }
  14913. /* [MS-XLSB] 2.4.655 BrtFmlaNum */
  14914. function parse_BrtFmlaNum(data, length, opts) {
  14915. var end = data.l + length;
  14916. var cell = parse_XLSBCell(data);
  14917. cell.r = opts['!row'];
  14918. var value = parse_Xnum(data);
  14919. var o = [cell, value, 'n'];
  14920. if(opts.cellFormula) {
  14921. data.l += 2;
  14922. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14923. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14924. }
  14925. else data.l = end;
  14926. return o;
  14927. }
  14928. /* [MS-XLSB] 2.4.656 BrtFmlaString */
  14929. function parse_BrtFmlaString(data, length, opts) {
  14930. var end = data.l + length;
  14931. var cell = parse_XLSBCell(data);
  14932. cell.r = opts['!row'];
  14933. var value = parse_XLWideString(data);
  14934. var o = [cell, value, 'str'];
  14935. if(opts.cellFormula) {
  14936. data.l += 2;
  14937. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14938. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14939. }
  14940. else data.l = end;
  14941. return o;
  14942. }
  14943. /* [MS-XLSB] 2.4.682 BrtMergeCell */
  14944. var parse_BrtMergeCell = parse_UncheckedRfX;
  14945. var write_BrtMergeCell = write_UncheckedRfX;
  14946. /* [MS-XLSB] 2.4.107 BrtBeginMergeCells */
  14947. function write_BrtBeginMergeCells(cnt, o) {
  14948. if(o == null) o = new_buf(4);
  14949. o.write_shift(4, cnt);
  14950. return o;
  14951. }
  14952. /* [MS-XLSB] 2.4.662 BrtHLink */
  14953. function parse_BrtHLink(data, length) {
  14954. var end = data.l + length;
  14955. var rfx = parse_UncheckedRfX(data, 16);
  14956. var relId = parse_XLNullableWideString(data);
  14957. var loc = parse_XLWideString(data);
  14958. var tooltip = parse_XLWideString(data);
  14959. var display = parse_XLWideString(data);
  14960. data.l = end;
  14961. var o = ({rfx:rfx, relId:relId, loc:loc, display:display});
  14962. if(tooltip) o.Tooltip = tooltip;
  14963. return o;
  14964. }
  14965. function write_BrtHLink(l, rId) {
  14966. var o = new_buf(50+4*(l[1].Target.length + (l[1].Tooltip || "").length));
  14967. write_UncheckedRfX({s:decode_cell(l[0]), e:decode_cell(l[0])}, o);
  14968. write_RelID("rId" + rId, o);
  14969. var locidx = l[1].Target.indexOf("#");
  14970. var loc = locidx == -1 ? "" : l[1].Target.slice(locidx+1);
  14971. write_XLWideString(loc || "", o);
  14972. write_XLWideString(l[1].Tooltip || "", o);
  14973. write_XLWideString("", o);
  14974. return o.slice(0, o.l);
  14975. }
  14976. /* [MS-XLSB] 2.4.692 BrtPane */
  14977. function parse_BrtPane(/*data, length, opts*/) {
  14978. }
  14979. /* [MS-XLSB] 2.4.6 BrtArrFmla */
  14980. function parse_BrtArrFmla(data, length, opts) {
  14981. var end = data.l + length;
  14982. var rfx = parse_RfX(data, 16);
  14983. var fAlwaysCalc = data.read_shift(1);
  14984. var o = [rfx]; o[2] = fAlwaysCalc;
  14985. if(opts.cellFormula) {
  14986. var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
  14987. o[1] = formula;
  14988. } else data.l = end;
  14989. return o;
  14990. }
  14991. /* [MS-XLSB] 2.4.750 BrtShrFmla */
  14992. function parse_BrtShrFmla(data, length, opts) {
  14993. var end = data.l + length;
  14994. var rfx = parse_UncheckedRfX(data, 16);
  14995. var o = [rfx];
  14996. if(opts.cellFormula) {
  14997. var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
  14998. o[1] = formula;
  14999. data.l = end;
  15000. } else data.l = end;
  15001. return o;
  15002. }
  15003. /* [MS-XLSB] 2.4.323 BrtColInfo */
  15004. /* TODO: once XLS ColInfo is set, combine the functions */
  15005. function write_BrtColInfo(C, col, o) {
  15006. if(o == null) o = new_buf(18);
  15007. var p = col_obj_w(C, col);
  15008. o.write_shift(-4, C);
  15009. o.write_shift(-4, C);
  15010. o.write_shift(4, (p.width || 10) * 256);
  15011. o.write_shift(4, 0/*ixfe*/); // style
  15012. var flags = 0;
  15013. if(col.hidden) flags |= 0x01;
  15014. if(typeof p.width == 'number') flags |= 0x02;
  15015. if(col.level) flags |= (col.level << 8);
  15016. o.write_shift(2, flags); // bit flag
  15017. return o;
  15018. }
  15019. /* [MS-XLSB] 2.4.678 BrtMargins */
  15020. var BrtMarginKeys = ["left","right","top","bottom","header","footer"];
  15021. function parse_BrtMargins(data) {
  15022. var margins = ({});
  15023. BrtMarginKeys.forEach(function(k) { margins[k] = parse_Xnum(data, 8); });
  15024. return margins;
  15025. }
  15026. function write_BrtMargins(margins, o) {
  15027. if(o == null) o = new_buf(6*8);
  15028. default_margins(margins);
  15029. BrtMarginKeys.forEach(function(k) { write_Xnum((margins)[k], o); });
  15030. return o;
  15031. }
  15032. /* [MS-XLSB] 2.4.299 BrtBeginWsView */
  15033. function parse_BrtBeginWsView(data) {
  15034. var f = data.read_shift(2);
  15035. data.l += 28;
  15036. return { RTL: f & 0x20 };
  15037. }
  15038. function write_BrtBeginWsView(ws, Workbook, o) {
  15039. if(o == null) o = new_buf(30);
  15040. var f = 0x39c;
  15041. if((((Workbook||{}).Views||[])[0]||{}).RTL) f |= 0x20;
  15042. o.write_shift(2, f); // bit flag
  15043. o.write_shift(4, 0);
  15044. o.write_shift(4, 0); // view first row
  15045. o.write_shift(4, 0); // view first col
  15046. o.write_shift(1, 0); // gridline color ICV
  15047. o.write_shift(1, 0);
  15048. o.write_shift(2, 0);
  15049. o.write_shift(2, 100); // zoom scale
  15050. o.write_shift(2, 0);
  15051. o.write_shift(2, 0);
  15052. o.write_shift(2, 0);
  15053. o.write_shift(4, 0); // workbook view id
  15054. return o;
  15055. }
  15056. /* [MS-XLSB] 2.4.309 BrtCellIgnoreEC */
  15057. function write_BrtCellIgnoreEC(ref) {
  15058. var o = new_buf(24);
  15059. o.write_shift(4, 4);
  15060. o.write_shift(4, 1);
  15061. write_UncheckedRfX(ref, o);
  15062. return o;
  15063. }
  15064. /* [MS-XLSB] 2.4.748 BrtSheetProtection */
  15065. function write_BrtSheetProtection(sp, o) {
  15066. if(o == null) o = new_buf(16*4+2);
  15067. o.write_shift(2, sp.password ? crypto_CreatePasswordVerifier_Method1(sp.password) : 0);
  15068. o.write_shift(4, 1); // this record should not be written if no protection
  15069. [
  15070. ["objects", false], // fObjects
  15071. ["scenarios", false], // fScenarios
  15072. ["formatCells", true], // fFormatCells
  15073. ["formatColumns", true], // fFormatColumns
  15074. ["formatRows", true], // fFormatRows
  15075. ["insertColumns", true], // fInsertColumns
  15076. ["insertRows", true], // fInsertRows
  15077. ["insertHyperlinks", true], // fInsertHyperlinks
  15078. ["deleteColumns", true], // fDeleteColumns
  15079. ["deleteRows", true], // fDeleteRows
  15080. ["selectLockedCells", false], // fSelLockedCells
  15081. ["sort", true], // fSort
  15082. ["autoFilter", true], // fAutoFilter
  15083. ["pivotTables", true], // fPivotTables
  15084. ["selectUnlockedCells", false] // fSelUnlockedCells
  15085. ].forEach(function(n) {
  15086. if(n[1]) o.write_shift(4, sp[n[0]] != null && !sp[n[0]] ? 1 : 0);
  15087. else o.write_shift(4, sp[n[0]] != null && sp[n[0]] ? 0 : 1);
  15088. });
  15089. return o;
  15090. }
  15091. function parse_BrtDVal(/*data, length, opts*/) {
  15092. }
  15093. function parse_BrtDVal14(/*data, length, opts*/) {
  15094. }
  15095. /* [MS-XLSB] 2.1.7.61 Worksheet */
  15096. function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles) {
  15097. if(!data) return data;
  15098. var opts = _opts || {};
  15099. if(!rels) rels = {'!id':{}};
  15100. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  15101. var s = (opts.dense ? [] : {});
  15102. var ref;
  15103. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  15104. var state = [];
  15105. var pass = false, end = false;
  15106. var row, p, cf, R, C, addr, sstr, rr, cell;
  15107. var merges = [];
  15108. opts.biff = 12;
  15109. opts['!row'] = 0;
  15110. var ai = 0, af = false;
  15111. var arrayf = [];
  15112. var sharedf = {};
  15113. var supbooks = opts.supbooks || wb.supbooks || ([[]]);
  15114. supbooks.sharedf = sharedf;
  15115. supbooks.arrayf = arrayf;
  15116. supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x) { return x.name; });
  15117. if(!opts.supbooks) {
  15118. opts.supbooks = supbooks;
  15119. if(wb.Names) for(var i = 0; i < wb.Names.length; ++i) supbooks[0][i+1] = wb.Names[i];
  15120. }
  15121. var colinfo = [], rowinfo = [];
  15122. var seencol = false;
  15123. XLSBRecordEnum[0x0010] = { n:"BrtShortReal", f:parse_BrtShortReal };
  15124. var cm, vm;
  15125. recordhopper(data, function ws_parse(val, RR, RT) {
  15126. if(end) return;
  15127. switch(RT) {
  15128. case 0x0094: /* 'BrtWsDim' */
  15129. ref = val; break;
  15130. case 0x0000: /* 'BrtRowHdr' */
  15131. row = val;
  15132. if(opts.sheetRows && opts.sheetRows <= row.r) end=true;
  15133. rr = encode_row(R = row.r);
  15134. opts['!row'] = row.r;
  15135. if(val.hidden || val.hpt || val.level != null) {
  15136. if(val.hpt) val.hpx = pt2px(val.hpt);
  15137. rowinfo[val.r] = val;
  15138. }
  15139. break;
  15140. case 0x0002: /* 'BrtCellRk' */
  15141. case 0x0003: /* 'BrtCellError' */
  15142. case 0x0004: /* 'BrtCellBool' */
  15143. case 0x0005: /* 'BrtCellReal' */
  15144. case 0x0006: /* 'BrtCellSt' */
  15145. case 0x0007: /* 'BrtCellIsst' */
  15146. case 0x0008: /* 'BrtFmlaString' */
  15147. case 0x0009: /* 'BrtFmlaNum' */
  15148. case 0x000A: /* 'BrtFmlaBool' */
  15149. case 0x000B: /* 'BrtFmlaError' */
  15150. case 0x000D: /* 'BrtShortRk' */
  15151. case 0x000E: /* 'BrtShortError' */
  15152. case 0x000F: /* 'BrtShortBool' */
  15153. case 0x0010: /* 'BrtShortReal' */
  15154. case 0x0011: /* 'BrtShortSt' */
  15155. case 0x0012: /* 'BrtShortIsst' */
  15156. case 0x003E: /* 'BrtCellRString' */
  15157. p = ({t:val[2]});
  15158. switch(val[2]) {
  15159. case 'n': p.v = val[1]; break;
  15160. case 's': sstr = strs[val[1]]; p.v = sstr.t; p.r = sstr.r; break;
  15161. case 'b': p.v = val[1] ? true : false; break;
  15162. case 'e': p.v = val[1]; if(opts.cellText !== false) p.w = BErr[p.v]; break;
  15163. case 'str': p.t = 's'; p.v = val[1]; break;
  15164. case 'is': p.t = 's'; p.v = val[1].t; break;
  15165. }
  15166. if((cf = styles.CellXf[val[0].iStyleRef])) safe_format(p,cf.numFmtId,null,opts, themes, styles);
  15167. C = val[0].c == -1 ? C + 1 : val[0].c;
  15168. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  15169. else s[encode_col(C) + rr] = p;
  15170. if(opts.cellFormula) {
  15171. af = false;
  15172. for(ai = 0; ai < arrayf.length; ++ai) {
  15173. var aii = arrayf[ai];
  15174. if(row.r >= aii[0].s.r && row.r <= aii[0].e.r)
  15175. if(C >= aii[0].s.c && C <= aii[0].e.c) {
  15176. p.F = encode_range(aii[0]); af = true;
  15177. }
  15178. }
  15179. if(!af && val.length > 3) p.f = val[3];
  15180. }
  15181. if(refguess.s.r > row.r) refguess.s.r = row.r;
  15182. if(refguess.s.c > C) refguess.s.c = C;
  15183. if(refguess.e.r < row.r) refguess.e.r = row.r;
  15184. if(refguess.e.c < C) refguess.e.c = C;
  15185. if(opts.cellDates && cf && p.t == 'n' && fmt_is_date(table_fmt[cf.numFmtId])) {
  15186. var _d = SSF_parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  15187. }
  15188. if(cm) {
  15189. if(cm.type == 'XLDAPR') p.D = true;
  15190. cm = void 0;
  15191. }
  15192. if(vm) vm = void 0;
  15193. break;
  15194. case 0x0001: /* 'BrtCellBlank' */
  15195. case 0x000C: /* 'BrtShortBlank' */
  15196. if(!opts.sheetStubs || pass) break;
  15197. p = ({t:'z',v:void 0});
  15198. C = val[0].c == -1 ? C + 1 : val[0].c;
  15199. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  15200. else s[encode_col(C) + rr] = p;
  15201. if(refguess.s.r > row.r) refguess.s.r = row.r;
  15202. if(refguess.s.c > C) refguess.s.c = C;
  15203. if(refguess.e.r < row.r) refguess.e.r = row.r;
  15204. if(refguess.e.c < C) refguess.e.c = C;
  15205. if(cm) {
  15206. if(cm.type == 'XLDAPR') p.D = true;
  15207. cm = void 0;
  15208. }
  15209. if(vm) vm = void 0;
  15210. break;
  15211. case 0x00B0: /* 'BrtMergeCell' */
  15212. merges.push(val); break;
  15213. case 0x0031: { /* 'BrtCellMeta' */
  15214. cm = ((opts.xlmeta||{}).Cell||[])[val-1];
  15215. } break;
  15216. case 0x01EE: /* 'BrtHLink' */
  15217. var rel = rels['!id'][val.relId];
  15218. if(rel) {
  15219. val.Target = rel.Target;
  15220. if(val.loc) val.Target += "#"+val.loc;
  15221. val.Rel = rel;
  15222. } else if(val.relId == '') {
  15223. val.Target = "#" + val.loc;
  15224. }
  15225. for(R=val.rfx.s.r;R<=val.rfx.e.r;++R) for(C=val.rfx.s.c;C<=val.rfx.e.c;++C) {
  15226. if(opts.dense) {
  15227. if(!s[R]) s[R] = [];
  15228. if(!s[R][C]) s[R][C] = {t:'z',v:undefined};
  15229. s[R][C].l = val;
  15230. } else {
  15231. addr = encode_cell({c:C,r:R});
  15232. if(!s[addr]) s[addr] = {t:'z',v:undefined};
  15233. s[addr].l = val;
  15234. }
  15235. }
  15236. break;
  15237. case 0x01AA: /* 'BrtArrFmla' */
  15238. if(!opts.cellFormula) break;
  15239. arrayf.push(val);
  15240. cell = ((opts.dense ? s[R][C] : s[encode_col(C) + rr]));
  15241. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  15242. cell.F = encode_range(val[0]);
  15243. break;
  15244. case 0x01AB: /* 'BrtShrFmla' */
  15245. if(!opts.cellFormula) break;
  15246. sharedf[encode_cell(val[0].s)] = val[1];
  15247. cell = (opts.dense ? s[R][C] : s[encode_col(C) + rr]);
  15248. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  15249. break;
  15250. /* identical to 'ColInfo' in XLS */
  15251. case 0x003C: /* 'BrtColInfo' */
  15252. if(!opts.cellStyles) break;
  15253. while(val.e >= val.s) {
  15254. colinfo[val.e--] = { width: val.w/256, hidden: !!(val.flags & 0x01), level: val.level };
  15255. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  15256. process_col(colinfo[val.e+1]);
  15257. }
  15258. break;
  15259. case 0x00A1: /* 'BrtBeginAFilter' */
  15260. s['!autofilter'] = { ref:encode_range(val) };
  15261. break;
  15262. case 0x01DC: /* 'BrtMargins' */
  15263. s['!margins'] = val;
  15264. break;
  15265. case 0x0093: /* 'BrtWsProp' */
  15266. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  15267. if(val.name) wb.Sheets[idx].CodeName = val.name;
  15268. if(val.above || val.left) s['!outline'] = { above: val.above, left: val.left };
  15269. break;
  15270. case 0x0089: /* 'BrtBeginWsView' */
  15271. if(!wb.Views) wb.Views = [{}];
  15272. if(!wb.Views[0]) wb.Views[0] = {};
  15273. if(val.RTL) wb.Views[0].RTL = true;
  15274. break;
  15275. case 0x01E5: /* 'BrtWsFmtInfo' */
  15276. break;
  15277. case 0x0040: /* 'BrtDVal' */
  15278. case 0x041D: /* 'BrtDVal14' */
  15279. break;
  15280. case 0x0097: /* 'BrtPane' */
  15281. break;
  15282. case 0x0098: /* 'BrtSel' */
  15283. case 0x00AF: /* 'BrtAFilterDateGroupItem' */
  15284. case 0x0284: /* 'BrtActiveX' */
  15285. case 0x0271: /* 'BrtBigName' */
  15286. case 0x0232: /* 'BrtBkHim' */
  15287. case 0x018C: /* 'BrtBrk' */
  15288. case 0x0458: /* 'BrtCFIcon' */
  15289. case 0x047A: /* 'BrtCFRuleExt' */
  15290. case 0x01D7: /* 'BrtCFVO' */
  15291. case 0x041A: /* 'BrtCFVO14' */
  15292. case 0x0289: /* 'BrtCellIgnoreEC' */
  15293. case 0x0451: /* 'BrtCellIgnoreEC14' */
  15294. case 0x024D: /* 'BrtCellSmartTagProperty' */
  15295. case 0x025F: /* 'BrtCellWatch' */
  15296. case 0x0234: /* 'BrtColor' */
  15297. case 0x041F: /* 'BrtColor14' */
  15298. case 0x00A8: /* 'BrtColorFilter' */
  15299. case 0x00AE: /* 'BrtCustomFilter' */
  15300. case 0x049C: /* 'BrtCustomFilter14' */
  15301. case 0x01F3: /* 'BrtDRef' */
  15302. case 0x01FB: /* 'BrtDXF' */
  15303. case 0x0226: /* 'BrtDrawing' */
  15304. case 0x00AB: /* 'BrtDynamicFilter' */
  15305. case 0x00A7: /* 'BrtFilter' */
  15306. case 0x0499: /* 'BrtFilter14' */
  15307. case 0x00A9: /* 'BrtIconFilter' */
  15308. case 0x049D: /* 'BrtIconFilter14' */
  15309. case 0x0227: /* 'BrtLegacyDrawing' */
  15310. case 0x0228: /* 'BrtLegacyDrawingHF' */
  15311. case 0x0295: /* 'BrtListPart' */
  15312. case 0x027F: /* 'BrtOleObject' */
  15313. case 0x01DE: /* 'BrtPageSetup' */
  15314. case 0x0219: /* 'BrtPhoneticInfo' */
  15315. case 0x01DD: /* 'BrtPrintOptions' */
  15316. case 0x0218: /* 'BrtRangeProtection' */
  15317. case 0x044F: /* 'BrtRangeProtection14' */
  15318. case 0x02A8: /* 'BrtRangeProtectionIso' */
  15319. case 0x0450: /* 'BrtRangeProtectionIso14' */
  15320. case 0x0400: /* 'BrtRwDescent' */
  15321. case 0x0297: /* 'BrtSheetCalcProp' */
  15322. case 0x0217: /* 'BrtSheetProtection' */
  15323. case 0x02A6: /* 'BrtSheetProtectionIso' */
  15324. case 0x01F8: /* 'BrtSlc' */
  15325. case 0x0413: /* 'BrtSparkline' */
  15326. case 0x01AC: /* 'BrtTable' */
  15327. case 0x00AA: /* 'BrtTop10Filter' */
  15328. case 0x0C00: /* 'BrtUid' */
  15329. case 0x0032: /* 'BrtValueMeta' */
  15330. case 0x0816: /* 'BrtWebExtension' */
  15331. case 0x0415: /* 'BrtWsFmtInfoEx14' */
  15332. break;
  15333. case 0x0023: /* 'BrtFRTBegin' */
  15334. pass = true; break;
  15335. case 0x0024: /* 'BrtFRTEnd' */
  15336. pass = false; break;
  15337. case 0x0025: /* 'BrtACBegin' */
  15338. state.push(RT); pass = true; break;
  15339. case 0x0026: /* 'BrtACEnd' */
  15340. state.pop(); pass = false; break;
  15341. default:
  15342. if(RR.T){/* empty */}
  15343. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  15344. }
  15345. }, opts);
  15346. delete opts.supbooks;
  15347. delete opts['!row'];
  15348. if(!s["!ref"] && (refguess.s.r < 2000000 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s["!ref"] = encode_range(ref || refguess);
  15349. if(opts.sheetRows && s["!ref"]) {
  15350. var tmpref = safe_decode_range(s["!ref"]);
  15351. if(opts.sheetRows <= +tmpref.e.r) {
  15352. tmpref.e.r = opts.sheetRows - 1;
  15353. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  15354. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  15355. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  15356. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  15357. s["!fullref"] = s["!ref"];
  15358. s["!ref"] = encode_range(tmpref);
  15359. }
  15360. }
  15361. if(merges.length > 0) s["!merges"] = merges;
  15362. if(colinfo.length > 0) s["!cols"] = colinfo;
  15363. if(rowinfo.length > 0) s["!rows"] = rowinfo;
  15364. return s;
  15365. }
  15366. /* TODO: something useful -- this is a stub */
  15367. function write_ws_bin_cell(ba, cell, R, C, opts, ws, last_seen) {
  15368. var o = ({r:R, c:C});
  15369. if(cell.c) ws['!comments'].push([encode_cell(o), cell.c]);
  15370. if(cell.v === undefined) return false;
  15371. var vv = "";
  15372. switch(cell.t) {
  15373. case 'b': vv = cell.v ? "1" : "0"; break;
  15374. case 'd': // no BrtCellDate :(
  15375. cell = dup(cell);
  15376. cell.z = cell.z || table_fmt[14];
  15377. cell.v = datenum(parseDate(cell.v)); cell.t = 'n';
  15378. break;
  15379. /* falls through */
  15380. case 'n': case 'e': vv = ''+cell.v; break;
  15381. default: vv = cell.v; break;
  15382. }
  15383. /* TODO: cell style */
  15384. o.s = get_cell_style(opts.cellXfs, cell, opts);
  15385. if(cell.l) ws['!links'].push([encode_cell(o), cell.l]);
  15386. switch(cell.t) {
  15387. case 's': case 'str':
  15388. if(opts.bookSST) {
  15389. vv = get_sst_id(opts.Strings, (cell.v == null ? "" : String(cell.v)), opts.revStrings);
  15390. o.t = "s"; o.v = vv;
  15391. if(last_seen) write_record(ba, 0x0012 /* BrtShortIsst */, write_BrtShortIsst(cell, o));
  15392. else write_record(ba, 0x0007 /* BrtCellIsst */, write_BrtCellIsst(cell, o));
  15393. } else {
  15394. o.t = "str";
  15395. if(last_seen) write_record(ba, 0x0011 /* BrtShortSt */, write_BrtShortSt(cell, o));
  15396. else write_record(ba, 0x0006 /* BrtCellSt */, write_BrtCellSt(cell, o));
  15397. }
  15398. return true;
  15399. case 'n':
  15400. /* TODO: determine threshold for Real vs RK */
  15401. if(cell.v == (cell.v | 0) && cell.v > -1000 && cell.v < 1000) {
  15402. if(last_seen) write_record(ba, 0x000D /* BrtShortRk */, write_BrtShortRk(cell, o));
  15403. else write_record(ba, 0x0002 /* BrtCellRk */, write_BrtCellRk(cell, o));
  15404. } else {
  15405. if(last_seen) write_record(ba, 0x0010 /* BrtShortReal */, write_BrtShortReal(cell, o));
  15406. else write_record(ba, 0x0005 /* BrtCellReal */, write_BrtCellReal(cell, o));
  15407. } return true;
  15408. case 'b':
  15409. o.t = "b";
  15410. if(last_seen) write_record(ba, 0x000F /* BrtShortBool */, write_BrtShortBool(cell, o));
  15411. else write_record(ba, 0x0004 /* BrtCellBool */, write_BrtCellBool(cell, o));
  15412. return true;
  15413. case 'e':
  15414. o.t = "e";
  15415. if(last_seen) write_record(ba, 0x000E /* BrtShortError */, write_BrtShortError(cell, o));
  15416. else write_record(ba, 0x0003 /* BrtCellError */, write_BrtCellError(cell, o));
  15417. return true;
  15418. }
  15419. if(last_seen) write_record(ba, 0x000C /* BrtShortBlank */, write_BrtShortBlank(cell, o));
  15420. else write_record(ba, 0x0001 /* BrtCellBlank */, write_BrtCellBlank(cell, o));
  15421. return true;
  15422. }
  15423. function write_CELLTABLE(ba, ws, idx, opts) {
  15424. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  15425. write_record(ba, 0x0091 /* BrtBeginSheetData */);
  15426. var dense = Array.isArray(ws);
  15427. var cap = range.e.r;
  15428. if(ws['!rows']) cap = Math.max(range.e.r, ws['!rows'].length - 1);
  15429. for(var R = range.s.r; R <= cap; ++R) {
  15430. rr = encode_row(R);
  15431. /* [ACCELLTABLE] */
  15432. /* BrtRowHdr */
  15433. write_row_header(ba, ws, range, R);
  15434. var last_seen = false;
  15435. if(R <= range.e.r) for(var C = range.s.c; C <= range.e.c; ++C) {
  15436. /* *16384CELL */
  15437. if(R === range.s.r) cols[C] = encode_col(C);
  15438. ref = cols[C] + rr;
  15439. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  15440. if(!cell) { last_seen = false; continue; }
  15441. /* write cell */
  15442. last_seen = write_ws_bin_cell(ba, cell, R, C, opts, ws, last_seen);
  15443. }
  15444. }
  15445. write_record(ba, 0x0092 /* BrtEndSheetData */);
  15446. }
  15447. function write_MERGECELLS(ba, ws) {
  15448. if(!ws || !ws['!merges']) return;
  15449. write_record(ba, 0x00B1 /* BrtBeginMergeCells */, write_BrtBeginMergeCells(ws['!merges'].length));
  15450. ws['!merges'].forEach(function(m) { write_record(ba, 0x00B0 /* BrtMergeCell */, write_BrtMergeCell(m)); });
  15451. write_record(ba, 0x00B2 /* BrtEndMergeCells */);
  15452. }
  15453. function write_COLINFOS(ba, ws) {
  15454. if(!ws || !ws['!cols']) return;
  15455. write_record(ba, 0x0186 /* BrtBeginColInfos */);
  15456. ws['!cols'].forEach(function(m, i) { if(m) write_record(ba, 0x003C /* 'BrtColInfo' */, write_BrtColInfo(i, m)); });
  15457. write_record(ba, 0x0187 /* BrtEndColInfos */);
  15458. }
  15459. function write_IGNOREECS(ba, ws) {
  15460. if(!ws || !ws['!ref']) return;
  15461. write_record(ba, 0x0288 /* BrtBeginCellIgnoreECs */);
  15462. write_record(ba, 0x0289 /* BrtCellIgnoreEC */, write_BrtCellIgnoreEC(safe_decode_range(ws['!ref'])));
  15463. write_record(ba, 0x028A /* BrtEndCellIgnoreECs */);
  15464. }
  15465. function write_HLINKS(ba, ws, rels) {
  15466. /* *BrtHLink */
  15467. ws['!links'].forEach(function(l) {
  15468. if(!l[1].Target) return;
  15469. var rId = add_rels(rels, -1, l[1].Target.replace(/#.*$/, ""), RELS.HLINK);
  15470. write_record(ba, 0x01EE /* BrtHLink */, write_BrtHLink(l, rId));
  15471. });
  15472. delete ws['!links'];
  15473. }
  15474. function write_LEGACYDRAWING(ba, ws, idx, rels) {
  15475. /* [BrtLegacyDrawing] */
  15476. if(ws['!comments'].length > 0) {
  15477. var rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  15478. write_record(ba, 0x0227 /* BrtLegacyDrawing */, write_RelID("rId" + rId));
  15479. ws['!legacy'] = rId;
  15480. }
  15481. }
  15482. function write_AUTOFILTER(ba, ws, wb, idx) {
  15483. if(!ws['!autofilter']) return;
  15484. var data = ws['!autofilter'];
  15485. var ref = typeof data.ref === "string" ? data.ref : encode_range(data.ref);
  15486. /* Update FilterDatabase defined name for the worksheet */
  15487. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  15488. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  15489. var names = wb.Workbook.Names;
  15490. var range = decode_range(ref);
  15491. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  15492. for(var i = 0; i < names.length; ++i) {
  15493. var name = names[i];
  15494. if(name.Name != '_xlnm._FilterDatabase') continue;
  15495. if(name.Sheet != idx) continue;
  15496. name.Ref = formula_quote_sheet_name(wb.SheetNames[idx]) + "!" + fix_range(ref); break;
  15497. }
  15498. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: formula_quote_sheet_name(wb.SheetNames[idx]) + "!" + fix_range(ref) });
  15499. write_record(ba, 0x00A1 /* BrtBeginAFilter */, write_UncheckedRfX(safe_decode_range(ref)));
  15500. /* *FILTERCOLUMN */
  15501. /* [SORTSTATE] */
  15502. /* BrtEndAFilter */
  15503. write_record(ba, 0x00A2 /* BrtEndAFilter */);
  15504. }
  15505. function write_WSVIEWS2(ba, ws, Workbook) {
  15506. write_record(ba, 0x0085 /* BrtBeginWsViews */);
  15507. { /* 1*WSVIEW2 */
  15508. /* [ACUID] */
  15509. write_record(ba, 0x0089 /* BrtBeginWsView */, write_BrtBeginWsView(ws, Workbook));
  15510. /* [BrtPane] */
  15511. /* *4BrtSel */
  15512. /* *4SXSELECT */
  15513. /* *FRT */
  15514. write_record(ba, 0x008A /* BrtEndWsView */);
  15515. }
  15516. /* *FRT */
  15517. write_record(ba, 0x0086 /* BrtEndWsViews */);
  15518. }
  15519. function write_WSFMTINFO() {
  15520. /* [ACWSFMTINFO] */
  15521. // write_record(ba, 0x01E5 /* BrtWsFmtInfo */, write_BrtWsFmtInfo(ws));
  15522. }
  15523. function write_SHEETPROTECT(ba, ws) {
  15524. if(!ws['!protect']) return;
  15525. /* [BrtSheetProtectionIso] */
  15526. write_record(ba, 0x0217 /* BrtSheetProtection */, write_BrtSheetProtection(ws['!protect']));
  15527. }
  15528. function write_ws_bin(idx, opts, wb, rels) {
  15529. var ba = buf_array();
  15530. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  15531. var c = s; try { if(wb && wb.Workbook) c = wb.Workbook.Sheets[idx].CodeName || c; } catch(e) {}
  15532. var r = safe_decode_range(ws['!ref'] || "A1");
  15533. if(r.e.c > 0x3FFF || r.e.r > 0xFFFFF) {
  15534. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:XFD1048576");
  15535. r.e.c = Math.min(r.e.c, 0x3FFF);
  15536. r.e.r = Math.min(r.e.c, 0xFFFFF);
  15537. }
  15538. ws['!links'] = [];
  15539. /* passed back to write_zip and removed there */
  15540. ws['!comments'] = [];
  15541. write_record(ba, 0x0081 /* BrtBeginSheet */);
  15542. if(wb.vbaraw || ws['!outline']) write_record(ba, 0x0093 /* BrtWsProp */, write_BrtWsProp(c, ws['!outline']));
  15543. write_record(ba, 0x0094 /* BrtWsDim */, write_BrtWsDim(r));
  15544. write_WSVIEWS2(ba, ws, wb.Workbook);
  15545. write_WSFMTINFO(ba, ws);
  15546. write_COLINFOS(ba, ws, idx, opts, wb);
  15547. write_CELLTABLE(ba, ws, idx, opts, wb);
  15548. /* [BrtSheetCalcProp] */
  15549. write_SHEETPROTECT(ba, ws);
  15550. /* *([BrtRangeProtectionIso] BrtRangeProtection) */
  15551. /* [SCENMAN] */
  15552. write_AUTOFILTER(ba, ws, wb, idx);
  15553. /* [SORTSTATE] */
  15554. /* [DCON] */
  15555. /* [USERSHVIEWS] */
  15556. write_MERGECELLS(ba, ws);
  15557. /* [BrtPhoneticInfo] */
  15558. /* *CONDITIONALFORMATTING */
  15559. /* [DVALS] */
  15560. write_HLINKS(ba, ws, rels);
  15561. /* [BrtPrintOptions] */
  15562. if(ws['!margins']) write_record(ba, 0x01DC /* BrtMargins */, write_BrtMargins(ws['!margins']));
  15563. /* [BrtPageSetup] */
  15564. /* [HEADERFOOTER] */
  15565. /* [RWBRK] */
  15566. /* [COLBRK] */
  15567. /* *BrtBigName */
  15568. /* [CELLWATCHES] */
  15569. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) write_IGNOREECS(ba, ws);
  15570. /* [SMARTTAGS] */
  15571. /* [BrtDrawing] */
  15572. write_LEGACYDRAWING(ba, ws, idx, rels);
  15573. /* [BrtLegacyDrawingHF] */
  15574. /* [BrtBkHim] */
  15575. /* [OLEOBJECTS] */
  15576. /* [ACTIVEXCONTROLS] */
  15577. /* [WEBPUBITEMS] */
  15578. /* [LISTPARTS] */
  15579. /* FRTWORKSHEET */
  15580. write_record(ba, 0x0082 /* BrtEndSheet */);
  15581. return ba.end();
  15582. }
  15583. function parse_Cache(data) {
  15584. var col = [];
  15585. var num = data.match(/^<c:numCache>/);
  15586. var f;
  15587. /* 21.2.2.150 pt CT_NumVal */
  15588. (data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
  15589. var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
  15590. if(!q) return;
  15591. col[+q[1]] = num ? +q[2] : q[2];
  15592. });
  15593. /* 21.2.2.71 formatCode CT_Xstring */
  15594. var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);
  15595. (data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });
  15596. return [col, nf, f];
  15597. }
  15598. /* 21.2 DrawingML - Charts */
  15599. function parse_chart(data, name, opts, rels, wb, csheet) {
  15600. var cs = ((csheet || {"!type":"chart"}));
  15601. if(!data) return csheet;
  15602. /* 21.2.2.27 chart CT_Chart */
  15603. var C = 0, R = 0, col = "A";
  15604. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  15605. /* 21.2.2.120 numCache CT_NumData */
  15606. (data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
  15607. var cache = parse_Cache(nc);
  15608. refguess.s.r = refguess.s.c = 0;
  15609. refguess.e.c = C;
  15610. col = encode_col(C);
  15611. cache[0].forEach(function(n,i) {
  15612. cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
  15613. R = i;
  15614. });
  15615. if(refguess.e.r < R) refguess.e.r = R;
  15616. ++C;
  15617. });
  15618. if(C > 0) cs["!ref"] = encode_range(refguess);
  15619. return cs;
  15620. }
  15621. /* 18.3 Worksheets also covers Chartsheets */
  15622. function parse_cs_xml(data, opts, idx, rels, wb) {
  15623. if(!data) return data;
  15624. /* 18.3.1.12 chartsheet CT_ChartSheet */
  15625. if(!rels) rels = {'!id':{}};
  15626. var s = ({'!type':"chart", '!drawel':null, '!rel':""});
  15627. var m;
  15628. /* 18.3.1.83 sheetPr CT_ChartsheetPr */
  15629. var sheetPr = data.match(sheetprregex);
  15630. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  15631. /* 18.3.1.36 drawing CT_Drawing */
  15632. if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];
  15633. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  15634. return s;
  15635. }
  15636. //function write_cs_xml(idx, opts, wb, rels) {
  15637. // var o = [XML_HEADER, writextag('chartsheet', null, {
  15638. // 'xmlns': XMLNS_main[0],
  15639. // 'xmlns:r': XMLNS.r
  15640. // })];
  15641. // o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
  15642. // add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  15643. // if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
  15644. // return o.join("");
  15645. //}
  15646. /* [MS-XLSB] 2.4.331 BrtCsProp */
  15647. function parse_BrtCsProp(data, length) {
  15648. data.l += 10;
  15649. var name = parse_XLWideString(data, length - 10);
  15650. return { name: name };
  15651. }
  15652. /* [MS-XLSB] 2.1.7.7 Chart Sheet */
  15653. function parse_cs_bin(data, opts, idx, rels, wb) {
  15654. if(!data) return data;
  15655. if(!rels) rels = {'!id':{}};
  15656. var s = {'!type':"chart", '!drawel':null, '!rel':""};
  15657. var state = [];
  15658. var pass = false;
  15659. recordhopper(data, function cs_parse(val, R, RT) {
  15660. switch(RT) {
  15661. case 0x0226: /* 'BrtDrawing' */
  15662. s['!rel'] = val; break;
  15663. case 0x028B: /* 'BrtCsProp' */
  15664. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  15665. if(val.name) wb.Sheets[idx].CodeName = val.name;
  15666. break;
  15667. case 0x0232: /* 'BrtBkHim' */
  15668. case 0x028C: /* 'BrtCsPageSetup' */
  15669. case 0x029D: /* 'BrtCsProtection' */
  15670. case 0x02A7: /* 'BrtCsProtectionIso' */
  15671. case 0x0227: /* 'BrtLegacyDrawing' */
  15672. case 0x0228: /* 'BrtLegacyDrawingHF' */
  15673. case 0x01DC: /* 'BrtMargins' */
  15674. case 0x0C00: /* 'BrtUid' */
  15675. break;
  15676. case 0x0023: /* 'BrtFRTBegin' */
  15677. pass = true; break;
  15678. case 0x0024: /* 'BrtFRTEnd' */
  15679. pass = false; break;
  15680. case 0x0025: /* 'BrtACBegin' */
  15681. state.push(RT); break;
  15682. case 0x0026: /* 'BrtACEnd' */
  15683. state.pop(); break;
  15684. default:
  15685. if(R.T > 0) state.push(RT);
  15686. else if(R.T < 0) state.pop();
  15687. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  15688. }
  15689. }, opts);
  15690. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  15691. return s;
  15692. }
  15693. //function write_cs_bin() {
  15694. // var ba = buf_array();
  15695. // write_record(ba, 0x0081 /* BrtBeginSheet */);
  15696. // /* [BrtCsProp] */
  15697. // /* CSVIEWS */
  15698. // /* [[BrtCsProtectionIso] BrtCsProtection] */
  15699. // /* [USERCSVIEWS] */
  15700. // /* [BrtMargins] */
  15701. // /* [BrtCsPageSetup] */
  15702. // /* [HEADERFOOTER] */
  15703. // /* BrtDrawing */
  15704. // /* [BrtLegacyDrawing] */
  15705. // /* [BrtLegacyDrawingHF] */
  15706. // /* [BrtBkHim] */
  15707. // /* [WEBPUBITEMS] */
  15708. // /* FRTCHARTSHEET */
  15709. // write_record(ba, 0x0082 /* BrtEndSheet */);
  15710. // return ba.end();
  15711. //}
  15712. /* 18.2.28 (CT_WorkbookProtection) Defaults */
  15713. var WBPropsDef = [
  15714. ['allowRefreshQuery', false, "bool"],
  15715. ['autoCompressPictures', true, "bool"],
  15716. ['backupFile', false, "bool"],
  15717. ['checkCompatibility', false, "bool"],
  15718. ['CodeName', ''],
  15719. ['date1904', false, "bool"],
  15720. ['defaultThemeVersion', 0, "int"],
  15721. ['filterPrivacy', false, "bool"],
  15722. ['hidePivotFieldList', false, "bool"],
  15723. ['promptedSolutions', false, "bool"],
  15724. ['publishItems', false, "bool"],
  15725. ['refreshAllConnections', false, "bool"],
  15726. ['saveExternalLinkValues', true, "bool"],
  15727. ['showBorderUnselectedTables', true, "bool"],
  15728. ['showInkAnnotation', true, "bool"],
  15729. ['showObjects', 'all'],
  15730. ['showPivotChartFilter', false, "bool"],
  15731. ['updateLinks', 'userSet']
  15732. ];
  15733. /* 18.2.30 (CT_BookView) Defaults */
  15734. var WBViewDef = [
  15735. ['activeTab', 0, "int"],
  15736. ['autoFilterDateGrouping', true, "bool"],
  15737. ['firstSheet', 0, "int"],
  15738. ['minimized', false, "bool"],
  15739. ['showHorizontalScroll', true, "bool"],
  15740. ['showSheetTabs', true, "bool"],
  15741. ['showVerticalScroll', true, "bool"],
  15742. ['tabRatio', 600, "int"],
  15743. ['visibility', 'visible']
  15744. //window{Height,Width}, {x,y}Window
  15745. ];
  15746. /* 18.2.19 (CT_Sheet) Defaults */
  15747. var SheetDef = [
  15748. //['state', 'visible']
  15749. ];
  15750. /* 18.2.2 (CT_CalcPr) Defaults */
  15751. var CalcPrDef = [
  15752. ['calcCompleted', 'true'],
  15753. ['calcMode', 'auto'],
  15754. ['calcOnSave', 'true'],
  15755. ['concurrentCalc', 'true'],
  15756. ['fullCalcOnLoad', 'false'],
  15757. ['fullPrecision', 'true'],
  15758. ['iterate', 'false'],
  15759. ['iterateCount', '100'],
  15760. ['iterateDelta', '0.001'],
  15761. ['refMode', 'A1']
  15762. ];
  15763. /* 18.2.3 (CT_CustomWorkbookView) Defaults */
  15764. /*var CustomWBViewDef = [
  15765. ['autoUpdate', 'false'],
  15766. ['changesSavedWin', 'false'],
  15767. ['includeHiddenRowCol', 'true'],
  15768. ['includePrintSettings', 'true'],
  15769. ['maximized', 'false'],
  15770. ['minimized', 'false'],
  15771. ['onlySync', 'false'],
  15772. ['personalView', 'false'],
  15773. ['showComments', 'commIndicator'],
  15774. ['showFormulaBar', 'true'],
  15775. ['showHorizontalScroll', 'true'],
  15776. ['showObjects', 'all'],
  15777. ['showSheetTabs', 'true'],
  15778. ['showStatusbar', 'true'],
  15779. ['showVerticalScroll', 'true'],
  15780. ['tabRatio', '600'],
  15781. ['xWindow', '0'],
  15782. ['yWindow', '0']
  15783. ];*/
  15784. function push_defaults_array(target, defaults) {
  15785. for(var j = 0; j != target.length; ++j) { var w = target[j];
  15786. for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
  15787. if(w[z[0]] == null) w[z[0]] = z[1];
  15788. else switch(z[2]) {
  15789. case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
  15790. case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
  15791. }
  15792. }
  15793. }
  15794. }
  15795. function push_defaults(target, defaults) {
  15796. for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
  15797. if(target[z[0]] == null) target[z[0]] = z[1];
  15798. else switch(z[2]) {
  15799. case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
  15800. case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
  15801. }
  15802. }
  15803. }
  15804. function parse_wb_defaults(wb) {
  15805. push_defaults(wb.WBProps, WBPropsDef);
  15806. push_defaults(wb.CalcPr, CalcPrDef);
  15807. push_defaults_array(wb.WBView, WBViewDef);
  15808. push_defaults_array(wb.Sheets, SheetDef);
  15809. _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
  15810. }
  15811. function safe1904(wb) {
  15812. /* TODO: store date1904 somewhere else */
  15813. if(!wb.Workbook) return "false";
  15814. if(!wb.Workbook.WBProps) return "false";
  15815. return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
  15816. }
  15817. var badchars = ":][*?\/\\".split("");
  15818. function check_ws_name(n, safe) {
  15819. if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
  15820. var _good = true;
  15821. badchars.forEach(function(c) {
  15822. if(n.indexOf(c) == -1) return;
  15823. if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
  15824. _good = false;
  15825. });
  15826. return _good;
  15827. }
  15828. function check_wb_names(N, S, codes) {
  15829. N.forEach(function(n,i) {
  15830. check_ws_name(n);
  15831. for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
  15832. if(codes) {
  15833. var cn = (S && S[i] && S[i].CodeName) || n;
  15834. if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
  15835. }
  15836. });
  15837. }
  15838. function check_wb(wb) {
  15839. if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
  15840. if(!wb.SheetNames.length) throw new Error("Workbook is empty");
  15841. var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
  15842. check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
  15843. for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
  15844. wb.SheetNames.forEach(function(n, i) {
  15845. var ws = wb.Sheets[n];
  15846. if(!ws || !ws["!autofilter"]) return;
  15847. var DN;
  15848. if(!wb.Workbook) wb.Workbook = {};
  15849. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  15850. wb.Workbook.Names.forEach(function(dn) { if(dn.Name == "_xlnm._FilterDatabase" && dn.Sheet == i) DN = dn; });
  15851. var nn = formula_quote_sheet_name(n) + "!" + fix_range(ws["!autofilter"].ref);
  15852. if(DN) DN.Ref = nn;
  15853. else wb.Workbook.Names.push({Name: "_xlnm._FilterDatabase", Sheet: i, Ref: nn});
  15854. });
  15855. /* TODO: validate workbook */
  15856. }
  15857. /* 18.2 Workbook */
  15858. var wbnsregex = /<\w+:workbook/;
  15859. function parse_wb_xml(data, opts) {
  15860. if(!data) throw new Error("Could not find file");
  15861. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" };
  15862. var pass = false, xmlns = "xmlns";
  15863. var dname = {}, dnstart = 0;
  15864. data.replace(tagregex, function xml_wb(x, idx) {
  15865. var y = parsexmltag(x);
  15866. switch(strip_ns(y[0])) {
  15867. case '<?xml': break;
  15868. /* 18.2.27 workbook CT_Workbook 1 */
  15869. case '<workbook':
  15870. if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
  15871. wb.xmlns = y[xmlns];
  15872. break;
  15873. case '</workbook>': break;
  15874. /* 18.2.13 fileVersion CT_FileVersion ? */
  15875. case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
  15876. case '<fileVersion/>': case '</fileVersion>': break;
  15877. /* 18.2.12 fileSharing CT_FileSharing ? */
  15878. case '<fileSharing':
  15879. break;
  15880. case '<fileSharing/>': break;
  15881. /* 18.2.28 workbookPr CT_WorkbookPr ? */
  15882. case '<workbookPr':
  15883. case '<workbookPr/>':
  15884. WBPropsDef.forEach(function(w) {
  15885. if(y[w[0]] == null) return;
  15886. switch(w[2]) {
  15887. case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
  15888. case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
  15889. default: wb.WBProps[w[0]] = y[w[0]];
  15890. }
  15891. });
  15892. if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
  15893. break;
  15894. case '</workbookPr>': break;
  15895. /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
  15896. case '<workbookProtection':
  15897. break;
  15898. case '<workbookProtection/>': break;
  15899. /* 18.2.1 bookViews CT_BookViews ? */
  15900. case '<bookViews': case '<bookViews>': case '</bookViews>': break;
  15901. /* 18.2.30 workbookView CT_BookView + */
  15902. case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
  15903. case '</workbookView>': break;
  15904. /* 18.2.20 sheets CT_Sheets 1 */
  15905. case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
  15906. /* 18.2.19 sheet CT_Sheet + */
  15907. case '<sheet':
  15908. switch(y.state) {
  15909. case "hidden": y.Hidden = 1; break;
  15910. case "veryHidden": y.Hidden = 2; break;
  15911. default: y.Hidden = 0;
  15912. }
  15913. delete y.state;
  15914. y.name = unescapexml(utf8read(y.name));
  15915. delete y[0]; wb.Sheets.push(y); break;
  15916. case '</sheet>': break;
  15917. /* 18.2.15 functionGroups CT_FunctionGroups ? */
  15918. case '<functionGroups': case '<functionGroups/>': break;
  15919. /* 18.2.14 functionGroup CT_FunctionGroup + */
  15920. case '<functionGroup': break;
  15921. /* 18.2.9 externalReferences CT_ExternalReferences ? */
  15922. case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
  15923. /* 18.2.8 externalReference CT_ExternalReference + */
  15924. case '<externalReference': break;
  15925. /* 18.2.6 definedNames CT_DefinedNames ? */
  15926. case '<definedNames/>': break;
  15927. case '<definedNames>': case '<definedNames': pass=true; break;
  15928. case '</definedNames>': pass=false; break;
  15929. /* 18.2.5 definedName CT_DefinedName + */
  15930. case '<definedName': {
  15931. dname = {};
  15932. dname.Name = utf8read(y.name);
  15933. if(y.comment) dname.Comment = y.comment;
  15934. if(y.localSheetId) dname.Sheet = +y.localSheetId;
  15935. if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
  15936. dnstart = idx + x.length;
  15937. } break;
  15938. case '</definedName>': {
  15939. dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
  15940. wb.Names.push(dname);
  15941. } break;
  15942. case '<definedName/>': break;
  15943. /* 18.2.2 calcPr CT_CalcPr ? */
  15944. case '<calcPr': delete y[0]; wb.CalcPr = y; break;
  15945. case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
  15946. case '</calcPr>': break;
  15947. /* 18.2.16 oleSize CT_OleSize ? (ref required) */
  15948. case '<oleSize': break;
  15949. /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
  15950. case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
  15951. /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
  15952. case '<customWorkbookView': case '</customWorkbookView>': break;
  15953. /* 18.2.18 pivotCaches CT_PivotCaches ? */
  15954. case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
  15955. /* 18.2.17 pivotCache CT_PivotCache ? */
  15956. case '<pivotCache': break;
  15957. /* 18.2.21 smartTagPr CT_SmartTagPr ? */
  15958. case '<smartTagPr': case '<smartTagPr/>': break;
  15959. /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
  15960. case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
  15961. /* 18.2.22 smartTagType CT_SmartTagType ? */
  15962. case '<smartTagType': break;
  15963. /* 18.2.24 webPublishing CT_WebPublishing ? */
  15964. case '<webPublishing': case '<webPublishing/>': break;
  15965. /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
  15966. case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
  15967. /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
  15968. case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
  15969. /* 18.2.25 webPublishObject CT_WebPublishObject ? */
  15970. case '<webPublishObject': break;
  15971. /* 18.2.10 extLst CT_ExtensionList ? */
  15972. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  15973. /* 18.2.7 ext CT_Extension + */
  15974. case '<ext': pass=true; break; //TODO: check with versions of excel
  15975. case '</ext>': pass=false; break;
  15976. /* Others */
  15977. case '<ArchID': break;
  15978. case '<AlternateContent':
  15979. case '<AlternateContent>': pass=true; break;
  15980. case '</AlternateContent>': pass=false; break;
  15981. /* TODO */
  15982. case '<revisionPtr': break;
  15983. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
  15984. }
  15985. return x;
  15986. });
  15987. if(XMLNS_main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  15988. parse_wb_defaults(wb);
  15989. return wb;
  15990. }
  15991. function write_wb_xml(wb) {
  15992. var o = [XML_HEADER];
  15993. o[o.length] = writextag('workbook', null, {
  15994. 'xmlns': XMLNS_main[0],
  15995. //'xmlns:mx': XMLNS.mx,
  15996. //'xmlns:s': XMLNS_main[0],
  15997. 'xmlns:r': XMLNS.r
  15998. });
  15999. var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);
  16000. /* fileVersion */
  16001. /* fileSharing */
  16002. var workbookPr = ({codeName:"ThisWorkbook"});
  16003. if(wb.Workbook && wb.Workbook.WBProps) {
  16004. WBPropsDef.forEach(function(x) {
  16005. if((wb.Workbook.WBProps[x[0]]) == null) return;
  16006. if((wb.Workbook.WBProps[x[0]]) == x[1]) return;
  16007. workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]);
  16008. });
  16009. if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
  16010. }
  16011. o[o.length] = (writextag('workbookPr', null, workbookPr));
  16012. /* workbookProtection */
  16013. var sheets = wb.Workbook && wb.Workbook.Sheets || [];
  16014. var i = 0;
  16015. /* bookViews only written if first worksheet is hidden */
  16016. if(sheets && sheets[0] && !!sheets[0].Hidden) {
  16017. o[o.length] = "<bookViews>";
  16018. for(i = 0; i != wb.SheetNames.length; ++i) {
  16019. if(!sheets[i]) break;
  16020. if(!sheets[i].Hidden) break;
  16021. }
  16022. if(i == wb.SheetNames.length) i = 0;
  16023. o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
  16024. o[o.length] = "</bookViews>";
  16025. }
  16026. o[o.length] = "<sheets>";
  16027. for(i = 0; i != wb.SheetNames.length; ++i) {
  16028. var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))});
  16029. sht.sheetId = ""+(i+1);
  16030. sht["r:id"] = "rId"+(i+1);
  16031. if(sheets[i]) switch(sheets[i].Hidden) {
  16032. case 1: sht.state = "hidden"; break;
  16033. case 2: sht.state = "veryHidden"; break;
  16034. }
  16035. o[o.length] = (writextag('sheet',null,sht));
  16036. }
  16037. o[o.length] = "</sheets>";
  16038. /* functionGroups */
  16039. /* externalReferences */
  16040. if(write_names) {
  16041. o[o.length] = "<definedNames>";
  16042. if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
  16043. var d = {name:n.Name};
  16044. if(n.Comment) d.comment = n.Comment;
  16045. if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
  16046. if(n.Hidden) d.hidden = "1";
  16047. if(!n.Ref) return;
  16048. o[o.length] = writextag('definedName', escapexml(n.Ref), d);
  16049. });
  16050. o[o.length] = "</definedNames>";
  16051. }
  16052. /* calcPr */
  16053. /* oleSize */
  16054. /* customWorkbookViews */
  16055. /* pivotCaches */
  16056. /* smartTagPr */
  16057. /* smartTagTypes */
  16058. /* webPublishing */
  16059. /* fileRecoveryPr */
  16060. /* webPublishObjects */
  16061. /* extLst */
  16062. if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
  16063. return o.join("");
  16064. }
  16065. /* [MS-XLSB] 2.4.304 BrtBundleSh */
  16066. function parse_BrtBundleSh(data, length) {
  16067. var z = {};
  16068. z.Hidden = data.read_shift(4); //hsState ST_SheetState
  16069. z.iTabID = data.read_shift(4);
  16070. z.strRelID = parse_RelID(data,length-8);
  16071. z.name = parse_XLWideString(data);
  16072. return z;
  16073. }
  16074. function write_BrtBundleSh(data, o) {
  16075. if(!o) o = new_buf(127);
  16076. o.write_shift(4, data.Hidden);
  16077. o.write_shift(4, data.iTabID);
  16078. write_RelID(data.strRelID, o);
  16079. write_XLWideString(data.name.slice(0,31), o);
  16080. return o.length > o.l ? o.slice(0, o.l) : o;
  16081. }
  16082. /* [MS-XLSB] 2.4.815 BrtWbProp */
  16083. function parse_BrtWbProp(data, length) {
  16084. var o = ({});
  16085. var flags = data.read_shift(4);
  16086. o.defaultThemeVersion = data.read_shift(4);
  16087. var strName = (length > 8) ? parse_XLWideString(data) : "";
  16088. if(strName.length > 0) o.CodeName = strName;
  16089. o.autoCompressPictures = !!(flags & 0x10000);
  16090. o.backupFile = !!(flags & 0x40);
  16091. o.checkCompatibility = !!(flags & 0x1000);
  16092. o.date1904 = !!(flags & 0x01);
  16093. o.filterPrivacy = !!(flags & 0x08);
  16094. o.hidePivotFieldList = !!(flags & 0x400);
  16095. o.promptedSolutions = !!(flags & 0x10);
  16096. o.publishItems = !!(flags & 0x800);
  16097. o.refreshAllConnections = !!(flags & 0x40000);
  16098. o.saveExternalLinkValues = !!(flags & 0x80);
  16099. o.showBorderUnselectedTables = !!(flags & 0x04);
  16100. o.showInkAnnotation = !!(flags & 0x20);
  16101. o.showObjects = ["all", "placeholders", "none"][(flags >> 13) & 0x03];
  16102. o.showPivotChartFilter = !!(flags & 0x8000);
  16103. o.updateLinks = ["userSet", "never", "always"][(flags >> 8) & 0x03];
  16104. return o;
  16105. }
  16106. function write_BrtWbProp(data, o) {
  16107. if(!o) o = new_buf(72);
  16108. var flags = 0;
  16109. if(data) {
  16110. /* TODO: mirror parse_BrtWbProp fields */
  16111. if(data.date1904) flags |= 0x01;
  16112. if(data.filterPrivacy) flags |= 0x08;
  16113. }
  16114. o.write_shift(4, flags);
  16115. o.write_shift(4, 0);
  16116. write_XLSBCodeName(data && data.CodeName || "ThisWorkbook", o);
  16117. return o.slice(0, o.l);
  16118. }
  16119. function parse_BrtFRTArchID$(data, length) {
  16120. var o = {};
  16121. data.read_shift(4);
  16122. o.ArchID = data.read_shift(4);
  16123. data.l += length - 8;
  16124. return o;
  16125. }
  16126. /* [MS-XLSB] 2.4.687 BrtName */
  16127. function parse_BrtName(data, length, opts) {
  16128. var end = data.l + length;
  16129. var flags = data.read_shift(4);
  16130. data.l += 1; //var chKey = data.read_shift(1);
  16131. var itab = data.read_shift(4);
  16132. var name = parse_XLNameWideString(data);
  16133. var formula = parse_XLSBNameParsedFormula(data, 0, opts);
  16134. var comment = parse_XLNullableWideString(data);
  16135. if(flags & 0x20) name = "_xlnm." + name;
  16136. //if(0 /* fProc */) {
  16137. // unusedstring1: XLNullableWideString
  16138. // description: XLNullableWideString
  16139. // helpTopic: XLNullableWideString
  16140. // unusedstring2: XLNullableWideString
  16141. //}
  16142. data.l = end;
  16143. var out = ({Name:name, Ptg:formula, Flags: flags});
  16144. if(itab < 0xFFFFFFF) out.Sheet = itab;
  16145. if(comment) out.Comment = comment;
  16146. return out;
  16147. }
  16148. function write_BrtName(name, wb) {
  16149. var o = new_buf(9);
  16150. var flags = 0;
  16151. var dname = name.Name;
  16152. if(XLSLblBuiltIn.indexOf(dname) > -1) { flags |= 0x20; dname = dname.slice(6); }
  16153. o.write_shift(4, flags); // flags
  16154. o.write_shift(1, 0); // chKey
  16155. o.write_shift(4, name.Sheet == null ? 0xFFFFFFFF : name.Sheet);
  16156. var arr = [
  16157. o,
  16158. write_XLWideString(dname),
  16159. write_XLSBNameParsedFormula(name.Ref, wb)
  16160. ];
  16161. if(name.Comment) arr.push(write_XLNullableWideString(name.Comment));
  16162. else {
  16163. var x = new_buf(4);
  16164. x.write_shift(4, 0xFFFFFFFF);
  16165. arr.push(x);
  16166. }
  16167. // if macro (flags & 0x0F):
  16168. // write_shift(4, 0xFFFFFFFF);
  16169. // write_XLNullableWideString(description)
  16170. // write_XLNullableWideString(helpTopic)
  16171. // write_shift(4, 0xFFFFFFFF);
  16172. return bconcat(arr);
  16173. }
  16174. /* [MS-XLSB] 2.1.7.61 Workbook */
  16175. function parse_wb_bin(data, opts) {
  16176. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
  16177. var state = [];
  16178. var pass = false;
  16179. if(!opts) opts = {};
  16180. opts.biff = 12;
  16181. var Names = [];
  16182. var supbooks = ([[]]);
  16183. supbooks.SheetNames = [];
  16184. supbooks.XTI = [];
  16185. XLSBRecordEnum[0x0010] = { n:"BrtFRTArchID$", f:parse_BrtFRTArchID$ };
  16186. recordhopper(data, function hopper_wb(val, R, RT) {
  16187. switch(RT) {
  16188. case 0x009C: /* 'BrtBundleSh' */
  16189. supbooks.SheetNames.push(val.name);
  16190. wb.Sheets.push(val); break;
  16191. case 0x0099: /* 'BrtWbProp' */
  16192. wb.WBProps = val; break;
  16193. case 0x0027: /* 'BrtName' */
  16194. if(val.Sheet != null) opts.SID = val.Sheet;
  16195. val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
  16196. delete opts.SID;
  16197. delete val.Ptg;
  16198. Names.push(val);
  16199. break;
  16200. case 0x040C: /* 'BrtNameExt' */ break;
  16201. case 0x0165: /* 'BrtSupSelf' */
  16202. case 0x0166: /* 'BrtSupSame' */
  16203. case 0x0163: /* 'BrtSupBookSrc' */
  16204. case 0x029B: /* 'BrtSupAddin' */
  16205. if(!supbooks[0].length) supbooks[0] = [RT, val];
  16206. else supbooks.push([RT, val]);
  16207. supbooks[supbooks.length - 1].XTI = [];
  16208. break;
  16209. case 0x016A: /* 'BrtExternSheet' */
  16210. if(supbooks.length === 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  16211. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val);
  16212. supbooks.XTI = supbooks.XTI.concat(val);
  16213. break;
  16214. case 0x0169: /* 'BrtPlaceholderName' */
  16215. break;
  16216. case 0x0817: /* 'BrtAbsPath15' */
  16217. case 0x009E: /* 'BrtBookView' */
  16218. case 0x008F: /* 'BrtBeginBundleShs' */
  16219. case 0x0298: /* 'BrtBeginFnGroup' */
  16220. case 0x0161: /* 'BrtBeginExternals' */
  16221. break;
  16222. /* case 'BrtModelTimeGroupingCalcCol' */
  16223. case 0x0C00: /* 'BrtUid' */
  16224. case 0x0C01: /* 'BrtRevisionPtr' */
  16225. case 0x0216: /* 'BrtBookProtection' */
  16226. case 0x02A5: /* 'BrtBookProtectionIso' */
  16227. case 0x009D: /* 'BrtCalcProp' */
  16228. case 0x0262: /* 'BrtCrashRecErr' */
  16229. case 0x0802: /* 'BrtDecoupledPivotCacheID' */
  16230. case 0x009B: /* 'BrtFileRecover' */
  16231. case 0x0224: /* 'BrtFileSharing' */
  16232. case 0x02A4: /* 'BrtFileSharingIso' */
  16233. case 0x0080: /* 'BrtFileVersion' */
  16234. case 0x0299: /* 'BrtFnGroup' */
  16235. case 0x0850: /* 'BrtModelRelationship' */
  16236. case 0x084D: /* 'BrtModelTable' */
  16237. case 0x0225: /* 'BrtOleSize' */
  16238. case 0x0805: /* 'BrtPivotTableRef' */
  16239. case 0x0254: /* 'BrtSmartTagType' */
  16240. case 0x081C: /* 'BrtTableSlicerCacheID' */
  16241. case 0x081B: /* 'BrtTableSlicerCacheIDs' */
  16242. case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
  16243. case 0x018D: /* 'BrtUserBookView' */
  16244. case 0x009A: /* 'BrtWbFactoid' */
  16245. case 0x045D: /* 'BrtWbProp14' */
  16246. case 0x0229: /* 'BrtWebOpt' */
  16247. case 0x082B: /* 'BrtWorkBookPr15' */
  16248. break;
  16249. case 0x0023: /* 'BrtFRTBegin' */
  16250. state.push(RT); pass = true; break;
  16251. case 0x0024: /* 'BrtFRTEnd' */
  16252. state.pop(); pass = false; break;
  16253. case 0x0025: /* 'BrtACBegin' */
  16254. state.push(RT); pass = true; break;
  16255. case 0x0026: /* 'BrtACEnd' */
  16256. state.pop(); pass = false; break;
  16257. case 0x0010: /* 'BrtFRTArchID$' */ break;
  16258. default:
  16259. if(R.T){/* empty */}
  16260. else if(!pass || (opts.WTF && state[state.length-1] != 0x0025 /* BrtACBegin */ && state[state.length-1] != 0x0023 /* BrtFRTBegin */)) throw new Error("Unexpected record 0x" + RT.toString(16));
  16261. }
  16262. }, opts);
  16263. parse_wb_defaults(wb);
  16264. // $FlowIgnore
  16265. wb.Names = Names;
  16266. (wb).supbooks = supbooks;
  16267. return wb;
  16268. }
  16269. function write_BUNDLESHS(ba, wb) {
  16270. write_record(ba, 0x008F /* BrtBeginBundleShs */);
  16271. for(var idx = 0; idx != wb.SheetNames.length; ++idx) {
  16272. var viz = wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx] && wb.Workbook.Sheets[idx].Hidden || 0;
  16273. var d = { Hidden: viz, iTabID: idx+1, strRelID: 'rId' + (idx+1), name: wb.SheetNames[idx] };
  16274. write_record(ba, 0x009C /* BrtBundleSh */, write_BrtBundleSh(d));
  16275. }
  16276. write_record(ba, 0x0090 /* BrtEndBundleShs */);
  16277. }
  16278. /* [MS-XLSB] 2.4.649 BrtFileVersion */
  16279. function write_BrtFileVersion(data, o) {
  16280. if(!o) o = new_buf(127);
  16281. for(var i = 0; i != 4; ++i) o.write_shift(4, 0);
  16282. write_XLWideString("SheetJS", o);
  16283. write_XLWideString(XLSX.version, o);
  16284. write_XLWideString(XLSX.version, o);
  16285. write_XLWideString("7262", o);
  16286. return o.length > o.l ? o.slice(0, o.l) : o;
  16287. }
  16288. /* [MS-XLSB] 2.4.301 BrtBookView */
  16289. function write_BrtBookView(idx, o) {
  16290. if(!o) o = new_buf(29);
  16291. o.write_shift(-4, 0);
  16292. o.write_shift(-4, 460);
  16293. o.write_shift(4, 28800);
  16294. o.write_shift(4, 17600);
  16295. o.write_shift(4, 500);
  16296. o.write_shift(4, idx);
  16297. o.write_shift(4, idx);
  16298. var flags = 0x78;
  16299. o.write_shift(1, flags);
  16300. return o.length > o.l ? o.slice(0, o.l) : o;
  16301. }
  16302. function write_BOOKVIEWS(ba, wb) {
  16303. /* required if hidden tab appears before visible tab */
  16304. if(!wb.Workbook || !wb.Workbook.Sheets) return;
  16305. var sheets = wb.Workbook.Sheets;
  16306. var i = 0, vistab = -1, hidden = -1;
  16307. for(; i < sheets.length; ++i) {
  16308. if(!sheets[i] || !sheets[i].Hidden && vistab == -1) vistab = i;
  16309. else if(sheets[i].Hidden == 1 && hidden == -1) hidden = i;
  16310. }
  16311. if(hidden > vistab) return;
  16312. write_record(ba, 0x0087 /* BrtBeginBookViews */);
  16313. write_record(ba, 0x009E /* BrtBookView */, write_BrtBookView(vistab));
  16314. /* 1*(BrtBookView *FRT) */
  16315. write_record(ba, 0x0088 /* BrtEndBookViews */);
  16316. }
  16317. function write_BRTNAMES(ba, wb) {
  16318. if(!wb.Workbook || !wb.Workbook.Names) return;
  16319. wb.Workbook.Names.forEach(function(name) { try {
  16320. if(name.Flags & 0x0e) return; // TODO: macro name write
  16321. write_record(ba, 0x0027 /* BrtName */, write_BrtName(name, wb));
  16322. } catch(e) {
  16323. console.error("Could not serialize defined name " + JSON.stringify(name));
  16324. } });
  16325. }
  16326. function write_SELF_EXTERNS_xlsb(wb) {
  16327. var L = wb.SheetNames.length;
  16328. var o = new_buf(12 * L + 28);
  16329. o.write_shift(4, L + 2);
  16330. o.write_shift(4, 0); o.write_shift(4, -2); o.write_shift(4, -2); // workbook-level reference
  16331. o.write_shift(4, 0); o.write_shift(4, -1); o.write_shift(4, -1); // #REF!...
  16332. for(var i = 0; i < L; ++i) {
  16333. o.write_shift(4, 0); o.write_shift(4, i); o.write_shift(4, i);
  16334. }
  16335. return o;
  16336. }
  16337. function write_EXTERNALS_xlsb(ba, wb) {
  16338. write_record(ba, 0x0161 /* BrtBeginExternals */);
  16339. write_record(ba, 0x0165 /* BrtSupSelf */);
  16340. write_record(ba, 0x016A /* BrtExternSheet */, write_SELF_EXTERNS_xlsb(wb, 0));
  16341. write_record(ba, 0x0162 /* BrtEndExternals */);
  16342. }
  16343. /* [MS-XLSB] 2.4.305 BrtCalcProp */
  16344. /*function write_BrtCalcProp(data, o) {
  16345. if(!o) o = new_buf(26);
  16346. o.write_shift(4,0); // force recalc
  16347. o.write_shift(4,1);
  16348. o.write_shift(4,0);
  16349. write_Xnum(0, o);
  16350. o.write_shift(-4, 1023);
  16351. o.write_shift(1, 0x33);
  16352. o.write_shift(1, 0x00);
  16353. return o;
  16354. }*/
  16355. /* [MS-XLSB] 2.4.646 BrtFileRecover */
  16356. /*function write_BrtFileRecover(data, o) {
  16357. if(!o) o = new_buf(1);
  16358. o.write_shift(1,0);
  16359. return o;
  16360. }*/
  16361. /* [MS-XLSB] 2.1.7.61 Workbook */
  16362. function write_wb_bin(wb, opts) {
  16363. var ba = buf_array();
  16364. write_record(ba, 0x0083 /* BrtBeginBook */);
  16365. write_record(ba, 0x0080 /* BrtFileVersion */, write_BrtFileVersion());
  16366. /* [[BrtFileSharingIso] BrtFileSharing] */
  16367. write_record(ba, 0x0099 /* BrtWbProp */, write_BrtWbProp(wb.Workbook && wb.Workbook.WBProps || null));
  16368. /* [ACABSPATH] */
  16369. /* [[BrtBookProtectionIso] BrtBookProtection] */
  16370. write_BOOKVIEWS(ba, wb, opts);
  16371. write_BUNDLESHS(ba, wb, opts);
  16372. /* [FNGROUP] */
  16373. write_EXTERNALS_xlsb(ba, wb);
  16374. if((wb.Workbook||{}).Names) write_BRTNAMES(ba, wb);
  16375. /* write_record(ba, 0x009D BrtCalcProp, write_BrtCalcProp()); */
  16376. /* [BrtOleSize] */
  16377. /* *(BrtUserBookView *FRT) */
  16378. /* [PIVOTCACHEIDS] */
  16379. /* [BrtWbFactoid] */
  16380. /* [SMARTTAGTYPES] */
  16381. /* [BrtWebOpt] */
  16382. /* write_record(ba, 0x009B BrtFileRecover, write_BrtFileRecover()); */
  16383. /* [WEBPUBITEMS] */
  16384. /* [CRERRS] */
  16385. /* FRTWORKBOOK */
  16386. write_record(ba, 0x0084 /* BrtEndBook */);
  16387. return ba.end();
  16388. }
  16389. function parse_wb(data, name, opts) {
  16390. if(name.slice(-4)===".bin") return parse_wb_bin((data), opts);
  16391. return parse_wb_xml((data), opts);
  16392. }
  16393. function parse_ws(data, name, idx, opts, rels, wb, themes, styles) {
  16394. if(name.slice(-4)===".bin") return parse_ws_bin((data), opts, idx, rels, wb, themes, styles);
  16395. return parse_ws_xml((data), opts, idx, rels, wb, themes, styles);
  16396. }
  16397. function parse_cs(data, name, idx, opts, rels, wb, themes, styles) {
  16398. if(name.slice(-4)===".bin") return parse_cs_bin((data), opts, idx, rels, wb, themes, styles);
  16399. return parse_cs_xml((data), opts, idx, rels, wb, themes, styles);
  16400. }
  16401. function parse_ms(data, name, idx, opts, rels, wb, themes, styles) {
  16402. if(name.slice(-4)===".bin") return parse_ms_bin((data), opts, idx, rels, wb, themes, styles);
  16403. return parse_ms_xml((data), opts, idx, rels, wb, themes, styles);
  16404. }
  16405. function parse_ds(data, name, idx, opts, rels, wb, themes, styles) {
  16406. if(name.slice(-4)===".bin") return parse_ds_bin((data), opts, idx, rels, wb, themes, styles);
  16407. return parse_ds_xml((data), opts, idx, rels, wb, themes, styles);
  16408. }
  16409. function parse_sty(data, name, themes, opts) {
  16410. if(name.slice(-4)===".bin") return parse_sty_bin((data), themes, opts);
  16411. return parse_sty_xml((data), themes, opts);
  16412. }
  16413. function parse_sst(data, name, opts) {
  16414. if(name.slice(-4)===".bin") return parse_sst_bin((data), opts);
  16415. return parse_sst_xml((data), opts);
  16416. }
  16417. function parse_cmnt(data, name, opts) {
  16418. if(name.slice(-4)===".bin") return parse_comments_bin((data), opts);
  16419. return parse_comments_xml((data), opts);
  16420. }
  16421. function parse_cc(data, name, opts) {
  16422. if(name.slice(-4)===".bin") return parse_cc_bin((data), name, opts);
  16423. return parse_cc_xml((data), name, opts);
  16424. }
  16425. function parse_xlink(data, rel, name, opts) {
  16426. if(name.slice(-4)===".bin") return parse_xlink_bin((data), rel, name, opts);
  16427. return parse_xlink_xml((data), rel, name, opts);
  16428. }
  16429. function parse_xlmeta(data, name, opts) {
  16430. if(name.slice(-4)===".bin") return parse_xlmeta_bin((data), name, opts);
  16431. return parse_xlmeta_xml((data), name, opts);
  16432. }
  16433. var attregexg2=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
  16434. var attregex2=/([\w:]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
  16435. function xlml_parsexmltag(tag, skip_root) {
  16436. var words = tag.split(/\s+/);
  16437. var z = ([]); if(!skip_root) z[0] = words[0];
  16438. if(words.length === 1) return z;
  16439. var m = tag.match(attregexg2), y, j, w, i;
  16440. if(m) for(i = 0; i != m.length; ++i) {
  16441. y = m[i].match(attregex2);
  16442. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  16443. else {
  16444. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  16445. else w = y[1].slice(j+1);
  16446. z[w] = y[2].slice(1,y[2].length-1);
  16447. }
  16448. }
  16449. return z;
  16450. }
  16451. function xlml_parsexmltagobj(tag) {
  16452. var words = tag.split(/\s+/);
  16453. var z = {};
  16454. if(words.length === 1) return z;
  16455. var m = tag.match(attregexg2), y, j, w, i;
  16456. if(m) for(i = 0; i != m.length; ++i) {
  16457. y = m[i].match(attregex2);
  16458. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  16459. else {
  16460. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  16461. else w = y[1].slice(j+1);
  16462. z[w] = y[2].slice(1,y[2].length-1);
  16463. }
  16464. }
  16465. return z;
  16466. }
  16467. // ----
  16468. /* map from xlml named formats to SSF TODO: localize */
  16469. var XLMLFormatMap;
  16470. function xlml_format(format, value) {
  16471. var fmt = XLMLFormatMap[format] || unescapexml(format);
  16472. if(fmt === "General") return SSF_general(value);
  16473. return SSF_format(fmt, value);
  16474. }
  16475. function xlml_set_custprop(Custprops, key, cp, val) {
  16476. var oval = val;
  16477. switch((cp[0].match(/dt:dt="([\w.]+)"/)||["",""])[1]) {
  16478. case "boolean": oval = parsexmlbool(val); break;
  16479. case "i2": case "int": oval = parseInt(val, 10); break;
  16480. case "r4": case "float": oval = parseFloat(val); break;
  16481. case "date": case "dateTime.tz": oval = parseDate(val); break;
  16482. case "i8": case "string": case "fixed": case "uuid": case "bin.base64": break;
  16483. default: throw new Error("bad custprop:" + cp[0]);
  16484. }
  16485. Custprops[unescapexml(key)] = oval;
  16486. }
  16487. function safe_format_xlml(cell, nf, o) {
  16488. if(cell.t === 'z') return;
  16489. if(!o || o.cellText !== false) try {
  16490. if(cell.t === 'e') { cell.w = cell.w || BErr[cell.v]; }
  16491. else if(nf === "General") {
  16492. if(cell.t === 'n') {
  16493. if((cell.v|0) === cell.v) cell.w = cell.v.toString(10);
  16494. else cell.w = SSF_general_num(cell.v);
  16495. }
  16496. else cell.w = SSF_general(cell.v);
  16497. }
  16498. else cell.w = xlml_format(nf||"General", cell.v);
  16499. } catch(e) { if(o.WTF) throw e; }
  16500. try {
  16501. var z = XLMLFormatMap[nf]||nf||"General";
  16502. if(o.cellNF) cell.z = z;
  16503. if(o.cellDates && cell.t == 'n' && fmt_is_date(z)) {
  16504. var _d = SSF_parse_date_code(cell.v); if(_d) { cell.t = 'd'; cell.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  16505. }
  16506. } catch(e) { if(o.WTF) throw e; }
  16507. }
  16508. function process_style_xlml(styles, stag, opts) {
  16509. if(opts.cellStyles) {
  16510. if(stag.Interior) {
  16511. var I = stag.Interior;
  16512. if(I.Pattern) I.patternType = XLMLPatternTypeMap[I.Pattern] || I.Pattern;
  16513. }
  16514. }
  16515. styles[stag.ID] = stag;
  16516. }
  16517. /* TODO: there must exist some form of OSP-blessed spec */
  16518. function parse_xlml_data(xml, ss, data, cell, base, styles, csty, row, arrayf, o) {
  16519. var nf = "General", sid = cell.StyleID, S = {}; o = o || {};
  16520. var interiors = [];
  16521. var i = 0;
  16522. if(sid === undefined && row) sid = row.StyleID;
  16523. if(sid === undefined && csty) sid = csty.StyleID;
  16524. while(styles[sid] !== undefined) {
  16525. if(styles[sid].nf) nf = styles[sid].nf;
  16526. if(styles[sid].Interior) interiors.push(styles[sid].Interior);
  16527. if(!styles[sid].Parent) break;
  16528. sid = styles[sid].Parent;
  16529. }
  16530. switch(data.Type) {
  16531. case 'Boolean':
  16532. cell.t = 'b';
  16533. cell.v = parsexmlbool(xml);
  16534. break;
  16535. case 'String':
  16536. cell.t = 's'; cell.r = xlml_fixstr(unescapexml(xml));
  16537. cell.v = (xml.indexOf("<") > -1 ? unescapexml(ss||xml).replace(/<.*?>/g, "") : cell.r); // todo: BR etc
  16538. break;
  16539. case 'DateTime':
  16540. if(xml.slice(-1) != "Z") xml += "Z";
  16541. cell.v = (parseDate(xml) - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  16542. if(cell.v !== cell.v) cell.v = unescapexml(xml);
  16543. else if(cell.v<60) cell.v = cell.v -1;
  16544. if(!nf || nf == "General") nf = "yyyy-mm-dd";
  16545. /* falls through */
  16546. case 'Number':
  16547. if(cell.v === undefined) cell.v=+xml;
  16548. if(!cell.t) cell.t = 'n';
  16549. break;
  16550. case 'Error': cell.t = 'e'; cell.v = RBErr[xml]; if(o.cellText !== false) cell.w = xml; break;
  16551. default:
  16552. if(xml == "" && ss == "") { cell.t = 'z'; }
  16553. else { cell.t = 's'; cell.v = xlml_fixstr(ss||xml); }
  16554. break;
  16555. }
  16556. safe_format_xlml(cell, nf, o);
  16557. if(o.cellFormula !== false) {
  16558. if(cell.Formula) {
  16559. var fstr = unescapexml(cell.Formula);
  16560. /* strictly speaking, the leading = is required but some writers omit */
  16561. if(fstr.charCodeAt(0) == 61 /* = */) fstr = fstr.slice(1);
  16562. cell.f = rc_to_a1(fstr, base);
  16563. delete cell.Formula;
  16564. if(cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
  16565. else if(cell.ArrayRange) {
  16566. cell.F = rc_to_a1(cell.ArrayRange, base);
  16567. arrayf.push([safe_decode_range(cell.F), cell.F]);
  16568. }
  16569. } else {
  16570. for(i = 0; i < arrayf.length; ++i)
  16571. if(base.r >= arrayf[i][0].s.r && base.r <= arrayf[i][0].e.r)
  16572. if(base.c >= arrayf[i][0].s.c && base.c <= arrayf[i][0].e.c)
  16573. cell.F = arrayf[i][1];
  16574. }
  16575. }
  16576. if(o.cellStyles) {
  16577. interiors.forEach(function(x) {
  16578. if(!S.patternType && x.patternType) S.patternType = x.patternType;
  16579. });
  16580. cell.s = S;
  16581. }
  16582. if(cell.StyleID !== undefined) cell.ixfe = cell.StyleID;
  16583. }
  16584. function xlml_prefix_dname(dname) {
  16585. return XLSLblBuiltIn.indexOf("_xlnm." + dname) > -1 ? "_xlnm." + dname : dname;
  16586. }
  16587. function xlml_clean_comment(comment) {
  16588. comment.t = comment.v || "";
  16589. comment.t = comment.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  16590. comment.v = comment.w = comment.ixfe = undefined;
  16591. }
  16592. /* TODO: Everything */
  16593. function parse_xlml_xml(d, _opts) {
  16594. var opts = _opts || {};
  16595. make_ssf();
  16596. var str = debom(xlml_normalize(d));
  16597. if(opts.type == 'binary' || opts.type == 'array' || opts.type == 'base64') {
  16598. if(typeof $cptable !== 'undefined') str = $cptable.utils.decode(65001, char_codes(str));
  16599. else str = utf8read(str);
  16600. }
  16601. var opening = str.slice(0, 1024).toLowerCase(), ishtml = false;
  16602. opening = opening.replace(/".*?"/g, "");
  16603. if((opening.indexOf(">") & 1023) > Math.min((opening.indexOf(",") & 1023), (opening.indexOf(";")&1023))) { var _o = dup(opts); _o.type = "string"; return PRN.to_workbook(str, _o); }
  16604. if(opening.indexOf("<?xml") == -1) ["html", "table", "head", "meta", "script", "style", "div"].forEach(function(tag) { if(opening.indexOf("<" + tag) >= 0) ishtml = true; });
  16605. if(ishtml) return html_to_workbook(str, opts);
  16606. XLMLFormatMap = ({
  16607. "General Number": "General",
  16608. "General Date": table_fmt[22],
  16609. "Long Date": "dddd, mmmm dd, yyyy",
  16610. "Medium Date": table_fmt[15],
  16611. "Short Date": table_fmt[14],
  16612. "Long Time": table_fmt[19],
  16613. "Medium Time": table_fmt[18],
  16614. "Short Time": table_fmt[20],
  16615. "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  16616. "Fixed": table_fmt[2],
  16617. "Standard": table_fmt[4],
  16618. "Percent": table_fmt[10],
  16619. "Scientific": table_fmt[11],
  16620. "Yes/No": '"Yes";"Yes";"No";@',
  16621. "True/False": '"True";"True";"False";@',
  16622. "On/Off": '"Yes";"Yes";"No";@'
  16623. });
  16624. var Rn;
  16625. var state = [], tmp;
  16626. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  16627. var sheets = {}, sheetnames = [], cursheet = (opts.dense ? [] : {}), sheetname = "";
  16628. var cell = ({}), row = {};// eslint-disable-line no-unused-vars
  16629. var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
  16630. var c = 0, r = 0;
  16631. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  16632. var styles = {}, stag = {};
  16633. var ss = "", fidx = 0;
  16634. var merges = [];
  16635. var Props = {}, Custprops = {}, pidx = 0, cp = [];
  16636. var comments = [], comment = ({});
  16637. var cstys = [], csty, seencol = false;
  16638. var arrayf = [];
  16639. var rowinfo = [], rowobj = {}, cc = 0, rr = 0;
  16640. var Workbook = ({ Sheets:[], WBProps:{date1904:false} }), wsprops = {};
  16641. xlmlregex.lastIndex = 0;
  16642. str = str.replace(/<!--([\s\S]*?)-->/mg,"");
  16643. var raw_Rn3 = "";
  16644. while((Rn = xlmlregex.exec(str))) switch((Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase())) {
  16645. case 'data' /*case 'Data'*/:
  16646. if(raw_Rn3 == "data") {
  16647. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16648. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  16649. break;
  16650. }
  16651. if(state[state.length-1][1]) break;
  16652. if(Rn[1]==='/') parse_xlml_data(str.slice(didx, Rn.index), ss, dtag, state[state.length-1][0]==/*"Comment"*/"comment"?comment:cell, {c:c,r:r}, styles, cstys[c], row, arrayf, opts);
  16653. else { ss = ""; dtag = xlml_parsexmltag(Rn[0]); didx = Rn.index + Rn[0].length; }
  16654. break;
  16655. case 'cell' /*case 'Cell'*/:
  16656. if(Rn[1]==='/'){
  16657. if(comments.length > 0) cell.c = comments;
  16658. if((!opts.sheetRows || opts.sheetRows > r) && cell.v !== void 0) {
  16659. if(opts.dense) {
  16660. if(!cursheet[r]) cursheet[r] = [];
  16661. cursheet[r][c] = cell;
  16662. } else cursheet[encode_col(c) + encode_row(r)] = cell;
  16663. }
  16664. if(cell.HRef) {
  16665. cell.l = ({Target:unescapexml(cell.HRef)});
  16666. if(cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
  16667. delete cell.HRef; delete cell.HRefScreenTip;
  16668. }
  16669. if(cell.MergeAcross || cell.MergeDown) {
  16670. cc = c + (parseInt(cell.MergeAcross,10)|0);
  16671. rr = r + (parseInt(cell.MergeDown,10)|0);
  16672. if(cc > c || rr > r) merges.push({s:{c:c,r:r},e:{c:cc,r:rr}});
  16673. }
  16674. if(!opts.sheetStubs) { if(cell.MergeAcross) c = cc + 1; else ++c; }
  16675. else if(cell.MergeAcross || cell.MergeDown) {
  16676. for(var cma = c; cma <= cc; ++cma) {
  16677. for(var cmd = r; cmd <= rr; ++cmd) {
  16678. if(cma > c || cmd > r) {
  16679. if(opts.dense) {
  16680. if(!cursheet[cmd]) cursheet[cmd] = [];
  16681. cursheet[cmd][cma] = {t:'z'};
  16682. } else cursheet[encode_col(cma) + encode_row(cmd)] = {t:'z'};
  16683. }
  16684. }
  16685. }
  16686. c = cc + 1;
  16687. }
  16688. else ++c;
  16689. } else {
  16690. cell = xlml_parsexmltagobj(Rn[0]);
  16691. if(cell.Index) c = +cell.Index - 1;
  16692. if(c < refguess.s.c) refguess.s.c = c;
  16693. if(c > refguess.e.c) refguess.e.c = c;
  16694. if(Rn[0].slice(-2) === "/>") ++c;
  16695. comments = [];
  16696. }
  16697. break;
  16698. case 'row' /*case 'Row'*/:
  16699. if(Rn[1]==='/' || Rn[0].slice(-2) === "/>") {
  16700. if(r < refguess.s.r) refguess.s.r = r;
  16701. if(r > refguess.e.r) refguess.e.r = r;
  16702. if(Rn[0].slice(-2) === "/>") {
  16703. row = xlml_parsexmltag(Rn[0]);
  16704. if(row.Index) r = +row.Index - 1;
  16705. }
  16706. c = 0; ++r;
  16707. } else {
  16708. row = xlml_parsexmltag(Rn[0]);
  16709. if(row.Index) r = +row.Index - 1;
  16710. rowobj = {};
  16711. if(row.AutoFitHeight == "0" || row.Height) {
  16712. rowobj.hpx = parseInt(row.Height, 10); rowobj.hpt = px2pt(rowobj.hpx);
  16713. rowinfo[r] = rowobj;
  16714. }
  16715. if(row.Hidden == "1") { rowobj.hidden = true; rowinfo[r] = rowobj; }
  16716. }
  16717. break;
  16718. case 'worksheet' /*case 'Worksheet'*/: /* TODO: read range from FullRows/FullColumns */
  16719. if(Rn[1]==='/'){
  16720. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  16721. sheetnames.push(sheetname);
  16722. if(refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
  16723. cursheet["!ref"] = encode_range(refguess);
  16724. if(opts.sheetRows && opts.sheetRows <= refguess.e.r) {
  16725. cursheet["!fullref"] = cursheet["!ref"];
  16726. refguess.e.r = opts.sheetRows - 1;
  16727. cursheet["!ref"] = encode_range(refguess);
  16728. }
  16729. }
  16730. if(merges.length) cursheet["!merges"] = merges;
  16731. if(cstys.length > 0) cursheet["!cols"] = cstys;
  16732. if(rowinfo.length > 0) cursheet["!rows"] = rowinfo;
  16733. sheets[sheetname] = cursheet;
  16734. } else {
  16735. refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  16736. r = c = 0;
  16737. state.push([Rn[3], false]);
  16738. tmp = xlml_parsexmltag(Rn[0]);
  16739. sheetname = unescapexml(tmp.Name);
  16740. cursheet = (opts.dense ? [] : {});
  16741. merges = [];
  16742. arrayf = [];
  16743. rowinfo = [];
  16744. wsprops = {name:sheetname, Hidden:0};
  16745. Workbook.Sheets.push(wsprops);
  16746. }
  16747. break;
  16748. case 'table' /*case 'Table'*/:
  16749. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16750. else if(Rn[0].slice(-2) == "/>") break;
  16751. else {
  16752. state.push([Rn[3], false]);
  16753. cstys = []; seencol = false;
  16754. }
  16755. break;
  16756. case 'style' /*case 'Style'*/:
  16757. if(Rn[1]==='/') process_style_xlml(styles, stag, opts);
  16758. else stag = xlml_parsexmltag(Rn[0]);
  16759. break;
  16760. case 'numberformat' /*case 'NumberFormat'*/:
  16761. stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
  16762. if(XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
  16763. for(var ssfidx = 0; ssfidx != 0x188; ++ssfidx) if(table_fmt[ssfidx] == stag.nf) break;
  16764. if(ssfidx == 0x188) for(ssfidx = 0x39; ssfidx != 0x188; ++ssfidx) if(table_fmt[ssfidx] == null) { SSF__load(stag.nf, ssfidx); break; }
  16765. break;
  16766. case 'column' /*case 'Column'*/:
  16767. if(state[state.length-1][0] !== /*'Table'*/'table') break;
  16768. if(Rn[1]==='/') break;
  16769. csty = xlml_parsexmltag(Rn[0]);
  16770. if(csty.Hidden) { csty.hidden = true; delete csty.Hidden; }
  16771. if(csty.Width) csty.wpx = parseInt(csty.Width, 10);
  16772. if(!seencol && csty.wpx > 10) {
  16773. seencol = true; MDW = DEF_MDW; //find_mdw_wpx(csty.wpx);
  16774. for(var _col = 0; _col < cstys.length; ++_col) if(cstys[_col]) process_col(cstys[_col]);
  16775. }
  16776. if(seencol) process_col(csty);
  16777. cstys[(csty.Index-1||cstys.length)] = csty;
  16778. for(var i = 0; i < +csty.Span; ++i) cstys[cstys.length] = dup(csty);
  16779. break;
  16780. case 'namedrange' /*case 'NamedRange'*/:
  16781. if(Rn[1]==='/') break;
  16782. if(!Workbook.Names) Workbook.Names = [];
  16783. var _NamedRange = parsexmltag(Rn[0]);
  16784. var _DefinedName = ({
  16785. Name: xlml_prefix_dname(_NamedRange.Name),
  16786. Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), {r:0, c:0})
  16787. });
  16788. if(Workbook.Sheets.length>0) _DefinedName.Sheet=Workbook.Sheets.length-1;
  16789. Workbook.Names.push(_DefinedName);
  16790. break;
  16791. case 'namedcell' /*case 'NamedCell'*/: break;
  16792. case 'b' /*case 'B'*/: break;
  16793. case 'i' /*case 'I'*/: break;
  16794. case 'u' /*case 'U'*/: break;
  16795. case 's' /*case 'S'*/: break;
  16796. case 'em' /*case 'EM'*/: break;
  16797. case 'h2' /*case 'H2'*/: break;
  16798. case 'h3' /*case 'H3'*/: break;
  16799. case 'sub' /*case 'Sub'*/: break;
  16800. case 'sup' /*case 'Sup'*/: break;
  16801. case 'span' /*case 'Span'*/: break;
  16802. case 'alignment' /*case 'Alignment'*/:
  16803. break;
  16804. case 'borders' /*case 'Borders'*/: break;
  16805. case 'border' /*case 'Border'*/: break;
  16806. case 'font' /*case 'Font'*/:
  16807. if(Rn[0].slice(-2) === "/>") break;
  16808. else if(Rn[1]==="/") ss += str.slice(fidx, Rn.index);
  16809. else fidx = Rn.index + Rn[0].length;
  16810. break;
  16811. case 'interior' /*case 'Interior'*/:
  16812. if(!opts.cellStyles) break;
  16813. stag.Interior = xlml_parsexmltag(Rn[0]);
  16814. break;
  16815. case 'protection' /*case 'Protection'*/: break;
  16816. case 'author' /*case 'Author'*/:
  16817. case 'title' /*case 'Title'*/:
  16818. case 'description' /*case 'Description'*/:
  16819. case 'created' /*case 'Created'*/:
  16820. case 'keywords' /*case 'Keywords'*/:
  16821. case 'subject' /*case 'Subject'*/:
  16822. case 'category' /*case 'Category'*/:
  16823. case 'company' /*case 'Company'*/:
  16824. case 'lastauthor' /*case 'LastAuthor'*/:
  16825. case 'lastsaved' /*case 'LastSaved'*/:
  16826. case 'lastprinted' /*case 'LastPrinted'*/:
  16827. case 'version' /*case 'Version'*/:
  16828. case 'revision' /*case 'Revision'*/:
  16829. case 'totaltime' /*case 'TotalTime'*/:
  16830. case 'hyperlinkbase' /*case 'HyperlinkBase'*/:
  16831. case 'manager' /*case 'Manager'*/:
  16832. case 'contentstatus' /*case 'ContentStatus'*/:
  16833. case 'identifier' /*case 'Identifier'*/:
  16834. case 'language' /*case 'Language'*/:
  16835. case 'appname' /*case 'AppName'*/:
  16836. if(Rn[0].slice(-2) === "/>") break;
  16837. else if(Rn[1]==="/") xlml_set_prop(Props, raw_Rn3, str.slice(pidx, Rn.index));
  16838. else pidx = Rn.index + Rn[0].length;
  16839. break;
  16840. case 'paragraphs' /*case 'Paragraphs'*/: break;
  16841. case 'styles' /*case 'Styles'*/:
  16842. case 'workbook' /*case 'Workbook'*/:
  16843. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16844. else state.push([Rn[3], false]);
  16845. break;
  16846. case 'comment' /*case 'Comment'*/:
  16847. if(Rn[1]==='/'){
  16848. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  16849. xlml_clean_comment(comment);
  16850. comments.push(comment);
  16851. } else {
  16852. state.push([Rn[3], false]);
  16853. tmp = xlml_parsexmltag(Rn[0]);
  16854. comment = ({a:tmp.Author});
  16855. }
  16856. break;
  16857. case 'autofilter' /*case 'AutoFilter'*/:
  16858. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16859. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  16860. var AutoFilter = xlml_parsexmltag(Rn[0]);
  16861. cursheet['!autofilter'] = { ref:rc_to_a1(AutoFilter.Range).replace(/\$/g,"") };
  16862. state.push([Rn[3], true]);
  16863. }
  16864. break;
  16865. case 'name' /*case 'Name'*/: break;
  16866. case 'datavalidation' /*case 'DataValidation'*/:
  16867. if(Rn[1]==='/'){
  16868. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  16869. } else {
  16870. if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  16871. }
  16872. break;
  16873. case 'pixelsperinch' /*case 'PixelsPerInch'*/:
  16874. break;
  16875. case 'componentoptions' /*case 'ComponentOptions'*/:
  16876. case 'documentproperties' /*case 'DocumentProperties'*/:
  16877. case 'customdocumentproperties' /*case 'CustomDocumentProperties'*/:
  16878. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/:
  16879. case 'pivottable' /*case 'PivotTable'*/:
  16880. case 'pivotcache' /*case 'PivotCache'*/:
  16881. case 'names' /*case 'Names'*/:
  16882. case 'mapinfo' /*case 'MapInfo'*/:
  16883. case 'pagebreaks' /*case 'PageBreaks'*/:
  16884. case 'querytable' /*case 'QueryTable'*/:
  16885. case 'sorting' /*case 'Sorting'*/:
  16886. case 'schema' /*case 'Schema'*/: //case 'data' /*case 'data'*/:
  16887. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  16888. case 'smarttagtype' /*case 'SmartTagType'*/:
  16889. case 'smarttags' /*case 'SmartTags'*/:
  16890. case 'excelworkbook' /*case 'ExcelWorkbook'*/:
  16891. case 'workbookoptions' /*case 'WorkbookOptions'*/:
  16892. case 'worksheetoptions' /*case 'WorksheetOptions'*/:
  16893. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16894. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  16895. break;
  16896. case 'null' /*case 'Null'*/: break;
  16897. default:
  16898. /* FODS file root is <office:document> */
  16899. if(state.length == 0 && Rn[3] == "document") return parse_fods(str, opts);
  16900. /* UOS file root is <uof:UOF> */
  16901. if(state.length == 0 && Rn[3] == "uof"/*"UOF"*/) return parse_fods(str, opts);
  16902. var seen = true;
  16903. switch(state[state.length-1][0]) {
  16904. /* OfficeDocumentSettings */
  16905. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/: switch(Rn[3]) {
  16906. case 'allowpng' /*case 'AllowPNG'*/: break;
  16907. case 'removepersonalinformation' /*case 'RemovePersonalInformation'*/: break;
  16908. case 'downloadcomponents' /*case 'DownloadComponents'*/: break;
  16909. case 'locationofcomponents' /*case 'LocationOfComponents'*/: break;
  16910. case 'colors' /*case 'Colors'*/: break;
  16911. case 'color' /*case 'Color'*/: break;
  16912. case 'index' /*case 'Index'*/: break;
  16913. case 'rgb' /*case 'RGB'*/: break;
  16914. case 'targetscreensize' /*case 'TargetScreenSize'*/: break;
  16915. case 'readonlyrecommended' /*case 'ReadOnlyRecommended'*/: break;
  16916. default: seen = false;
  16917. } break;
  16918. /* ComponentOptions */
  16919. case 'componentoptions' /*case 'ComponentOptions'*/: switch(Rn[3]) {
  16920. case 'toolbar' /*case 'Toolbar'*/: break;
  16921. case 'hideofficelogo' /*case 'HideOfficeLogo'*/: break;
  16922. case 'spreadsheetautofit' /*case 'SpreadsheetAutoFit'*/: break;
  16923. case 'label' /*case 'Label'*/: break;
  16924. case 'caption' /*case 'Caption'*/: break;
  16925. case 'maxheight' /*case 'MaxHeight'*/: break;
  16926. case 'maxwidth' /*case 'MaxWidth'*/: break;
  16927. case 'nextsheetnumber' /*case 'NextSheetNumber'*/: break;
  16928. default: seen = false;
  16929. } break;
  16930. /* ExcelWorkbook */
  16931. case 'excelworkbook' /*case 'ExcelWorkbook'*/: switch(Rn[3]) {
  16932. case 'date1904' /*case 'Date1904'*/:
  16933. Workbook.WBProps.date1904 = true;
  16934. break;
  16935. case 'windowheight' /*case 'WindowHeight'*/: break;
  16936. case 'windowwidth' /*case 'WindowWidth'*/: break;
  16937. case 'windowtopx' /*case 'WindowTopX'*/: break;
  16938. case 'windowtopy' /*case 'WindowTopY'*/: break;
  16939. case 'tabratio' /*case 'TabRatio'*/: break;
  16940. case 'protectstructure' /*case 'ProtectStructure'*/: break;
  16941. case 'protectwindow' /*case 'ProtectWindow'*/: break;
  16942. case 'protectwindows' /*case 'ProtectWindows'*/: break;
  16943. case 'activesheet' /*case 'ActiveSheet'*/: break;
  16944. case 'displayinknotes' /*case 'DisplayInkNotes'*/: break;
  16945. case 'firstvisiblesheet' /*case 'FirstVisibleSheet'*/: break;
  16946. case 'supbook' /*case 'SupBook'*/: break;
  16947. case 'sheetname' /*case 'SheetName'*/: break;
  16948. case 'sheetindex' /*case 'SheetIndex'*/: break;
  16949. case 'sheetindexfirst' /*case 'SheetIndexFirst'*/: break;
  16950. case 'sheetindexlast' /*case 'SheetIndexLast'*/: break;
  16951. case 'dll' /*case 'Dll'*/: break;
  16952. case 'acceptlabelsinformulas' /*case 'AcceptLabelsInFormulas'*/: break;
  16953. case 'donotsavelinkvalues' /*case 'DoNotSaveLinkValues'*/: break;
  16954. case 'iteration' /*case 'Iteration'*/: break;
  16955. case 'maxiterations' /*case 'MaxIterations'*/: break;
  16956. case 'maxchange' /*case 'MaxChange'*/: break;
  16957. case 'path' /*case 'Path'*/: break;
  16958. case 'xct' /*case 'Xct'*/: break;
  16959. case 'count' /*case 'Count'*/: break;
  16960. case 'selectedsheets' /*case 'SelectedSheets'*/: break;
  16961. case 'calculation' /*case 'Calculation'*/: break;
  16962. case 'uncalced' /*case 'Uncalced'*/: break;
  16963. case 'startupprompt' /*case 'StartupPrompt'*/: break;
  16964. case 'crn' /*case 'Crn'*/: break;
  16965. case 'externname' /*case 'ExternName'*/: break;
  16966. case 'formula' /*case 'Formula'*/: break;
  16967. case 'colfirst' /*case 'ColFirst'*/: break;
  16968. case 'collast' /*case 'ColLast'*/: break;
  16969. case 'wantadvise' /*case 'WantAdvise'*/: break;
  16970. case 'boolean' /*case 'Boolean'*/: break;
  16971. case 'error' /*case 'Error'*/: break;
  16972. case 'text' /*case 'Text'*/: break;
  16973. case 'ole' /*case 'OLE'*/: break;
  16974. case 'noautorecover' /*case 'NoAutoRecover'*/: break;
  16975. case 'publishobjects' /*case 'PublishObjects'*/: break;
  16976. case 'donotcalculatebeforesave' /*case 'DoNotCalculateBeforeSave'*/: break;
  16977. case 'number' /*case 'Number'*/: break;
  16978. case 'refmoder1c1' /*case 'RefModeR1C1'*/: break;
  16979. case 'embedsavesmarttags' /*case 'EmbedSaveSmartTags'*/: break;
  16980. default: seen = false;
  16981. } break;
  16982. /* WorkbookOptions */
  16983. case 'workbookoptions' /*case 'WorkbookOptions'*/: switch(Rn[3]) {
  16984. case 'owcversion' /*case 'OWCVersion'*/: break;
  16985. case 'height' /*case 'Height'*/: break;
  16986. case 'width' /*case 'Width'*/: break;
  16987. default: seen = false;
  16988. } break;
  16989. /* WorksheetOptions */
  16990. case 'worksheetoptions' /*case 'WorksheetOptions'*/: switch(Rn[3]) {
  16991. case 'visible' /*case 'Visible'*/:
  16992. if(Rn[0].slice(-2) === "/>"){/* empty */}
  16993. else if(Rn[1]==="/") switch(str.slice(pidx, Rn.index)) {
  16994. case "SheetHidden": wsprops.Hidden = 1; break;
  16995. case "SheetVeryHidden": wsprops.Hidden = 2; break;
  16996. }
  16997. else pidx = Rn.index + Rn[0].length;
  16998. break;
  16999. case 'header' /*case 'Header'*/:
  17000. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  17001. if(!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet['!margins'].header = +parsexmltag(Rn[0]).Margin;
  17002. break;
  17003. case 'footer' /*case 'Footer'*/:
  17004. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  17005. if(!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet['!margins'].footer = +parsexmltag(Rn[0]).Margin;
  17006. break;
  17007. case 'pagemargins' /*case 'PageMargins'*/:
  17008. var pagemargins = parsexmltag(Rn[0]);
  17009. if(!cursheet['!margins']) default_margins(cursheet['!margins']={},'xlml');
  17010. if(!isNaN(+pagemargins.Top)) cursheet['!margins'].top = +pagemargins.Top;
  17011. if(!isNaN(+pagemargins.Left)) cursheet['!margins'].left = +pagemargins.Left;
  17012. if(!isNaN(+pagemargins.Right)) cursheet['!margins'].right = +pagemargins.Right;
  17013. if(!isNaN(+pagemargins.Bottom)) cursheet['!margins'].bottom = +pagemargins.Bottom;
  17014. break;
  17015. case 'displayrighttoleft' /*case 'DisplayRightToLeft'*/:
  17016. if(!Workbook.Views) Workbook.Views = [];
  17017. if(!Workbook.Views[0]) Workbook.Views[0] = {};
  17018. Workbook.Views[0].RTL = true;
  17019. break;
  17020. case 'freezepanes' /*case 'FreezePanes'*/: break;
  17021. case 'frozennosplit' /*case 'FrozenNoSplit'*/: break;
  17022. case 'splithorizontal' /*case 'SplitHorizontal'*/:
  17023. case 'splitvertical' /*case 'SplitVertical'*/:
  17024. break;
  17025. case 'donotdisplaygridlines' /*case 'DoNotDisplayGridlines'*/:
  17026. break;
  17027. case 'activerow' /*case 'ActiveRow'*/: break;
  17028. case 'activecol' /*case 'ActiveCol'*/: break;
  17029. case 'toprowbottompane' /*case 'TopRowBottomPane'*/: break;
  17030. case 'leftcolumnrightpane' /*case 'LeftColumnRightPane'*/: break;
  17031. case 'unsynced' /*case 'Unsynced'*/: break;
  17032. case 'print' /*case 'Print'*/: break;
  17033. case 'printerrors' /*case 'PrintErrors'*/: break;
  17034. case 'panes' /*case 'Panes'*/: break;
  17035. case 'scale' /*case 'Scale'*/: break;
  17036. case 'pane' /*case 'Pane'*/: break;
  17037. case 'number' /*case 'Number'*/: break;
  17038. case 'layout' /*case 'Layout'*/: break;
  17039. case 'pagesetup' /*case 'PageSetup'*/: break;
  17040. case 'selected' /*case 'Selected'*/: break;
  17041. case 'protectobjects' /*case 'ProtectObjects'*/: break;
  17042. case 'enableselection' /*case 'EnableSelection'*/: break;
  17043. case 'protectscenarios' /*case 'ProtectScenarios'*/: break;
  17044. case 'validprinterinfo' /*case 'ValidPrinterInfo'*/: break;
  17045. case 'horizontalresolution' /*case 'HorizontalResolution'*/: break;
  17046. case 'verticalresolution' /*case 'VerticalResolution'*/: break;
  17047. case 'numberofcopies' /*case 'NumberofCopies'*/: break;
  17048. case 'activepane' /*case 'ActivePane'*/: break;
  17049. case 'toprowvisible' /*case 'TopRowVisible'*/: break;
  17050. case 'leftcolumnvisible' /*case 'LeftColumnVisible'*/: break;
  17051. case 'fittopage' /*case 'FitToPage'*/: break;
  17052. case 'rangeselection' /*case 'RangeSelection'*/: break;
  17053. case 'papersizeindex' /*case 'PaperSizeIndex'*/: break;
  17054. case 'pagelayoutzoom' /*case 'PageLayoutZoom'*/: break;
  17055. case 'pagebreakzoom' /*case 'PageBreakZoom'*/: break;
  17056. case 'filteron' /*case 'FilterOn'*/: break;
  17057. case 'fitwidth' /*case 'FitWidth'*/: break;
  17058. case 'fitheight' /*case 'FitHeight'*/: break;
  17059. case 'commentslayout' /*case 'CommentsLayout'*/: break;
  17060. case 'zoom' /*case 'Zoom'*/: break;
  17061. case 'lefttoright' /*case 'LeftToRight'*/: break;
  17062. case 'gridlines' /*case 'Gridlines'*/: break;
  17063. case 'allowsort' /*case 'AllowSort'*/: break;
  17064. case 'allowfilter' /*case 'AllowFilter'*/: break;
  17065. case 'allowinsertrows' /*case 'AllowInsertRows'*/: break;
  17066. case 'allowdeleterows' /*case 'AllowDeleteRows'*/: break;
  17067. case 'allowinsertcols' /*case 'AllowInsertCols'*/: break;
  17068. case 'allowdeletecols' /*case 'AllowDeleteCols'*/: break;
  17069. case 'allowinserthyperlinks' /*case 'AllowInsertHyperlinks'*/: break;
  17070. case 'allowformatcells' /*case 'AllowFormatCells'*/: break;
  17071. case 'allowsizecols' /*case 'AllowSizeCols'*/: break;
  17072. case 'allowsizerows' /*case 'AllowSizeRows'*/: break;
  17073. case 'nosummaryrowsbelowdetail' /*case 'NoSummaryRowsBelowDetail'*/:
  17074. if(!cursheet["!outline"]) cursheet["!outline"] = {};
  17075. cursheet["!outline"].above = true;
  17076. break;
  17077. case 'tabcolorindex' /*case 'TabColorIndex'*/: break;
  17078. case 'donotdisplayheadings' /*case 'DoNotDisplayHeadings'*/: break;
  17079. case 'showpagelayoutzoom' /*case 'ShowPageLayoutZoom'*/: break;
  17080. case 'nosummarycolumnsrightdetail' /*case 'NoSummaryColumnsRightDetail'*/:
  17081. if(!cursheet["!outline"]) cursheet["!outline"] = {};
  17082. cursheet["!outline"].left = true;
  17083. break;
  17084. case 'blackandwhite' /*case 'BlackAndWhite'*/: break;
  17085. case 'donotdisplayzeros' /*case 'DoNotDisplayZeros'*/: break;
  17086. case 'displaypagebreak' /*case 'DisplayPageBreak'*/: break;
  17087. case 'rowcolheadings' /*case 'RowColHeadings'*/: break;
  17088. case 'donotdisplayoutline' /*case 'DoNotDisplayOutline'*/: break;
  17089. case 'noorientation' /*case 'NoOrientation'*/: break;
  17090. case 'allowusepivottables' /*case 'AllowUsePivotTables'*/: break;
  17091. case 'zeroheight' /*case 'ZeroHeight'*/: break;
  17092. case 'viewablerange' /*case 'ViewableRange'*/: break;
  17093. case 'selection' /*case 'Selection'*/: break;
  17094. case 'protectcontents' /*case 'ProtectContents'*/: break;
  17095. default: seen = false;
  17096. } break;
  17097. /* PivotTable */
  17098. case 'pivottable' /*case 'PivotTable'*/: case 'pivotcache' /*case 'PivotCache'*/: switch(Rn[3]) {
  17099. case 'immediateitemsondrop' /*case 'ImmediateItemsOnDrop'*/: break;
  17100. case 'showpagemultipleitemlabel' /*case 'ShowPageMultipleItemLabel'*/: break;
  17101. case 'compactrowindent' /*case 'CompactRowIndent'*/: break;
  17102. case 'location' /*case 'Location'*/: break;
  17103. case 'pivotfield' /*case 'PivotField'*/: break;
  17104. case 'orientation' /*case 'Orientation'*/: break;
  17105. case 'layoutform' /*case 'LayoutForm'*/: break;
  17106. case 'layoutsubtotallocation' /*case 'LayoutSubtotalLocation'*/: break;
  17107. case 'layoutcompactrow' /*case 'LayoutCompactRow'*/: break;
  17108. case 'position' /*case 'Position'*/: break;
  17109. case 'pivotitem' /*case 'PivotItem'*/: break;
  17110. case 'datatype' /*case 'DataType'*/: break;
  17111. case 'datafield' /*case 'DataField'*/: break;
  17112. case 'sourcename' /*case 'SourceName'*/: break;
  17113. case 'parentfield' /*case 'ParentField'*/: break;
  17114. case 'ptlineitems' /*case 'PTLineItems'*/: break;
  17115. case 'ptlineitem' /*case 'PTLineItem'*/: break;
  17116. case 'countofsameitems' /*case 'CountOfSameItems'*/: break;
  17117. case 'item' /*case 'Item'*/: break;
  17118. case 'itemtype' /*case 'ItemType'*/: break;
  17119. case 'ptsource' /*case 'PTSource'*/: break;
  17120. case 'cacheindex' /*case 'CacheIndex'*/: break;
  17121. case 'consolidationreference' /*case 'ConsolidationReference'*/: break;
  17122. case 'filename' /*case 'FileName'*/: break;
  17123. case 'reference' /*case 'Reference'*/: break;
  17124. case 'nocolumngrand' /*case 'NoColumnGrand'*/: break;
  17125. case 'norowgrand' /*case 'NoRowGrand'*/: break;
  17126. case 'blanklineafteritems' /*case 'BlankLineAfterItems'*/: break;
  17127. case 'hidden' /*case 'Hidden'*/: break;
  17128. case 'subtotal' /*case 'Subtotal'*/: break;
  17129. case 'basefield' /*case 'BaseField'*/: break;
  17130. case 'mapchilditems' /*case 'MapChildItems'*/: break;
  17131. case 'function' /*case 'Function'*/: break;
  17132. case 'refreshonfileopen' /*case 'RefreshOnFileOpen'*/: break;
  17133. case 'printsettitles' /*case 'PrintSetTitles'*/: break;
  17134. case 'mergelabels' /*case 'MergeLabels'*/: break;
  17135. case 'defaultversion' /*case 'DefaultVersion'*/: break;
  17136. case 'refreshname' /*case 'RefreshName'*/: break;
  17137. case 'refreshdate' /*case 'RefreshDate'*/: break;
  17138. case 'refreshdatecopy' /*case 'RefreshDateCopy'*/: break;
  17139. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  17140. case 'versionlastupdate' /*case 'VersionLastUpdate'*/: break;
  17141. case 'versionupdateablemin' /*case 'VersionUpdateableMin'*/: break;
  17142. case 'versionrefreshablemin' /*case 'VersionRefreshableMin'*/: break;
  17143. case 'calculation' /*case 'Calculation'*/: break;
  17144. default: seen = false;
  17145. } break;
  17146. /* PageBreaks */
  17147. case 'pagebreaks' /*case 'PageBreaks'*/: switch(Rn[3]) {
  17148. case 'colbreaks' /*case 'ColBreaks'*/: break;
  17149. case 'colbreak' /*case 'ColBreak'*/: break;
  17150. case 'rowbreaks' /*case 'RowBreaks'*/: break;
  17151. case 'rowbreak' /*case 'RowBreak'*/: break;
  17152. case 'colstart' /*case 'ColStart'*/: break;
  17153. case 'colend' /*case 'ColEnd'*/: break;
  17154. case 'rowend' /*case 'RowEnd'*/: break;
  17155. default: seen = false;
  17156. } break;
  17157. /* AutoFilter */
  17158. case 'autofilter' /*case 'AutoFilter'*/: switch(Rn[3]) {
  17159. case 'autofiltercolumn' /*case 'AutoFilterColumn'*/: break;
  17160. case 'autofiltercondition' /*case 'AutoFilterCondition'*/: break;
  17161. case 'autofilterand' /*case 'AutoFilterAnd'*/: break;
  17162. case 'autofilteror' /*case 'AutoFilterOr'*/: break;
  17163. default: seen = false;
  17164. } break;
  17165. /* QueryTable */
  17166. case 'querytable' /*case 'QueryTable'*/: switch(Rn[3]) {
  17167. case 'id' /*case 'Id'*/: break;
  17168. case 'autoformatfont' /*case 'AutoFormatFont'*/: break;
  17169. case 'autoformatpattern' /*case 'AutoFormatPattern'*/: break;
  17170. case 'querysource' /*case 'QuerySource'*/: break;
  17171. case 'querytype' /*case 'QueryType'*/: break;
  17172. case 'enableredirections' /*case 'EnableRedirections'*/: break;
  17173. case 'refreshedinxl9' /*case 'RefreshedInXl9'*/: break;
  17174. case 'urlstring' /*case 'URLString'*/: break;
  17175. case 'htmltables' /*case 'HTMLTables'*/: break;
  17176. case 'connection' /*case 'Connection'*/: break;
  17177. case 'commandtext' /*case 'CommandText'*/: break;
  17178. case 'refreshinfo' /*case 'RefreshInfo'*/: break;
  17179. case 'notitles' /*case 'NoTitles'*/: break;
  17180. case 'nextid' /*case 'NextId'*/: break;
  17181. case 'columninfo' /*case 'ColumnInfo'*/: break;
  17182. case 'overwritecells' /*case 'OverwriteCells'*/: break;
  17183. case 'donotpromptforfile' /*case 'DoNotPromptForFile'*/: break;
  17184. case 'textwizardsettings' /*case 'TextWizardSettings'*/: break;
  17185. case 'source' /*case 'Source'*/: break;
  17186. case 'number' /*case 'Number'*/: break;
  17187. case 'decimal' /*case 'Decimal'*/: break;
  17188. case 'thousandseparator' /*case 'ThousandSeparator'*/: break;
  17189. case 'trailingminusnumbers' /*case 'TrailingMinusNumbers'*/: break;
  17190. case 'formatsettings' /*case 'FormatSettings'*/: break;
  17191. case 'fieldtype' /*case 'FieldType'*/: break;
  17192. case 'delimiters' /*case 'Delimiters'*/: break;
  17193. case 'tab' /*case 'Tab'*/: break;
  17194. case 'comma' /*case 'Comma'*/: break;
  17195. case 'autoformatname' /*case 'AutoFormatName'*/: break;
  17196. case 'versionlastedit' /*case 'VersionLastEdit'*/: break;
  17197. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  17198. default: seen = false;
  17199. } break;
  17200. case 'datavalidation' /*case 'DataValidation'*/:
  17201. switch(Rn[3]) {
  17202. case 'range' /*case 'Range'*/: break;
  17203. case 'type' /*case 'Type'*/: break;
  17204. case 'min' /*case 'Min'*/: break;
  17205. case 'max' /*case 'Max'*/: break;
  17206. case 'sort' /*case 'Sort'*/: break;
  17207. case 'descending' /*case 'Descending'*/: break;
  17208. case 'order' /*case 'Order'*/: break;
  17209. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  17210. case 'value' /*case 'Value'*/: break;
  17211. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  17212. case 'errormessage' /*case 'ErrorMessage'*/: break;
  17213. case 'errortitle' /*case 'ErrorTitle'*/: break;
  17214. case 'inputmessage' /*case 'InputMessage'*/: break;
  17215. case 'inputtitle' /*case 'InputTitle'*/: break;
  17216. case 'combohide' /*case 'ComboHide'*/: break;
  17217. case 'inputhide' /*case 'InputHide'*/: break;
  17218. case 'condition' /*case 'Condition'*/: break;
  17219. case 'qualifier' /*case 'Qualifier'*/: break;
  17220. case 'useblank' /*case 'UseBlank'*/: break;
  17221. case 'value1' /*case 'Value1'*/: break;
  17222. case 'value2' /*case 'Value2'*/: break;
  17223. case 'format' /*case 'Format'*/: break;
  17224. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  17225. default: seen = false;
  17226. } break;
  17227. case 'sorting' /*case 'Sorting'*/:
  17228. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  17229. switch(Rn[3]) {
  17230. case 'range' /*case 'Range'*/: break;
  17231. case 'type' /*case 'Type'*/: break;
  17232. case 'min' /*case 'Min'*/: break;
  17233. case 'max' /*case 'Max'*/: break;
  17234. case 'sort' /*case 'Sort'*/: break;
  17235. case 'descending' /*case 'Descending'*/: break;
  17236. case 'order' /*case 'Order'*/: break;
  17237. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  17238. case 'value' /*case 'Value'*/: break;
  17239. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  17240. case 'errormessage' /*case 'ErrorMessage'*/: break;
  17241. case 'errortitle' /*case 'ErrorTitle'*/: break;
  17242. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  17243. case 'inputmessage' /*case 'InputMessage'*/: break;
  17244. case 'inputtitle' /*case 'InputTitle'*/: break;
  17245. case 'combohide' /*case 'ComboHide'*/: break;
  17246. case 'inputhide' /*case 'InputHide'*/: break;
  17247. case 'condition' /*case 'Condition'*/: break;
  17248. case 'qualifier' /*case 'Qualifier'*/: break;
  17249. case 'useblank' /*case 'UseBlank'*/: break;
  17250. case 'value1' /*case 'Value1'*/: break;
  17251. case 'value2' /*case 'Value2'*/: break;
  17252. case 'format' /*case 'Format'*/: break;
  17253. default: seen = false;
  17254. } break;
  17255. /* MapInfo (schema) */
  17256. case 'mapinfo' /*case 'MapInfo'*/: case 'schema' /*case 'Schema'*/: case 'data' /*case 'data'*/: switch(Rn[3]) {
  17257. case 'map' /*case 'Map'*/: break;
  17258. case 'entry' /*case 'Entry'*/: break;
  17259. case 'range' /*case 'Range'*/: break;
  17260. case 'xpath' /*case 'XPath'*/: break;
  17261. case 'field' /*case 'Field'*/: break;
  17262. case 'xsdtype' /*case 'XSDType'*/: break;
  17263. case 'filteron' /*case 'FilterOn'*/: break;
  17264. case 'aggregate' /*case 'Aggregate'*/: break;
  17265. case 'elementtype' /*case 'ElementType'*/: break;
  17266. case 'attributetype' /*case 'AttributeType'*/: break;
  17267. /* These are from xsd (XML Schema Definition) */
  17268. case 'schema' /*case 'schema'*/:
  17269. case 'element' /*case 'element'*/:
  17270. case 'complextype' /*case 'complexType'*/:
  17271. case 'datatype' /*case 'datatype'*/:
  17272. case 'all' /*case 'all'*/:
  17273. case 'attribute' /*case 'attribute'*/:
  17274. case 'extends' /*case 'extends'*/: break;
  17275. case 'row' /*case 'row'*/: break;
  17276. default: seen = false;
  17277. } break;
  17278. /* SmartTags (can be anything) */
  17279. case 'smarttags' /*case 'SmartTags'*/: break;
  17280. default: seen = false; break;
  17281. }
  17282. if(seen) break;
  17283. /* CustomDocumentProperties */
  17284. if(Rn[3].match(/!\[CDATA/)) break;
  17285. if(!state[state.length-1][1]) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  17286. if(state[state.length-1][0]===/*'CustomDocumentProperties'*/'customdocumentproperties') {
  17287. if(Rn[0].slice(-2) === "/>") break;
  17288. else if(Rn[1]==="/") xlml_set_custprop(Custprops, raw_Rn3, cp, str.slice(pidx, Rn.index));
  17289. else { cp = Rn; pidx = Rn.index + Rn[0].length; }
  17290. break;
  17291. }
  17292. if(opts.WTF) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  17293. }
  17294. var out = ({});
  17295. if(!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
  17296. out.SheetNames = sheetnames;
  17297. out.Workbook = Workbook;
  17298. out.SSF = dup(table_fmt);
  17299. out.Props = Props;
  17300. out.Custprops = Custprops;
  17301. out.bookType = "xlml";
  17302. return out;
  17303. }
  17304. function parse_xlml(data, opts) {
  17305. fix_read_opts(opts=opts||{});
  17306. switch(opts.type||"base64") {
  17307. case "base64": return parse_xlml_xml(Base64_decode(data), opts);
  17308. case "binary": case "buffer": case "file": return parse_xlml_xml(data, opts);
  17309. case "array": return parse_xlml_xml(a2s(data), opts);
  17310. }
  17311. }
  17312. /* TODO */
  17313. function write_props_xlml(wb, opts) {
  17314. var o = [];
  17315. /* DocumentProperties */
  17316. if(wb.Props) o.push(xlml_write_docprops(wb.Props, opts));
  17317. /* CustomDocumentProperties */
  17318. if(wb.Custprops) o.push(xlml_write_custprops(wb.Props, wb.Custprops, opts));
  17319. return o.join("");
  17320. }
  17321. /* TODO */
  17322. function write_wb_xlml(wb) {
  17323. /* OfficeDocumentSettings */
  17324. /* ExcelWorkbook */
  17325. if((((wb||{}).Workbook||{}).WBProps||{}).date1904) return '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"><Date1904/></ExcelWorkbook>';
  17326. return "";
  17327. }
  17328. /* TODO */
  17329. function write_sty_xlml(wb, opts) {
  17330. /* Styles */
  17331. var styles = ['<Style ss:ID="Default" ss:Name="Normal"><NumberFormat/></Style>'];
  17332. opts.cellXfs.forEach(function(xf, id) {
  17333. var payload = [];
  17334. payload.push(writextag('NumberFormat', null, {"ss:Format": escapexml(table_fmt[xf.numFmtId])}));
  17335. var o = {"ss:ID": "s" + (21+id)};
  17336. styles.push(writextag('Style', payload.join(""), o));
  17337. });
  17338. return writextag("Styles", styles.join(""));
  17339. }
  17340. function write_name_xlml(n) { return writextag("NamedRange", null, {"ss:Name": n.Name.slice(0,6) == "_xlnm." ? n.Name.slice(6) : n.Name, "ss:RefersTo":"=" + a1_to_rc(n.Ref, {r:0,c:0})}); }
  17341. function write_names_xlml(wb) {
  17342. if(!((wb||{}).Workbook||{}).Names) return "";
  17343. var names = wb.Workbook.Names;
  17344. var out = [];
  17345. for(var i = 0; i < names.length; ++i) {
  17346. var n = names[i];
  17347. if(n.Sheet != null) continue;
  17348. if(n.Name.match(/^_xlfn\./)) continue;
  17349. out.push(write_name_xlml(n));
  17350. }
  17351. return writextag("Names", out.join(""));
  17352. }
  17353. function write_ws_xlml_names(ws, opts, idx, wb) {
  17354. if(!ws) return "";
  17355. if(!((wb||{}).Workbook||{}).Names) return "";
  17356. var names = wb.Workbook.Names;
  17357. var out = [];
  17358. for(var i = 0; i < names.length; ++i) {
  17359. var n = names[i];
  17360. if(n.Sheet != idx) continue;
  17361. /*switch(n.Name) {
  17362. case "_": continue;
  17363. }*/
  17364. if(n.Name.match(/^_xlfn\./)) continue;
  17365. out.push(write_name_xlml(n));
  17366. }
  17367. return out.join("");
  17368. }
  17369. /* WorksheetOptions */
  17370. function write_ws_xlml_wsopts(ws, opts, idx, wb) {
  17371. if(!ws) return "";
  17372. var o = [];
  17373. /* NOTE: spec technically allows any order, but stick with implied order */
  17374. /* FitToPage */
  17375. /* DoNotDisplayColHeaders */
  17376. /* DoNotDisplayRowHeaders */
  17377. /* ViewableRange */
  17378. /* Selection */
  17379. /* GridlineColor */
  17380. /* Name */
  17381. /* ExcelWorksheetType */
  17382. /* IntlMacro */
  17383. /* Unsynced */
  17384. /* Selected */
  17385. /* CodeName */
  17386. if(ws['!margins']) {
  17387. o.push("<PageSetup>");
  17388. if(ws['!margins'].header) o.push(writextag("Header", null, {'x:Margin':ws['!margins'].header}));
  17389. if(ws['!margins'].footer) o.push(writextag("Footer", null, {'x:Margin':ws['!margins'].footer}));
  17390. o.push(writextag("PageMargins", null, {
  17391. 'x:Bottom': ws['!margins'].bottom || "0.75",
  17392. 'x:Left': ws['!margins'].left || "0.7",
  17393. 'x:Right': ws['!margins'].right || "0.7",
  17394. 'x:Top': ws['!margins'].top || "0.75"
  17395. }));
  17396. o.push("</PageSetup>");
  17397. }
  17398. /* PageSetup */
  17399. /* DisplayPageBreak */
  17400. /* TransitionExpressionEvaluation */
  17401. /* TransitionFormulaEntry */
  17402. /* Print */
  17403. /* Zoom */
  17404. /* PageLayoutZoom */
  17405. /* PageBreakZoom */
  17406. /* ShowPageBreakZoom */
  17407. /* DefaultRowHeight */
  17408. /* DefaultColumnWidth */
  17409. /* StandardWidth */
  17410. if(wb && wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx]) {
  17411. /* Visible */
  17412. if(wb.Workbook.Sheets[idx].Hidden) o.push(writextag("Visible", (wb.Workbook.Sheets[idx].Hidden == 1 ? "SheetHidden" : "SheetVeryHidden"), {}));
  17413. else {
  17414. /* Selected */
  17415. for(var i = 0; i < idx; ++i) if(wb.Workbook.Sheets[i] && !wb.Workbook.Sheets[i].Hidden) break;
  17416. if(i == idx) o.push("<Selected/>");
  17417. }
  17418. }
  17419. /* LeftColumnVisible */
  17420. if(((((wb||{}).Workbook||{}).Views||[])[0]||{}).RTL) o.push("<DisplayRightToLeft/>");
  17421. /* GridlineColorIndex */
  17422. /* DisplayFormulas */
  17423. /* DoNotDisplayGridlines */
  17424. /* DoNotDisplayHeadings */
  17425. /* DoNotDisplayOutline */
  17426. /* ApplyAutomaticOutlineStyles */
  17427. /* NoSummaryRowsBelowDetail */
  17428. /* NoSummaryColumnsRightDetail */
  17429. /* DoNotDisplayZeros */
  17430. /* ActiveRow */
  17431. /* ActiveColumn */
  17432. /* FilterOn */
  17433. /* RangeSelection */
  17434. /* TopRowVisible */
  17435. /* TopRowBottomPane */
  17436. /* LeftColumnRightPane */
  17437. /* ActivePane */
  17438. /* SplitHorizontal */
  17439. /* SplitVertical */
  17440. /* FreezePanes */
  17441. /* FrozenNoSplit */
  17442. /* TabColorIndex */
  17443. /* Panes */
  17444. /* NOTE: Password not supported in XLML Format */
  17445. if(ws['!protect']) {
  17446. o.push(writetag("ProtectContents", "True"));
  17447. if(ws['!protect'].objects) o.push(writetag("ProtectObjects", "True"));
  17448. if(ws['!protect'].scenarios) o.push(writetag("ProtectScenarios", "True"));
  17449. if(ws['!protect'].selectLockedCells != null && !ws['!protect'].selectLockedCells) o.push(writetag("EnableSelection", "NoSelection"));
  17450. else if(ws['!protect'].selectUnlockedCells != null && !ws['!protect'].selectUnlockedCells) o.push(writetag("EnableSelection", "UnlockedCells"));
  17451. [
  17452. [ "formatCells", "AllowFormatCells" ],
  17453. [ "formatColumns", "AllowSizeCols" ],
  17454. [ "formatRows", "AllowSizeRows" ],
  17455. [ "insertColumns", "AllowInsertCols" ],
  17456. [ "insertRows", "AllowInsertRows" ],
  17457. [ "insertHyperlinks", "AllowInsertHyperlinks" ],
  17458. [ "deleteColumns", "AllowDeleteCols" ],
  17459. [ "deleteRows", "AllowDeleteRows" ],
  17460. [ "sort", "AllowSort" ],
  17461. [ "autoFilter", "AllowFilter" ],
  17462. [ "pivotTables", "AllowUsePivotTables" ]
  17463. ].forEach(function(x) { if(ws['!protect'][x[0]]) o.push("<"+x[1]+"/>"); });
  17464. }
  17465. if(o.length == 0) return "";
  17466. return writextag("WorksheetOptions", o.join(""), {xmlns:XLMLNS.x});
  17467. }
  17468. function write_ws_xlml_comment(comments) {
  17469. return comments.map(function(c) {
  17470. // TODO: formatted text
  17471. var t = xlml_unfixstr(c.t||"");
  17472. var d =writextag("ss:Data", t, {"xmlns":"http://www.w3.org/TR/REC-html40"});
  17473. return writextag("Comment", d, {"ss:Author":c.a});
  17474. }).join("");
  17475. }
  17476. function write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr){
  17477. if(!cell || (cell.v == undefined && cell.f == undefined)) return "";
  17478. var attr = {};
  17479. if(cell.f) attr["ss:Formula"] = "=" + escapexml(a1_to_rc(cell.f, addr));
  17480. if(cell.F && cell.F.slice(0, ref.length) == ref) {
  17481. var end = decode_cell(cell.F.slice(ref.length + 1));
  17482. attr["ss:ArrayRange"] = "RC:R" + (end.r == addr.r ? "" : "[" + (end.r - addr.r) + "]") + "C" + (end.c == addr.c ? "" : "[" + (end.c - addr.c) + "]");
  17483. }
  17484. if(cell.l && cell.l.Target) {
  17485. attr["ss:HRef"] = escapexml(cell.l.Target);
  17486. if(cell.l.Tooltip) attr["x:HRefScreenTip"] = escapexml(cell.l.Tooltip);
  17487. }
  17488. if(ws['!merges']) {
  17489. var marr = ws['!merges'];
  17490. for(var mi = 0; mi != marr.length; ++mi) {
  17491. if(marr[mi].s.c != addr.c || marr[mi].s.r != addr.r) continue;
  17492. if(marr[mi].e.c > marr[mi].s.c) attr['ss:MergeAcross'] = marr[mi].e.c - marr[mi].s.c;
  17493. if(marr[mi].e.r > marr[mi].s.r) attr['ss:MergeDown'] = marr[mi].e.r - marr[mi].s.r;
  17494. }
  17495. }
  17496. var t = "", p = "";
  17497. switch(cell.t) {
  17498. case 'z': if(!opts.sheetStubs) return ""; break;
  17499. case 'n': t = 'Number'; p = String(cell.v); break;
  17500. case 'b': t = 'Boolean'; p = (cell.v ? "1" : "0"); break;
  17501. case 'e': t = 'Error'; p = BErr[cell.v]; break;
  17502. case 'd': t = 'DateTime'; p = new Date(cell.v).toISOString(); if(cell.z == null) cell.z = cell.z || table_fmt[14]; break;
  17503. case 's': t = 'String'; p = escapexlml(cell.v||""); break;
  17504. }
  17505. /* TODO: cell style */
  17506. var os = get_cell_style(opts.cellXfs, cell, opts);
  17507. attr["ss:StyleID"] = "s" + (21+os);
  17508. attr["ss:Index"] = addr.c + 1;
  17509. var _v = (cell.v != null ? p : "");
  17510. var m = cell.t == 'z' ? "" : ('<Data ss:Type="' + t + '">' + _v + '</Data>');
  17511. if((cell.c||[]).length > 0) m += write_ws_xlml_comment(cell.c);
  17512. return writextag("Cell", m, attr);
  17513. }
  17514. function write_ws_xlml_row(R, row) {
  17515. var o = '<Row ss:Index="' + (R+1) + '"';
  17516. if(row) {
  17517. if(row.hpt && !row.hpx) row.hpx = pt2px(row.hpt);
  17518. if(row.hpx) o += ' ss:AutoFitHeight="0" ss:Height="' + row.hpx + '"';
  17519. if(row.hidden) o += ' ss:Hidden="1"';
  17520. }
  17521. return o + '>';
  17522. }
  17523. /* TODO */
  17524. function write_ws_xlml_table(ws, opts, idx, wb) {
  17525. if(!ws['!ref']) return "";
  17526. var range = safe_decode_range(ws['!ref']);
  17527. var marr = ws['!merges'] || [], mi = 0;
  17528. var o = [];
  17529. if(ws['!cols']) ws['!cols'].forEach(function(n, i) {
  17530. process_col(n);
  17531. var w = !!n.width;
  17532. var p = col_obj_w(i, n);
  17533. var k = {"ss:Index":i+1};
  17534. if(w) k['ss:Width'] = width2px(p.width);
  17535. if(n.hidden) k['ss:Hidden']="1";
  17536. o.push(writextag("Column",null,k));
  17537. });
  17538. var dense = Array.isArray(ws);
  17539. for(var R = range.s.r; R <= range.e.r; ++R) {
  17540. var row = [write_ws_xlml_row(R, (ws['!rows']||[])[R])];
  17541. for(var C = range.s.c; C <= range.e.c; ++C) {
  17542. var skip = false;
  17543. for(mi = 0; mi != marr.length; ++mi) {
  17544. if(marr[mi].s.c > C) continue;
  17545. if(marr[mi].s.r > R) continue;
  17546. if(marr[mi].e.c < C) continue;
  17547. if(marr[mi].e.r < R) continue;
  17548. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  17549. break;
  17550. }
  17551. if(skip) continue;
  17552. var addr = {r:R,c:C};
  17553. var ref = encode_cell(addr), cell = dense ? (ws[R]||[])[C] : ws[ref];
  17554. row.push(write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr));
  17555. }
  17556. row.push("</Row>");
  17557. if(row.length > 2) o.push(row.join(""));
  17558. }
  17559. return o.join("");
  17560. }
  17561. function write_ws_xlml(idx, opts, wb) {
  17562. var o = [];
  17563. var s = wb.SheetNames[idx];
  17564. var ws = wb.Sheets[s];
  17565. var t = ws ? write_ws_xlml_names(ws, opts, idx, wb) : "";
  17566. if(t.length > 0) o.push("<Names>" + t + "</Names>");
  17567. /* Table */
  17568. t = ws ? write_ws_xlml_table(ws, opts, idx, wb) : "";
  17569. if(t.length > 0) o.push("<Table>" + t + "</Table>");
  17570. /* WorksheetOptions */
  17571. o.push(write_ws_xlml_wsopts(ws, opts, idx, wb));
  17572. if(ws["!autofilter"]) o.push('<AutoFilter x:Range="' + a1_to_rc(fix_range(ws["!autofilter"].ref), {r:0,c:0}) + '" xmlns="urn:schemas-microsoft-com:office:excel"></AutoFilter>');
  17573. return o.join("");
  17574. }
  17575. function write_xlml(wb, opts) {
  17576. if(!opts) opts = {};
  17577. if(!wb.SSF) wb.SSF = dup(table_fmt);
  17578. if(wb.SSF) {
  17579. make_ssf(); SSF_load_table(wb.SSF);
  17580. // $FlowIgnore
  17581. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  17582. opts.ssf = wb.SSF;
  17583. opts.cellXfs = [];
  17584. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  17585. }
  17586. var d = [];
  17587. d.push(write_props_xlml(wb, opts));
  17588. d.push(write_wb_xlml(wb, opts));
  17589. d.push("");
  17590. d.push("");
  17591. for(var i = 0; i < wb.SheetNames.length; ++i)
  17592. d.push(writextag("Worksheet", write_ws_xlml(i, opts, wb), {"ss:Name":escapexml(wb.SheetNames[i])}));
  17593. d[2] = write_sty_xlml(wb, opts);
  17594. d[3] = write_names_xlml(wb, opts);
  17595. return XML_HEADER + writextag("Workbook", d.join(""), {
  17596. 'xmlns': XLMLNS.ss,
  17597. 'xmlns:o': XLMLNS.o,
  17598. 'xmlns:x': XLMLNS.x,
  17599. 'xmlns:ss': XLMLNS.ss,
  17600. 'xmlns:dt': XLMLNS.dt,
  17601. 'xmlns:html': XLMLNS.html
  17602. });
  17603. }
  17604. /* [MS-OLEDS] 2.3.8 CompObjStream */
  17605. function parse_compobj(obj) {
  17606. var v = {};
  17607. var o = obj.content;
  17608. /* [MS-OLEDS] 2.3.7 CompObjHeader -- All fields MUST be ignored */
  17609. o.l = 28;
  17610. v.AnsiUserType = o.read_shift(0, "lpstr-ansi");
  17611. v.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o);
  17612. if(o.length - o.l <= 4) return v;
  17613. var m = o.read_shift(4);
  17614. if(m == 0 || m > 40) return v;
  17615. o.l-=4; v.Reserved1 = o.read_shift(0, "lpstr-ansi");
  17616. if(o.length - o.l <= 4) return v;
  17617. m = o.read_shift(4);
  17618. if(m !== 0x71b239f4) return v;
  17619. v.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o);
  17620. m = o.read_shift(4);
  17621. if(m == 0 || m > 40) return v;
  17622. o.l-=4; v.Reserved2 = o.read_shift(0, "lpwstr");
  17623. }
  17624. /*
  17625. Continue logic for:
  17626. - 2.4.58 Continue 0x003c
  17627. - 2.4.59 ContinueBigName 0x043c
  17628. - 2.4.60 ContinueFrt 0x0812
  17629. - 2.4.61 ContinueFrt11 0x0875
  17630. - 2.4.62 ContinueFrt12 0x087f
  17631. */
  17632. var CONTINUE_RT = [ 0x003c, 0x043c, 0x0812, 0x0875, 0x087f ];
  17633. function slurp(RecordType, R, blob, length, opts) {
  17634. var l = length;
  17635. var bufs = [];
  17636. var d = blob.slice(blob.l,blob.l+l);
  17637. if(opts && opts.enc && opts.enc.insitu && d.length > 0) switch(RecordType) {
  17638. case 0x0009: case 0x0209: case 0x0409: case 0x0809/* BOF */: case 0x002F /* FilePass */: case 0x0195 /* FileLock */: case 0x00E1 /* InterfaceHdr */: case 0x0196 /* RRDInfo */: case 0x0138 /* RRDHead */: case 0x0194 /* UsrExcl */: case 0x000a /* EOF */:
  17639. break;
  17640. case 0x0085 /* BoundSheet8 */:
  17641. break;
  17642. default:
  17643. opts.enc.insitu(d);
  17644. }
  17645. bufs.push(d);
  17646. blob.l += l;
  17647. var nextrt = __readUInt16LE(blob,blob.l), next = XLSRecordEnum[nextrt];
  17648. var start = 0;
  17649. while(next != null && CONTINUE_RT.indexOf(nextrt) > -1) {
  17650. l = __readUInt16LE(blob,blob.l+2);
  17651. start = blob.l + 4;
  17652. if(nextrt == 0x0812 /* ContinueFrt */) start += 4;
  17653. else if(nextrt == 0x0875 || nextrt == 0x087f) {
  17654. start += 12;
  17655. }
  17656. d = blob.slice(start,blob.l+4+l);
  17657. bufs.push(d);
  17658. blob.l += 4+l;
  17659. next = (XLSRecordEnum[nextrt = __readUInt16LE(blob, blob.l)]);
  17660. }
  17661. var b = (bconcat(bufs));
  17662. prep_blob(b, 0);
  17663. var ll = 0; b.lens = [];
  17664. for(var j = 0; j < bufs.length; ++j) { b.lens.push(ll); ll += bufs[j].length; }
  17665. if(b.length < length) throw "XLS Record 0x" + RecordType.toString(16) + " Truncated: " + b.length + " < " + length;
  17666. return R.f(b, b.length, opts);
  17667. }
  17668. function safe_format_xf(p, opts, date1904) {
  17669. if(p.t === 'z') return;
  17670. if(!p.XF) return;
  17671. var fmtid = 0;
  17672. try {
  17673. fmtid = p.z || p.XF.numFmtId || 0;
  17674. if(opts.cellNF) p.z = table_fmt[fmtid];
  17675. } catch(e) { if(opts.WTF) throw e; }
  17676. if(!opts || opts.cellText !== false) try {
  17677. if(p.t === 'e') { p.w = p.w || BErr[p.v]; }
  17678. else if(fmtid === 0 || fmtid == "General") {
  17679. if(p.t === 'n') {
  17680. if((p.v|0) === p.v) p.w = p.v.toString(10);
  17681. else p.w = SSF_general_num(p.v);
  17682. }
  17683. else p.w = SSF_general(p.v);
  17684. }
  17685. else p.w = SSF_format(fmtid,p.v, {date1904:!!date1904, dateNF: opts && opts.dateNF});
  17686. } catch(e) { if(opts.WTF) throw e; }
  17687. if(opts.cellDates && fmtid && p.t == 'n' && fmt_is_date(table_fmt[fmtid] || String(fmtid))) {
  17688. var _d = SSF_parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  17689. }
  17690. }
  17691. function make_cell(val, ixfe, t) {
  17692. return ({v:val, ixfe:ixfe, t:t});
  17693. }
  17694. // 2.3.2
  17695. function parse_workbook(blob, options) {
  17696. var wb = ({opts:{}});
  17697. var Sheets = {};
  17698. if(DENSE != null && options.dense == null) options.dense = DENSE;
  17699. var out = ((options.dense ? [] : {}));
  17700. var Directory = {};
  17701. var range = ({});
  17702. var last_formula = null;
  17703. var sst = ([]);
  17704. var cur_sheet = "";
  17705. var Preamble = {};
  17706. var lastcell, last_cell = "", cc, cmnt, rngC, rngR;
  17707. var sharedf = {};
  17708. var arrayf = [];
  17709. var temp_val;
  17710. var country;
  17711. var XFs = []; /* XF records */
  17712. var palette = [];
  17713. var Workbook = ({ Sheets:[], WBProps:{date1904:false}, Views:[{}] }), wsprops = {};
  17714. var get_rgb = function getrgb(icv) {
  17715. if(icv < 8) return XLSIcv[icv];
  17716. if(icv < 64) return palette[icv-8] || XLSIcv[icv];
  17717. return XLSIcv[icv];
  17718. };
  17719. var process_cell_style = function pcs(cell, line, options) {
  17720. var xfd = line.XF.data;
  17721. if(!xfd || !xfd.patternType || !options || !options.cellStyles) return;
  17722. line.s = ({});
  17723. line.s.patternType = xfd.patternType;
  17724. var t;
  17725. if((t = rgb2Hex(get_rgb(xfd.icvFore)))) { line.s.fgColor = {rgb:t}; }
  17726. if((t = rgb2Hex(get_rgb(xfd.icvBack)))) { line.s.bgColor = {rgb:t}; }
  17727. };
  17728. var addcell = function addcell(cell, line, options) {
  17729. if(file_depth > 1) return;
  17730. if(options.sheetRows && cell.r >= options.sheetRows) return;
  17731. if(options.cellStyles && line.XF && line.XF.data) process_cell_style(cell, line, options);
  17732. delete line.ixfe; delete line.XF;
  17733. lastcell = cell;
  17734. last_cell = encode_cell(cell);
  17735. if(!range || !range.s || !range.e) range = {s:{r:0,c:0},e:{r:0,c:0}};
  17736. if(cell.r < range.s.r) range.s.r = cell.r;
  17737. if(cell.c < range.s.c) range.s.c = cell.c;
  17738. if(cell.r + 1 > range.e.r) range.e.r = cell.r + 1;
  17739. if(cell.c + 1 > range.e.c) range.e.c = cell.c + 1;
  17740. if(options.cellFormula && line.f) {
  17741. for(var afi = 0; afi < arrayf.length; ++afi) {
  17742. if(arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
  17743. if(arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
  17744. line.F = encode_range(arrayf[afi][0]);
  17745. if(arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
  17746. if(line.f) line.f = "" + stringify_formula(arrayf[afi][1], range, cell, supbooks, opts);
  17747. break;
  17748. }
  17749. }
  17750. {
  17751. if(options.dense) {
  17752. if(!out[cell.r]) out[cell.r] = [];
  17753. out[cell.r][cell.c] = line;
  17754. } else out[last_cell] = line;
  17755. }
  17756. };
  17757. var opts = ({
  17758. enc: false, // encrypted
  17759. sbcch: 0, // cch in the preceding SupBook
  17760. snames: [], // sheetnames
  17761. sharedf: sharedf, // shared formulae by address
  17762. arrayf: arrayf, // array formulae array
  17763. rrtabid: [], // RRTabId
  17764. lastuser: "", // Last User from WriteAccess
  17765. biff: 8, // BIFF version
  17766. codepage: 0, // CP from CodePage record
  17767. winlocked: 0, // fLockWn from WinProtect
  17768. cellStyles: !!options && !!options.cellStyles,
  17769. WTF: !!options && !!options.wtf
  17770. });
  17771. if(options.password) opts.password = options.password;
  17772. var themes;
  17773. var merges = [];
  17774. var objects = [];
  17775. var colinfo = [], rowinfo = [];
  17776. var seencol = false;
  17777. var supbooks = ([]); // 1-indexed, will hold extern names
  17778. supbooks.SheetNames = opts.snames;
  17779. supbooks.sharedf = opts.sharedf;
  17780. supbooks.arrayf = opts.arrayf;
  17781. supbooks.names = [];
  17782. supbooks.XTI = [];
  17783. var last_RT = 0;
  17784. var file_depth = 0; /* TODO: make a real stack */
  17785. var BIFF2Fmt = 0, BIFF2FmtTable = [];
  17786. var FilterDatabases = []; /* TODO: sort out supbooks and process elsewhere */
  17787. var last_lbl;
  17788. /* explicit override for some broken writers */
  17789. opts.codepage = 1200;
  17790. set_cp(1200);
  17791. var seen_codepage = false;
  17792. while(blob.l < blob.length - 1) {
  17793. var s = blob.l;
  17794. var RecordType = blob.read_shift(2);
  17795. if(RecordType === 0 && last_RT === 0x000a /* EOF */) break;
  17796. var length = (blob.l === blob.length ? 0 : blob.read_shift(2));
  17797. var R = XLSRecordEnum[RecordType];
  17798. if(file_depth == 0 && [0x0009, 0x0209, 0x0409, 0x0809].indexOf(RecordType) == -1 /* BOF */) break;
  17799. //console.log(RecordType.toString(16), RecordType, R, blob.l, length, blob.length);
  17800. //if(!R) console.log(blob.slice(blob.l, blob.l + length));
  17801. if(R && R.f) {
  17802. if(options.bookSheets) {
  17803. if(last_RT === 0x0085 /* BoundSheet8 */ && RecordType !== 0x0085 /* R.n !== 'BoundSheet8' */) break;
  17804. }
  17805. last_RT = RecordType;
  17806. if(R.r === 2 || R.r == 12) {
  17807. var rt = blob.read_shift(2); length -= 2;
  17808. if(!opts.enc && rt !== RecordType && (((rt&0xFF)<<8)|(rt>>8)) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
  17809. if(R.r == 12){
  17810. blob.l += 10; length -= 10;
  17811. } // skip FRT
  17812. }
  17813. //console.error(R,blob.l,length,blob.length);
  17814. var val = ({});
  17815. if(RecordType === 0x000a /* EOF */) val = R.f(blob, length, opts);
  17816. else val = slurp(RecordType, R, blob, length, opts);
  17817. if(file_depth == 0 && [0x0009, 0x0209, 0x0409, 0x0809].indexOf(last_RT) === -1 /* BOF */) continue;
  17818. switch(RecordType) {
  17819. case 0x0022 /* Date1904 */:
  17820. wb.opts.Date1904 = Workbook.WBProps.date1904 = val; break;
  17821. case 0x0086 /* WriteProtect */: wb.opts.WriteProtect = true; break;
  17822. case 0x002f /* FilePass */:
  17823. if(!opts.enc) blob.l = 0;
  17824. opts.enc = val;
  17825. if(!options.password) throw new Error("File is password-protected");
  17826. if(val.valid == null) throw new Error("Encryption scheme unsupported");
  17827. if(!val.valid) throw new Error("Password is incorrect");
  17828. break;
  17829. case 0x005c /* WriteAccess */: opts.lastuser = val; break;
  17830. case 0x0042 /* CodePage */:
  17831. var cpval = Number(val);
  17832. /* overrides based on test cases */
  17833. switch(cpval) {
  17834. case 0x5212: cpval = 1200; break;
  17835. case 0x8000: cpval = 10000; break;
  17836. case 0x8001: cpval = 1252; break;
  17837. }
  17838. set_cp(opts.codepage = cpval);
  17839. seen_codepage = true;
  17840. break;
  17841. case 0x013d /* RRTabId */: opts.rrtabid = val; break;
  17842. case 0x0019 /* WinProtect */: opts.winlocked = val; break;
  17843. case 0x01b7 /* RefreshAll */: wb.opts["RefreshAll"] = val; break;
  17844. case 0x000c /* CalcCount */: wb.opts["CalcCount"] = val; break;
  17845. case 0x0010 /* CalcDelta */: wb.opts["CalcDelta"] = val; break;
  17846. case 0x0011 /* CalcIter */: wb.opts["CalcIter"] = val; break;
  17847. case 0x000d /* CalcMode */: wb.opts["CalcMode"] = val; break;
  17848. case 0x000e /* CalcPrecision */: wb.opts["CalcPrecision"] = val; break;
  17849. case 0x005f /* CalcSaveRecalc */: wb.opts["CalcSaveRecalc"] = val; break;
  17850. case 0x000f /* CalcRefMode */: opts.CalcRefMode = val; break; // TODO: implement R1C1
  17851. case 0x08a3 /* ForceFullCalculation */: wb.opts.FullCalc = val; break;
  17852. case 0x0081 /* WsBool */:
  17853. if(val.fDialog) out["!type"] = "dialog";
  17854. if(!val.fBelow) (out["!outline"] || (out["!outline"] = {})).above = true;
  17855. if(!val.fRight) (out["!outline"] || (out["!outline"] = {})).left = true;
  17856. break; // TODO
  17857. case 0x00e0 /* XF */:
  17858. XFs.push(val); break;
  17859. case 0x01ae /* SupBook */:
  17860. supbooks.push([val]);
  17861. supbooks[supbooks.length-1].XTI = [];
  17862. break;
  17863. case 0x0023: case 0x0223 /* ExternName */:
  17864. supbooks[supbooks.length-1].push(val);
  17865. break;
  17866. case 0x0018: case 0x0218 /* Lbl */:
  17867. last_lbl = ({
  17868. Name: val.Name,
  17869. Ref: stringify_formula(val.rgce,range,null,supbooks,opts)
  17870. });
  17871. if(val.itab > 0) last_lbl.Sheet = val.itab - 1;
  17872. supbooks.names.push(last_lbl);
  17873. if(!supbooks[0]) { supbooks[0] = []; supbooks[0].XTI = []; }
  17874. supbooks[supbooks.length-1].push(val);
  17875. if(val.Name == "_xlnm._FilterDatabase" && val.itab > 0)
  17876. if(val.rgce && val.rgce[0] && val.rgce[0][0] && val.rgce[0][0][0] == 'PtgArea3d')
  17877. FilterDatabases[val.itab - 1] = { ref: encode_range(val.rgce[0][0][1][2]) };
  17878. break;
  17879. case 0x0016 /* ExternCount */: opts.ExternCount = val; break;
  17880. case 0x0017 /* ExternSheet */:
  17881. if(supbooks.length == 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  17882. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val); supbooks.XTI = supbooks.XTI.concat(val); break;
  17883. case 0x0894 /* NameCmt */:
  17884. /* TODO: search for correct name */
  17885. if(opts.biff < 8) break;
  17886. if(last_lbl != null) last_lbl.Comment = val[1];
  17887. break;
  17888. case 0x0012 /* Protect */: out["!protect"] = val; break; /* for sheet or book */
  17889. case 0x0013 /* Password */: if(val !== 0 && opts.WTF) console.error("Password verifier: " + val); break;
  17890. case 0x0085 /* BoundSheet8 */: {
  17891. Directory[val.pos] = val;
  17892. opts.snames.push(val.name);
  17893. } break;
  17894. case 0x000a /* EOF */: {
  17895. if(--file_depth) break;
  17896. if(range.e) {
  17897. if(range.e.r > 0 && range.e.c > 0) {
  17898. range.e.r--; range.e.c--;
  17899. out["!ref"] = encode_range(range);
  17900. if(options.sheetRows && options.sheetRows <= range.e.r) {
  17901. var tmpri = range.e.r;
  17902. range.e.r = options.sheetRows - 1;
  17903. out["!fullref"] = out["!ref"];
  17904. out["!ref"] = encode_range(range);
  17905. range.e.r = tmpri;
  17906. }
  17907. range.e.r++; range.e.c++;
  17908. }
  17909. if(merges.length > 0) out["!merges"] = merges;
  17910. if(objects.length > 0) out["!objects"] = objects;
  17911. if(colinfo.length > 0) out["!cols"] = colinfo;
  17912. if(rowinfo.length > 0) out["!rows"] = rowinfo;
  17913. Workbook.Sheets.push(wsprops);
  17914. }
  17915. if(cur_sheet === "") Preamble = out; else Sheets[cur_sheet] = out;
  17916. out = ((options.dense ? [] : {}));
  17917. } break;
  17918. case 0x0009: case 0x0209: case 0x0409: case 0x0809 /* BOF */: {
  17919. if(opts.biff === 8) opts.biff = {
  17920. 0x0009:2,
  17921. 0x0209:3,
  17922. 0x0409:4
  17923. }[RecordType] || {
  17924. 0x0200:2,
  17925. 0x0300:3,
  17926. 0x0400:4,
  17927. 0x0500:5,
  17928. 0x0600:8,
  17929. 0x0002:2,
  17930. 0x0007:2
  17931. }[val.BIFFVer] || 8;
  17932. opts.biffguess = val.BIFFVer == 0;
  17933. if(val.BIFFVer == 0 && val.dt == 0x1000) { opts.biff = 5; seen_codepage = true; set_cp(opts.codepage = 28591); }
  17934. if(opts.biff == 8 && val.BIFFVer == 0 && val.dt == 16) opts.biff = 2;
  17935. if(file_depth++) break;
  17936. out = ((options.dense ? [] : {}));
  17937. if(opts.biff < 8 && !seen_codepage) { seen_codepage = true; set_cp(opts.codepage = options.codepage || 1252); }
  17938. if(opts.biff < 5 || val.BIFFVer == 0 && val.dt == 0x1000) {
  17939. if(cur_sheet === "") cur_sheet = "Sheet1";
  17940. range = {s:{r:0,c:0},e:{r:0,c:0}};
  17941. /* fake BoundSheet8 */
  17942. var fakebs8 = {pos: blob.l - length, name:cur_sheet};
  17943. Directory[fakebs8.pos] = fakebs8;
  17944. opts.snames.push(cur_sheet);
  17945. }
  17946. else cur_sheet = (Directory[s] || {name:""}).name;
  17947. if(val.dt == 0x20) out["!type"] = "chart";
  17948. if(val.dt == 0x40) out["!type"] = "macro";
  17949. merges = [];
  17950. objects = [];
  17951. opts.arrayf = arrayf = [];
  17952. colinfo = []; rowinfo = [];
  17953. seencol = false;
  17954. wsprops = {Hidden:(Directory[s]||{hs:0}).hs, name:cur_sheet };
  17955. } break;
  17956. case 0x0203 /* Number */: case 0x0003 /* BIFF2NUM */: case 0x0002 /* BIFF2INT */: {
  17957. if(out["!type"] == "chart") if(options.dense ? (out[val.r]||[])[val.c]: out[encode_cell({c:val.c, r:val.r})]) ++val.c;
  17958. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe]||{}, v:val.val, t:'n'});
  17959. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17960. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17961. addcell({c:val.c, r:val.r}, temp_val, options);
  17962. } break;
  17963. case 0x0005: case 0x0205 /* BoolErr */: {
  17964. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:val.t});
  17965. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17966. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17967. addcell({c:val.c, r:val.r}, temp_val, options);
  17968. } break;
  17969. case 0x027e /* RK */: {
  17970. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.rknum, t:'n'});
  17971. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17972. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17973. addcell({c:val.c, r:val.r}, temp_val, options);
  17974. } break;
  17975. case 0x00bd /* MulRk */: {
  17976. for(var j = val.c; j <= val.C; ++j) {
  17977. var ixfe = val.rkrec[j-val.c][0];
  17978. temp_val= ({ixfe:ixfe, XF:XFs[ixfe], v:val.rkrec[j-val.c][1], t:'n'});
  17979. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17980. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17981. addcell({c:j, r:val.r}, temp_val, options);
  17982. }
  17983. } break;
  17984. case 0x0006: case 0x0206: case 0x0406 /* Formula */: {
  17985. if(val.val == 'String') { last_formula = val; break; }
  17986. temp_val = make_cell(val.val, val.cell.ixfe, val.tt);
  17987. temp_val.XF = XFs[temp_val.ixfe];
  17988. if(options.cellFormula) {
  17989. var _f = val.formula;
  17990. if(_f && _f[0] && _f[0][0] && _f[0][0][0] == 'PtgExp') {
  17991. var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
  17992. var _fe = encode_cell({r:_fr, c:_fc});
  17993. if(sharedf[_fe]) temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  17994. else temp_val.F = ((options.dense ? (out[_fr]||[])[_fc]: out[_fe]) || {}).F;
  17995. } else temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  17996. }
  17997. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17998. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17999. addcell(val.cell, temp_val, options);
  18000. last_formula = val;
  18001. } break;
  18002. case 0x0007: case 0x0207 /* String */: {
  18003. if(last_formula) { /* technically always true */
  18004. last_formula.val = val;
  18005. temp_val = make_cell(val, last_formula.cell.ixfe, 's');
  18006. temp_val.XF = XFs[temp_val.ixfe];
  18007. if(options.cellFormula) {
  18008. temp_val.f = ""+stringify_formula(last_formula.formula, range, last_formula.cell, supbooks, opts);
  18009. }
  18010. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  18011. safe_format_xf(temp_val, options, wb.opts.Date1904);
  18012. addcell(last_formula.cell, temp_val, options);
  18013. last_formula = null;
  18014. } else throw new Error("String record expects Formula");
  18015. } break;
  18016. case 0x0021: case 0x0221 /* Array */: {
  18017. arrayf.push(val);
  18018. var _arraystart = encode_cell(val[0].s);
  18019. cc = options.dense ? (out[val[0].s.r]||[])[val[0].s.c] : out[_arraystart];
  18020. if(options.cellFormula && cc) {
  18021. if(!last_formula) break; /* technically unreachable */
  18022. if(!_arraystart || !cc) break;
  18023. cc.f = ""+stringify_formula(val[1], range, val[0], supbooks, opts);
  18024. cc.F = encode_range(val[0]);
  18025. }
  18026. } break;
  18027. case 0x04bc /* ShrFmla */: {
  18028. if(!options.cellFormula) break;
  18029. if(last_cell) {
  18030. /* TODO: capture range */
  18031. if(!last_formula) break; /* technically unreachable */
  18032. sharedf[encode_cell(last_formula.cell)]= val[0];
  18033. cc = options.dense ? (out[last_formula.cell.r]||[])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
  18034. (cc||{}).f = ""+stringify_formula(val[0], range, lastcell, supbooks, opts);
  18035. }
  18036. } break;
  18037. case 0x00fd /* LabelSst */:
  18038. temp_val=make_cell(sst[val.isst].t, val.ixfe, 's');
  18039. if(sst[val.isst].h) temp_val.h = sst[val.isst].h;
  18040. temp_val.XF = XFs[temp_val.ixfe];
  18041. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  18042. safe_format_xf(temp_val, options, wb.opts.Date1904);
  18043. addcell({c:val.c, r:val.r}, temp_val, options);
  18044. break;
  18045. case 0x0201 /* Blank */: if(options.sheetStubs) {
  18046. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], t:'z'});
  18047. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  18048. safe_format_xf(temp_val, options, wb.opts.Date1904);
  18049. addcell({c:val.c, r:val.r}, temp_val, options);
  18050. } break;
  18051. case 0x00be /* MulBlank */: if(options.sheetStubs) {
  18052. for(var _j = val.c; _j <= val.C; ++_j) {
  18053. var _ixfe = val.ixfe[_j-val.c];
  18054. temp_val= ({ixfe:_ixfe, XF:XFs[_ixfe], t:'z'});
  18055. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  18056. safe_format_xf(temp_val, options, wb.opts.Date1904);
  18057. addcell({c:_j, r:val.r}, temp_val, options);
  18058. }
  18059. } break;
  18060. case 0x00d6 /* RString */:
  18061. case 0x0204 /* Label */: case 0x0004 /* BIFF2STR */:
  18062. temp_val=make_cell(val.val, val.ixfe, 's');
  18063. temp_val.XF = XFs[temp_val.ixfe];
  18064. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  18065. safe_format_xf(temp_val, options, wb.opts.Date1904);
  18066. addcell({c:val.c, r:val.r}, temp_val, options);
  18067. break;
  18068. case 0x0000: case 0x0200 /* Dimensions */: {
  18069. if(file_depth === 1) range = val; /* TODO: stack */
  18070. } break;
  18071. case 0x00fc /* SST */: {
  18072. sst = val;
  18073. } break;
  18074. case 0x041e /* Format */: { /* val = [id, fmt] */
  18075. if(opts.biff == 4) {
  18076. BIFF2FmtTable[BIFF2Fmt++] = val[1];
  18077. for(var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if(table_fmt[b4idx] == val[1]) break;
  18078. if(b4idx >= 163) SSF__load(val[1], BIFF2Fmt + 163);
  18079. }
  18080. else SSF__load(val[1], val[0]);
  18081. } break;
  18082. case 0x001e /* BIFF2FORMAT */: {
  18083. BIFF2FmtTable[BIFF2Fmt++] = val;
  18084. for(var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if(table_fmt[b2idx] == val) break;
  18085. if(b2idx >= 163) SSF__load(val, BIFF2Fmt + 163);
  18086. } break;
  18087. case 0x00e5 /* MergeCells */: merges = merges.concat(val); break;
  18088. case 0x005d /* Obj */: objects[val.cmo[0]] = opts.lastobj = val; break;
  18089. case 0x01b6 /* TxO */: opts.lastobj.TxO = val; break;
  18090. case 0x007f /* ImData */: opts.lastobj.ImData = val; break;
  18091. case 0x01b8 /* HLink */: {
  18092. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  18093. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  18094. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  18095. if(cc) cc.l = val[1];
  18096. }
  18097. } break;
  18098. case 0x0800 /* HLinkTooltip */: {
  18099. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  18100. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  18101. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  18102. if(cc && cc.l) cc.l.Tooltip = val[1];
  18103. }
  18104. } break;
  18105. case 0x001c /* Note */: {
  18106. if(opts.biff <= 5 && opts.biff >= 2) break; /* TODO: BIFF5 */
  18107. cc = options.dense ? (out[val[0].r]||[])[val[0].c] : out[encode_cell(val[0])];
  18108. var noteobj = objects[val[2]];
  18109. if(!cc) {
  18110. if(options.dense) {
  18111. if(!out[val[0].r]) out[val[0].r] = [];
  18112. cc = out[val[0].r][val[0].c] = ({t:"z"});
  18113. } else {
  18114. cc = out[encode_cell(val[0])] = ({t:"z"});
  18115. }
  18116. range.e.r = Math.max(range.e.r, val[0].r);
  18117. range.s.r = Math.min(range.s.r, val[0].r);
  18118. range.e.c = Math.max(range.e.c, val[0].c);
  18119. range.s.c = Math.min(range.s.c, val[0].c);
  18120. }
  18121. if(!cc.c) cc.c = [];
  18122. cmnt = {a:val[1],t:noteobj.TxO.t};
  18123. cc.c.push(cmnt);
  18124. } break;
  18125. case 0x087d /* XFExt */: update_xfext(XFs[val.ixfe], val.ext); break;
  18126. case 0x007d /* ColInfo */: {
  18127. if(!opts.cellStyles) break;
  18128. while(val.e >= val.s) {
  18129. colinfo[val.e--] = { width: val.w/256, level: (val.level || 0), hidden: !!(val.flags & 1) };
  18130. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  18131. process_col(colinfo[val.e+1]);
  18132. }
  18133. } break;
  18134. case 0x0208 /* Row */: {
  18135. var rowobj = {};
  18136. if(val.level != null) { rowinfo[val.r] = rowobj; rowobj.level = val.level; }
  18137. if(val.hidden) { rowinfo[val.r] = rowobj; rowobj.hidden = true; }
  18138. if(val.hpt) {
  18139. rowinfo[val.r] = rowobj;
  18140. rowobj.hpt = val.hpt; rowobj.hpx = pt2px(val.hpt);
  18141. }
  18142. } break;
  18143. case 0x0026 /* LeftMargin */:
  18144. case 0x0027 /* RightMargin */:
  18145. case 0x0028 /* TopMargin */:
  18146. case 0x0029 /* BottomMargin */:
  18147. if(!out['!margins']) default_margins(out['!margins'] = {});
  18148. out['!margins'][({0x26: "left", 0x27:"right", 0x28:"top", 0x29:"bottom"})[RecordType]] = val;
  18149. break;
  18150. case 0x00a1 /* Setup */: // TODO
  18151. if(!out['!margins']) default_margins(out['!margins'] = {});
  18152. out['!margins'].header = val.header;
  18153. out['!margins'].footer = val.footer;
  18154. break;
  18155. case 0x023e /* Window2 */: // TODO
  18156. // $FlowIgnore
  18157. if(val.RTL) Workbook.Views[0].RTL = true;
  18158. break;
  18159. case 0x0092 /* Palette */: palette = val; break;
  18160. case 0x0896 /* Theme */: themes = val; break;
  18161. case 0x008c /* Country */: country = val; break;
  18162. case 0x01ba /* CodeName */: {
  18163. if(!cur_sheet) Workbook.WBProps.CodeName = val || "ThisWorkbook";
  18164. else wsprops.CodeName = val || wsprops.name;
  18165. } break;
  18166. }
  18167. } else {
  18168. if(!R) console.error("Missing Info for XLS Record 0x" + RecordType.toString(16));
  18169. blob.l += length;
  18170. }
  18171. }
  18172. wb.SheetNames=keys(Directory).sort(function(a,b) { return Number(a) - Number(b); }).map(function(x){return Directory[x].name;});
  18173. if(!options.bookSheets) wb.Sheets=Sheets;
  18174. if(!wb.SheetNames.length && Preamble["!ref"]) {
  18175. wb.SheetNames.push("Sheet1");
  18176. /*jshint -W069 */
  18177. if(wb.Sheets) wb.Sheets["Sheet1"] = Preamble;
  18178. /*jshint +W069 */
  18179. } else wb.Preamble=Preamble;
  18180. if(wb.Sheets) FilterDatabases.forEach(function(r,i) { wb.Sheets[wb.SheetNames[i]]['!autofilter'] = r; });
  18181. wb.Strings = sst;
  18182. wb.SSF = dup(table_fmt);
  18183. if(opts.enc) wb.Encryption = opts.enc;
  18184. if(themes) wb.Themes = themes;
  18185. wb.Metadata = {};
  18186. if(country !== undefined) wb.Metadata.Country = country;
  18187. if(supbooks.names.length > 0) Workbook.Names = supbooks.names;
  18188. wb.Workbook = Workbook;
  18189. return wb;
  18190. }
  18191. /* TODO: split props*/
  18192. var PSCLSID = {
  18193. SI: "e0859ff2f94f6810ab9108002b27b3d9",
  18194. DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
  18195. UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
  18196. };
  18197. function parse_xls_props(cfb, props, o) {
  18198. /* [MS-OSHARED] 2.3.3.2.2 Document Summary Information Property Set */
  18199. var DSI = CFB.find(cfb, '/!DocumentSummaryInformation');
  18200. if(DSI && DSI.size > 0) try {
  18201. var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
  18202. for(var d in DocSummary) props[d] = DocSummary[d];
  18203. } catch(e) {if(o.WTF) throw e;/* empty */}
  18204. /* [MS-OSHARED] 2.3.3.2.1 Summary Information Property Set*/
  18205. var SI = CFB.find(cfb, '/!SummaryInformation');
  18206. if(SI && SI.size > 0) try {
  18207. var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
  18208. for(var s in Summary) if(props[s] == null) props[s] = Summary[s];
  18209. } catch(e) {if(o.WTF) throw e;/* empty */}
  18210. if(props.HeadingPairs && props.TitlesOfParts) {
  18211. load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o);
  18212. delete props.HeadingPairs; delete props.TitlesOfParts;
  18213. }
  18214. }
  18215. function write_xls_props(wb, cfb) {
  18216. var DSEntries = [], SEntries = [], CEntries = [];
  18217. var i = 0, Keys;
  18218. var DocSummaryRE = evert_key(DocSummaryPIDDSI, "n");
  18219. var SummaryRE = evert_key(SummaryPIDSI, "n");
  18220. if(wb.Props) {
  18221. Keys = keys(wb.Props);
  18222. // $FlowIgnore
  18223. for(i = 0; i < Keys.length; ++i) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Props[Keys[i]]]);
  18224. }
  18225. if(wb.Custprops) {
  18226. Keys = keys(wb.Custprops);
  18227. // $FlowIgnore
  18228. for(i = 0; i < Keys.length; ++i) if(!Object.prototype.hasOwnProperty.call((wb.Props||{}), Keys[i])) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Custprops[Keys[i]]]);
  18229. }
  18230. var CEntries2 = [];
  18231. for(i = 0; i < CEntries.length; ++i) {
  18232. if(XLSPSSkip.indexOf(CEntries[i][0]) > -1 || PseudoPropsPairs.indexOf(CEntries[i][0]) > -1) continue;
  18233. if(CEntries[i][1] == null) continue;
  18234. CEntries2.push(CEntries[i]);
  18235. }
  18236. if(SEntries.length) CFB.utils.cfb_add(cfb, "/\u0005SummaryInformation", write_PropertySetStream(SEntries, PSCLSID.SI, SummaryRE, SummaryPIDSI));
  18237. if(DSEntries.length || CEntries2.length) CFB.utils.cfb_add(cfb, "/\u0005DocumentSummaryInformation", write_PropertySetStream(DSEntries, PSCLSID.DSI, DocSummaryRE, DocSummaryPIDDSI, CEntries2.length ? CEntries2 : null, PSCLSID.UDI));
  18238. }
  18239. function parse_xlscfb(cfb, options) {
  18240. if(!options) options = {};
  18241. fix_read_opts(options);
  18242. reset_cp();
  18243. if(options.codepage) set_ansi(options.codepage);
  18244. var CompObj, WB;
  18245. if(cfb.FullPaths) {
  18246. if(CFB.find(cfb, '/encryption')) throw new Error("File is password-protected");
  18247. CompObj = CFB.find(cfb, '!CompObj');
  18248. WB = CFB.find(cfb, '/Workbook') || CFB.find(cfb, '/Book');
  18249. } else {
  18250. switch(options.type) {
  18251. case 'base64': cfb = s2a(Base64_decode(cfb)); break;
  18252. case 'binary': cfb = s2a(cfb); break;
  18253. case 'buffer': break;
  18254. case 'array': if(!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb); break;
  18255. }
  18256. prep_blob(cfb, 0);
  18257. WB = ({content: cfb});
  18258. }
  18259. var WorkbookP;
  18260. var _data;
  18261. if(CompObj) parse_compobj(CompObj);
  18262. if(options.bookProps && !options.bookSheets) WorkbookP = ({});
  18263. else {
  18264. var T = has_buf ? 'buffer' : 'array';
  18265. if(WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
  18266. /* Quattro Pro 7-8 */
  18267. else if((_data=CFB.find(cfb, 'PerfectOffice_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  18268. /* Quattro Pro 9 */
  18269. else if((_data=CFB.find(cfb, 'NativeContent_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  18270. /* Works 4 for Mac */
  18271. else if((_data=CFB.find(cfb, 'MN0')) && _data.content) throw new Error("Unsupported Works 4 for Mac file");
  18272. else throw new Error("Cannot find Workbook stream");
  18273. if(options.bookVBA && cfb.FullPaths && CFB.find(cfb, '/_VBA_PROJECT_CUR/VBA/dir')) WorkbookP.vbaraw = make_vba_xls(cfb);
  18274. }
  18275. var props = {};
  18276. if(cfb.FullPaths) parse_xls_props(cfb, props, options);
  18277. WorkbookP.Props = WorkbookP.Custprops = props; /* TODO: split up properties */
  18278. if(options.bookFiles) WorkbookP.cfb = cfb;
  18279. /*WorkbookP.CompObjP = CompObjP; // TODO: storage? */
  18280. return WorkbookP;
  18281. }
  18282. function write_xlscfb(wb, opts) {
  18283. var o = opts || {};
  18284. var cfb = CFB.utils.cfb_new({root:"R"});
  18285. var wbpath = "/Workbook";
  18286. switch(o.bookType || "xls") {
  18287. case "xls": o.bookType = "biff8";
  18288. /* falls through */
  18289. case "xla": if(!o.bookType) o.bookType = "xla";
  18290. /* falls through */
  18291. case "biff8": wbpath = "/Workbook"; o.biff = 8; break;
  18292. case "biff5": wbpath = "/Book"; o.biff = 5; break;
  18293. default: throw new Error("invalid type " + o.bookType + " for XLS CFB");
  18294. }
  18295. CFB.utils.cfb_add(cfb, wbpath, write_biff_buf(wb, o));
  18296. if(o.biff == 8 && (wb.Props || wb.Custprops)) write_xls_props(wb, cfb);
  18297. // TODO: SI, DSI, CO
  18298. if(o.biff == 8 && wb.vbaraw) fill_vba_xls(cfb, CFB.read(wb.vbaraw, {type: typeof wb.vbaraw == "string" ? "binary" : "buffer"}));
  18299. return cfb;
  18300. }
  18301. /* [MS-XLSB] 2.3 Record Enumeration */
  18302. var XLSBRecordEnum = {
  18303. 0x0000: { /* n:"BrtRowHdr", */ f:parse_BrtRowHdr },
  18304. 0x0001: { /* n:"BrtCellBlank", */ f:parse_BrtCellBlank },
  18305. 0x0002: { /* n:"BrtCellRk", */ f:parse_BrtCellRk },
  18306. 0x0003: { /* n:"BrtCellError", */ f:parse_BrtCellError },
  18307. 0x0004: { /* n:"BrtCellBool", */ f:parse_BrtCellBool },
  18308. 0x0005: { /* n:"BrtCellReal", */ f:parse_BrtCellReal },
  18309. 0x0006: { /* n:"BrtCellSt", */ f:parse_BrtCellSt },
  18310. 0x0007: { /* n:"BrtCellIsst", */ f:parse_BrtCellIsst },
  18311. 0x0008: { /* n:"BrtFmlaString", */ f:parse_BrtFmlaString },
  18312. 0x0009: { /* n:"BrtFmlaNum", */ f:parse_BrtFmlaNum },
  18313. 0x000A: { /* n:"BrtFmlaBool", */ f:parse_BrtFmlaBool },
  18314. 0x000B: { /* n:"BrtFmlaError", */ f:parse_BrtFmlaError },
  18315. 0x000C: { /* n:"BrtShortBlank", */ f:parse_BrtShortBlank },
  18316. 0x000D: { /* n:"BrtShortRk", */ f:parse_BrtShortRk },
  18317. 0x000E: { /* n:"BrtShortError", */ f:parse_BrtShortError },
  18318. 0x000F: { /* n:"BrtShortBool", */ f:parse_BrtShortBool },
  18319. 0x0010: { /* n:"BrtShortReal", */ f:parse_BrtShortReal },
  18320. 0x0011: { /* n:"BrtShortSt", */ f:parse_BrtShortSt },
  18321. 0x0012: { /* n:"BrtShortIsst", */ f:parse_BrtShortIsst },
  18322. 0x0013: { /* n:"BrtSSTItem", */ f:parse_RichStr },
  18323. 0x0014: { /* n:"BrtPCDIMissing" */ },
  18324. 0x0015: { /* n:"BrtPCDINumber" */ },
  18325. 0x0016: { /* n:"BrtPCDIBoolean" */ },
  18326. 0x0017: { /* n:"BrtPCDIError" */ },
  18327. 0x0018: { /* n:"BrtPCDIString" */ },
  18328. 0x0019: { /* n:"BrtPCDIDatetime" */ },
  18329. 0x001A: { /* n:"BrtPCDIIndex" */ },
  18330. 0x001B: { /* n:"BrtPCDIAMissing" */ },
  18331. 0x001C: { /* n:"BrtPCDIANumber" */ },
  18332. 0x001D: { /* n:"BrtPCDIABoolean" */ },
  18333. 0x001E: { /* n:"BrtPCDIAError" */ },
  18334. 0x001F: { /* n:"BrtPCDIAString" */ },
  18335. 0x0020: { /* n:"BrtPCDIADatetime" */ },
  18336. 0x0021: { /* n:"BrtPCRRecord" */ },
  18337. 0x0022: { /* n:"BrtPCRRecordDt" */ },
  18338. 0x0023: { /* n:"BrtFRTBegin", */ T:1 },
  18339. 0x0024: { /* n:"BrtFRTEnd", */ T:-1 },
  18340. 0x0025: { /* n:"BrtACBegin", */ T:1 },
  18341. 0x0026: { /* n:"BrtACEnd", */ T:-1 },
  18342. 0x0027: { /* n:"BrtName", */ f:parse_BrtName },
  18343. 0x0028: { /* n:"BrtIndexRowBlock" */ },
  18344. 0x002A: { /* n:"BrtIndexBlock" */ },
  18345. 0x002B: { /* n:"BrtFont", */ f:parse_BrtFont },
  18346. 0x002C: { /* n:"BrtFmt", */ f:parse_BrtFmt },
  18347. 0x002D: { /* n:"BrtFill", */ f:parse_BrtFill },
  18348. 0x002E: { /* n:"BrtBorder", */ f:parse_BrtBorder },
  18349. 0x002F: { /* n:"BrtXF", */ f:parse_BrtXF },
  18350. 0x0030: { /* n:"BrtStyle" */ },
  18351. 0x0031: { /* n:"BrtCellMeta", */ f:parse_Int32LE },
  18352. 0x0032: { /* n:"BrtValueMeta" */ },
  18353. 0x0033: { /* n:"BrtMdb" */ f:parse_BrtMdb },
  18354. 0x0034: { /* n:"BrtBeginFmd", */ T:1 },
  18355. 0x0035: { /* n:"BrtEndFmd", */ T:-1 },
  18356. 0x0036: { /* n:"BrtBeginMdx", */ T:1 },
  18357. 0x0037: { /* n:"BrtEndMdx", */ T:-1 },
  18358. 0x0038: { /* n:"BrtBeginMdxTuple", */ T:1 },
  18359. 0x0039: { /* n:"BrtEndMdxTuple", */ T:-1 },
  18360. 0x003A: { /* n:"BrtMdxMbrIstr" */ },
  18361. 0x003B: { /* n:"BrtStr" */ },
  18362. 0x003C: { /* n:"BrtColInfo", */ f:parse_ColInfo },
  18363. 0x003E: { /* n:"BrtCellRString", */ f:parse_BrtCellRString },
  18364. 0x003F: { /* n:"BrtCalcChainItem$", */ f:parse_BrtCalcChainItem$ },
  18365. 0x0040: { /* n:"BrtDVal", */ f:parse_BrtDVal },
  18366. 0x0041: { /* n:"BrtSxvcellNum" */ },
  18367. 0x0042: { /* n:"BrtSxvcellStr" */ },
  18368. 0x0043: { /* n:"BrtSxvcellBool" */ },
  18369. 0x0044: { /* n:"BrtSxvcellErr" */ },
  18370. 0x0045: { /* n:"BrtSxvcellDate" */ },
  18371. 0x0046: { /* n:"BrtSxvcellNil" */ },
  18372. 0x0080: { /* n:"BrtFileVersion" */ },
  18373. 0x0081: { /* n:"BrtBeginSheet", */ T:1 },
  18374. 0x0082: { /* n:"BrtEndSheet", */ T:-1 },
  18375. 0x0083: { /* n:"BrtBeginBook", */ T:1, f:parsenoop, p:0 },
  18376. 0x0084: { /* n:"BrtEndBook", */ T:-1 },
  18377. 0x0085: { /* n:"BrtBeginWsViews", */ T:1 },
  18378. 0x0086: { /* n:"BrtEndWsViews", */ T:-1 },
  18379. 0x0087: { /* n:"BrtBeginBookViews", */ T:1 },
  18380. 0x0088: { /* n:"BrtEndBookViews", */ T:-1 },
  18381. 0x0089: { /* n:"BrtBeginWsView", */ T:1, f:parse_BrtBeginWsView },
  18382. 0x008A: { /* n:"BrtEndWsView", */ T:-1 },
  18383. 0x008B: { /* n:"BrtBeginCsViews", */ T:1 },
  18384. 0x008C: { /* n:"BrtEndCsViews", */ T:-1 },
  18385. 0x008D: { /* n:"BrtBeginCsView", */ T:1 },
  18386. 0x008E: { /* n:"BrtEndCsView", */ T:-1 },
  18387. 0x008F: { /* n:"BrtBeginBundleShs", */ T:1 },
  18388. 0x0090: { /* n:"BrtEndBundleShs", */ T:-1 },
  18389. 0x0091: { /* n:"BrtBeginSheetData", */ T:1 },
  18390. 0x0092: { /* n:"BrtEndSheetData", */ T:-1 },
  18391. 0x0093: { /* n:"BrtWsProp", */ f:parse_BrtWsProp },
  18392. 0x0094: { /* n:"BrtWsDim", */ f:parse_BrtWsDim, p:16 },
  18393. 0x0097: { /* n:"BrtPane", */ f:parse_BrtPane },
  18394. 0x0098: { /* n:"BrtSel" */ },
  18395. 0x0099: { /* n:"BrtWbProp", */ f:parse_BrtWbProp },
  18396. 0x009A: { /* n:"BrtWbFactoid" */ },
  18397. 0x009B: { /* n:"BrtFileRecover" */ },
  18398. 0x009C: { /* n:"BrtBundleSh", */ f:parse_BrtBundleSh },
  18399. 0x009D: { /* n:"BrtCalcProp" */ },
  18400. 0x009E: { /* n:"BrtBookView" */ },
  18401. 0x009F: { /* n:"BrtBeginSst", */ T:1, f:parse_BrtBeginSst },
  18402. 0x00A0: { /* n:"BrtEndSst", */ T:-1 },
  18403. 0x00A1: { /* n:"BrtBeginAFilter", */ T:1, f:parse_UncheckedRfX },
  18404. 0x00A2: { /* n:"BrtEndAFilter", */ T:-1 },
  18405. 0x00A3: { /* n:"BrtBeginFilterColumn", */ T:1 },
  18406. 0x00A4: { /* n:"BrtEndFilterColumn", */ T:-1 },
  18407. 0x00A5: { /* n:"BrtBeginFilters", */ T:1 },
  18408. 0x00A6: { /* n:"BrtEndFilters", */ T:-1 },
  18409. 0x00A7: { /* n:"BrtFilter" */ },
  18410. 0x00A8: { /* n:"BrtColorFilter" */ },
  18411. 0x00A9: { /* n:"BrtIconFilter" */ },
  18412. 0x00AA: { /* n:"BrtTop10Filter" */ },
  18413. 0x00AB: { /* n:"BrtDynamicFilter" */ },
  18414. 0x00AC: { /* n:"BrtBeginCustomFilters", */ T:1 },
  18415. 0x00AD: { /* n:"BrtEndCustomFilters", */ T:-1 },
  18416. 0x00AE: { /* n:"BrtCustomFilter" */ },
  18417. 0x00AF: { /* n:"BrtAFilterDateGroupItem" */ },
  18418. 0x00B0: { /* n:"BrtMergeCell", */ f:parse_BrtMergeCell },
  18419. 0x00B1: { /* n:"BrtBeginMergeCells", */ T:1 },
  18420. 0x00B2: { /* n:"BrtEndMergeCells", */ T:-1 },
  18421. 0x00B3: { /* n:"BrtBeginPivotCacheDef", */ T:1 },
  18422. 0x00B4: { /* n:"BrtEndPivotCacheDef", */ T:-1 },
  18423. 0x00B5: { /* n:"BrtBeginPCDFields", */ T:1 },
  18424. 0x00B6: { /* n:"BrtEndPCDFields", */ T:-1 },
  18425. 0x00B7: { /* n:"BrtBeginPCDField", */ T:1 },
  18426. 0x00B8: { /* n:"BrtEndPCDField", */ T:-1 },
  18427. 0x00B9: { /* n:"BrtBeginPCDSource", */ T:1 },
  18428. 0x00BA: { /* n:"BrtEndPCDSource", */ T:-1 },
  18429. 0x00BB: { /* n:"BrtBeginPCDSRange", */ T:1 },
  18430. 0x00BC: { /* n:"BrtEndPCDSRange", */ T:-1 },
  18431. 0x00BD: { /* n:"BrtBeginPCDFAtbl", */ T:1 },
  18432. 0x00BE: { /* n:"BrtEndPCDFAtbl", */ T:-1 },
  18433. 0x00BF: { /* n:"BrtBeginPCDIRun", */ T:1 },
  18434. 0x00C0: { /* n:"BrtEndPCDIRun", */ T:-1 },
  18435. 0x00C1: { /* n:"BrtBeginPivotCacheRecords", */ T:1 },
  18436. 0x00C2: { /* n:"BrtEndPivotCacheRecords", */ T:-1 },
  18437. 0x00C3: { /* n:"BrtBeginPCDHierarchies", */ T:1 },
  18438. 0x00C4: { /* n:"BrtEndPCDHierarchies", */ T:-1 },
  18439. 0x00C5: { /* n:"BrtBeginPCDHierarchy", */ T:1 },
  18440. 0x00C6: { /* n:"BrtEndPCDHierarchy", */ T:-1 },
  18441. 0x00C7: { /* n:"BrtBeginPCDHFieldsUsage", */ T:1 },
  18442. 0x00C8: { /* n:"BrtEndPCDHFieldsUsage", */ T:-1 },
  18443. 0x00C9: { /* n:"BrtBeginExtConnection", */ T:1 },
  18444. 0x00CA: { /* n:"BrtEndExtConnection", */ T:-1 },
  18445. 0x00CB: { /* n:"BrtBeginECDbProps", */ T:1 },
  18446. 0x00CC: { /* n:"BrtEndECDbProps", */ T:-1 },
  18447. 0x00CD: { /* n:"BrtBeginECOlapProps", */ T:1 },
  18448. 0x00CE: { /* n:"BrtEndECOlapProps", */ T:-1 },
  18449. 0x00CF: { /* n:"BrtBeginPCDSConsol", */ T:1 },
  18450. 0x00D0: { /* n:"BrtEndPCDSConsol", */ T:-1 },
  18451. 0x00D1: { /* n:"BrtBeginPCDSCPages", */ T:1 },
  18452. 0x00D2: { /* n:"BrtEndPCDSCPages", */ T:-1 },
  18453. 0x00D3: { /* n:"BrtBeginPCDSCPage", */ T:1 },
  18454. 0x00D4: { /* n:"BrtEndPCDSCPage", */ T:-1 },
  18455. 0x00D5: { /* n:"BrtBeginPCDSCPItem", */ T:1 },
  18456. 0x00D6: { /* n:"BrtEndPCDSCPItem", */ T:-1 },
  18457. 0x00D7: { /* n:"BrtBeginPCDSCSets", */ T:1 },
  18458. 0x00D8: { /* n:"BrtEndPCDSCSets", */ T:-1 },
  18459. 0x00D9: { /* n:"BrtBeginPCDSCSet", */ T:1 },
  18460. 0x00DA: { /* n:"BrtEndPCDSCSet", */ T:-1 },
  18461. 0x00DB: { /* n:"BrtBeginPCDFGroup", */ T:1 },
  18462. 0x00DC: { /* n:"BrtEndPCDFGroup", */ T:-1 },
  18463. 0x00DD: { /* n:"BrtBeginPCDFGItems", */ T:1 },
  18464. 0x00DE: { /* n:"BrtEndPCDFGItems", */ T:-1 },
  18465. 0x00DF: { /* n:"BrtBeginPCDFGRange", */ T:1 },
  18466. 0x00E0: { /* n:"BrtEndPCDFGRange", */ T:-1 },
  18467. 0x00E1: { /* n:"BrtBeginPCDFGDiscrete", */ T:1 },
  18468. 0x00E2: { /* n:"BrtEndPCDFGDiscrete", */ T:-1 },
  18469. 0x00E3: { /* n:"BrtBeginPCDSDTupleCache", */ T:1 },
  18470. 0x00E4: { /* n:"BrtEndPCDSDTupleCache", */ T:-1 },
  18471. 0x00E5: { /* n:"BrtBeginPCDSDTCEntries", */ T:1 },
  18472. 0x00E6: { /* n:"BrtEndPCDSDTCEntries", */ T:-1 },
  18473. 0x00E7: { /* n:"BrtBeginPCDSDTCEMembers", */ T:1 },
  18474. 0x00E8: { /* n:"BrtEndPCDSDTCEMembers", */ T:-1 },
  18475. 0x00E9: { /* n:"BrtBeginPCDSDTCEMember", */ T:1 },
  18476. 0x00EA: { /* n:"BrtEndPCDSDTCEMember", */ T:-1 },
  18477. 0x00EB: { /* n:"BrtBeginPCDSDTCQueries", */ T:1 },
  18478. 0x00EC: { /* n:"BrtEndPCDSDTCQueries", */ T:-1 },
  18479. 0x00ED: { /* n:"BrtBeginPCDSDTCQuery", */ T:1 },
  18480. 0x00EE: { /* n:"BrtEndPCDSDTCQuery", */ T:-1 },
  18481. 0x00EF: { /* n:"BrtBeginPCDSDTCSets", */ T:1 },
  18482. 0x00F0: { /* n:"BrtEndPCDSDTCSets", */ T:-1 },
  18483. 0x00F1: { /* n:"BrtBeginPCDSDTCSet", */ T:1 },
  18484. 0x00F2: { /* n:"BrtEndPCDSDTCSet", */ T:-1 },
  18485. 0x00F3: { /* n:"BrtBeginPCDCalcItems", */ T:1 },
  18486. 0x00F4: { /* n:"BrtEndPCDCalcItems", */ T:-1 },
  18487. 0x00F5: { /* n:"BrtBeginPCDCalcItem", */ T:1 },
  18488. 0x00F6: { /* n:"BrtEndPCDCalcItem", */ T:-1 },
  18489. 0x00F7: { /* n:"BrtBeginPRule", */ T:1 },
  18490. 0x00F8: { /* n:"BrtEndPRule", */ T:-1 },
  18491. 0x00F9: { /* n:"BrtBeginPRFilters", */ T:1 },
  18492. 0x00FA: { /* n:"BrtEndPRFilters", */ T:-1 },
  18493. 0x00FB: { /* n:"BrtBeginPRFilter", */ T:1 },
  18494. 0x00FC: { /* n:"BrtEndPRFilter", */ T:-1 },
  18495. 0x00FD: { /* n:"BrtBeginPNames", */ T:1 },
  18496. 0x00FE: { /* n:"BrtEndPNames", */ T:-1 },
  18497. 0x00FF: { /* n:"BrtBeginPName", */ T:1 },
  18498. 0x0100: { /* n:"BrtEndPName", */ T:-1 },
  18499. 0x0101: { /* n:"BrtBeginPNPairs", */ T:1 },
  18500. 0x0102: { /* n:"BrtEndPNPairs", */ T:-1 },
  18501. 0x0103: { /* n:"BrtBeginPNPair", */ T:1 },
  18502. 0x0104: { /* n:"BrtEndPNPair", */ T:-1 },
  18503. 0x0105: { /* n:"BrtBeginECWebProps", */ T:1 },
  18504. 0x0106: { /* n:"BrtEndECWebProps", */ T:-1 },
  18505. 0x0107: { /* n:"BrtBeginEcWpTables", */ T:1 },
  18506. 0x0108: { /* n:"BrtEndECWPTables", */ T:-1 },
  18507. 0x0109: { /* n:"BrtBeginECParams", */ T:1 },
  18508. 0x010A: { /* n:"BrtEndECParams", */ T:-1 },
  18509. 0x010B: { /* n:"BrtBeginECParam", */ T:1 },
  18510. 0x010C: { /* n:"BrtEndECParam", */ T:-1 },
  18511. 0x010D: { /* n:"BrtBeginPCDKPIs", */ T:1 },
  18512. 0x010E: { /* n:"BrtEndPCDKPIs", */ T:-1 },
  18513. 0x010F: { /* n:"BrtBeginPCDKPI", */ T:1 },
  18514. 0x0110: { /* n:"BrtEndPCDKPI", */ T:-1 },
  18515. 0x0111: { /* n:"BrtBeginDims", */ T:1 },
  18516. 0x0112: { /* n:"BrtEndDims", */ T:-1 },
  18517. 0x0113: { /* n:"BrtBeginDim", */ T:1 },
  18518. 0x0114: { /* n:"BrtEndDim", */ T:-1 },
  18519. 0x0115: { /* n:"BrtIndexPartEnd" */ },
  18520. 0x0116: { /* n:"BrtBeginStyleSheet", */ T:1 },
  18521. 0x0117: { /* n:"BrtEndStyleSheet", */ T:-1 },
  18522. 0x0118: { /* n:"BrtBeginSXView", */ T:1 },
  18523. 0x0119: { /* n:"BrtEndSXVI", */ T:-1 },
  18524. 0x011A: { /* n:"BrtBeginSXVI", */ T:1 },
  18525. 0x011B: { /* n:"BrtBeginSXVIs", */ T:1 },
  18526. 0x011C: { /* n:"BrtEndSXVIs", */ T:-1 },
  18527. 0x011D: { /* n:"BrtBeginSXVD", */ T:1 },
  18528. 0x011E: { /* n:"BrtEndSXVD", */ T:-1 },
  18529. 0x011F: { /* n:"BrtBeginSXVDs", */ T:1 },
  18530. 0x0120: { /* n:"BrtEndSXVDs", */ T:-1 },
  18531. 0x0121: { /* n:"BrtBeginSXPI", */ T:1 },
  18532. 0x0122: { /* n:"BrtEndSXPI", */ T:-1 },
  18533. 0x0123: { /* n:"BrtBeginSXPIs", */ T:1 },
  18534. 0x0124: { /* n:"BrtEndSXPIs", */ T:-1 },
  18535. 0x0125: { /* n:"BrtBeginSXDI", */ T:1 },
  18536. 0x0126: { /* n:"BrtEndSXDI", */ T:-1 },
  18537. 0x0127: { /* n:"BrtBeginSXDIs", */ T:1 },
  18538. 0x0128: { /* n:"BrtEndSXDIs", */ T:-1 },
  18539. 0x0129: { /* n:"BrtBeginSXLI", */ T:1 },
  18540. 0x012A: { /* n:"BrtEndSXLI", */ T:-1 },
  18541. 0x012B: { /* n:"BrtBeginSXLIRws", */ T:1 },
  18542. 0x012C: { /* n:"BrtEndSXLIRws", */ T:-1 },
  18543. 0x012D: { /* n:"BrtBeginSXLICols", */ T:1 },
  18544. 0x012E: { /* n:"BrtEndSXLICols", */ T:-1 },
  18545. 0x012F: { /* n:"BrtBeginSXFormat", */ T:1 },
  18546. 0x0130: { /* n:"BrtEndSXFormat", */ T:-1 },
  18547. 0x0131: { /* n:"BrtBeginSXFormats", */ T:1 },
  18548. 0x0132: { /* n:"BrtEndSxFormats", */ T:-1 },
  18549. 0x0133: { /* n:"BrtBeginSxSelect", */ T:1 },
  18550. 0x0134: { /* n:"BrtEndSxSelect", */ T:-1 },
  18551. 0x0135: { /* n:"BrtBeginISXVDRws", */ T:1 },
  18552. 0x0136: { /* n:"BrtEndISXVDRws", */ T:-1 },
  18553. 0x0137: { /* n:"BrtBeginISXVDCols", */ T:1 },
  18554. 0x0138: { /* n:"BrtEndISXVDCols", */ T:-1 },
  18555. 0x0139: { /* n:"BrtEndSXLocation", */ T:-1 },
  18556. 0x013A: { /* n:"BrtBeginSXLocation", */ T:1 },
  18557. 0x013B: { /* n:"BrtEndSXView", */ T:-1 },
  18558. 0x013C: { /* n:"BrtBeginSXTHs", */ T:1 },
  18559. 0x013D: { /* n:"BrtEndSXTHs", */ T:-1 },
  18560. 0x013E: { /* n:"BrtBeginSXTH", */ T:1 },
  18561. 0x013F: { /* n:"BrtEndSXTH", */ T:-1 },
  18562. 0x0140: { /* n:"BrtBeginISXTHRws", */ T:1 },
  18563. 0x0141: { /* n:"BrtEndISXTHRws", */ T:-1 },
  18564. 0x0142: { /* n:"BrtBeginISXTHCols", */ T:1 },
  18565. 0x0143: { /* n:"BrtEndISXTHCols", */ T:-1 },
  18566. 0x0144: { /* n:"BrtBeginSXTDMPS", */ T:1 },
  18567. 0x0145: { /* n:"BrtEndSXTDMPs", */ T:-1 },
  18568. 0x0146: { /* n:"BrtBeginSXTDMP", */ T:1 },
  18569. 0x0147: { /* n:"BrtEndSXTDMP", */ T:-1 },
  18570. 0x0148: { /* n:"BrtBeginSXTHItems", */ T:1 },
  18571. 0x0149: { /* n:"BrtEndSXTHItems", */ T:-1 },
  18572. 0x014A: { /* n:"BrtBeginSXTHItem", */ T:1 },
  18573. 0x014B: { /* n:"BrtEndSXTHItem", */ T:-1 },
  18574. 0x014C: { /* n:"BrtBeginMetadata", */ T:1 },
  18575. 0x014D: { /* n:"BrtEndMetadata", */ T:-1 },
  18576. 0x014E: { /* n:"BrtBeginEsmdtinfo", */ T:1 },
  18577. 0x014F: { /* n:"BrtMdtinfo", */ f:parse_BrtMdtinfo },
  18578. 0x0150: { /* n:"BrtEndEsmdtinfo", */ T:-1 },
  18579. 0x0151: { /* n:"BrtBeginEsmdb", */ f:parse_BrtBeginEsmdb, T:1 },
  18580. 0x0152: { /* n:"BrtEndEsmdb", */ T:-1 },
  18581. 0x0153: { /* n:"BrtBeginEsfmd", */ T:1 },
  18582. 0x0154: { /* n:"BrtEndEsfmd", */ T:-1 },
  18583. 0x0155: { /* n:"BrtBeginSingleCells", */ T:1 },
  18584. 0x0156: { /* n:"BrtEndSingleCells", */ T:-1 },
  18585. 0x0157: { /* n:"BrtBeginList", */ T:1 },
  18586. 0x0158: { /* n:"BrtEndList", */ T:-1 },
  18587. 0x0159: { /* n:"BrtBeginListCols", */ T:1 },
  18588. 0x015A: { /* n:"BrtEndListCols", */ T:-1 },
  18589. 0x015B: { /* n:"BrtBeginListCol", */ T:1 },
  18590. 0x015C: { /* n:"BrtEndListCol", */ T:-1 },
  18591. 0x015D: { /* n:"BrtBeginListXmlCPr", */ T:1 },
  18592. 0x015E: { /* n:"BrtEndListXmlCPr", */ T:-1 },
  18593. 0x015F: { /* n:"BrtListCCFmla" */ },
  18594. 0x0160: { /* n:"BrtListTrFmla" */ },
  18595. 0x0161: { /* n:"BrtBeginExternals", */ T:1 },
  18596. 0x0162: { /* n:"BrtEndExternals", */ T:-1 },
  18597. 0x0163: { /* n:"BrtSupBookSrc", */ f:parse_RelID},
  18598. 0x0165: { /* n:"BrtSupSelf" */ },
  18599. 0x0166: { /* n:"BrtSupSame" */ },
  18600. 0x0167: { /* n:"BrtSupTabs" */ },
  18601. 0x0168: { /* n:"BrtBeginSupBook", */ T:1 },
  18602. 0x0169: { /* n:"BrtPlaceholderName" */ },
  18603. 0x016A: { /* n:"BrtExternSheet", */ f:parse_ExternSheet },
  18604. 0x016B: { /* n:"BrtExternTableStart" */ },
  18605. 0x016C: { /* n:"BrtExternTableEnd" */ },
  18606. 0x016E: { /* n:"BrtExternRowHdr" */ },
  18607. 0x016F: { /* n:"BrtExternCellBlank" */ },
  18608. 0x0170: { /* n:"BrtExternCellReal" */ },
  18609. 0x0171: { /* n:"BrtExternCellBool" */ },
  18610. 0x0172: { /* n:"BrtExternCellError" */ },
  18611. 0x0173: { /* n:"BrtExternCellString" */ },
  18612. 0x0174: { /* n:"BrtBeginEsmdx", */ T:1 },
  18613. 0x0175: { /* n:"BrtEndEsmdx", */ T:-1 },
  18614. 0x0176: { /* n:"BrtBeginMdxSet", */ T:1 },
  18615. 0x0177: { /* n:"BrtEndMdxSet", */ T:-1 },
  18616. 0x0178: { /* n:"BrtBeginMdxMbrProp", */ T:1 },
  18617. 0x0179: { /* n:"BrtEndMdxMbrProp", */ T:-1 },
  18618. 0x017A: { /* n:"BrtBeginMdxKPI", */ T:1 },
  18619. 0x017B: { /* n:"BrtEndMdxKPI", */ T:-1 },
  18620. 0x017C: { /* n:"BrtBeginEsstr", */ T:1 },
  18621. 0x017D: { /* n:"BrtEndEsstr", */ T:-1 },
  18622. 0x017E: { /* n:"BrtBeginPRFItem", */ T:1 },
  18623. 0x017F: { /* n:"BrtEndPRFItem", */ T:-1 },
  18624. 0x0180: { /* n:"BrtBeginPivotCacheIDs", */ T:1 },
  18625. 0x0181: { /* n:"BrtEndPivotCacheIDs", */ T:-1 },
  18626. 0x0182: { /* n:"BrtBeginPivotCacheID", */ T:1 },
  18627. 0x0183: { /* n:"BrtEndPivotCacheID", */ T:-1 },
  18628. 0x0184: { /* n:"BrtBeginISXVIs", */ T:1 },
  18629. 0x0185: { /* n:"BrtEndISXVIs", */ T:-1 },
  18630. 0x0186: { /* n:"BrtBeginColInfos", */ T:1 },
  18631. 0x0187: { /* n:"BrtEndColInfos", */ T:-1 },
  18632. 0x0188: { /* n:"BrtBeginRwBrk", */ T:1 },
  18633. 0x0189: { /* n:"BrtEndRwBrk", */ T:-1 },
  18634. 0x018A: { /* n:"BrtBeginColBrk", */ T:1 },
  18635. 0x018B: { /* n:"BrtEndColBrk", */ T:-1 },
  18636. 0x018C: { /* n:"BrtBrk" */ },
  18637. 0x018D: { /* n:"BrtUserBookView" */ },
  18638. 0x018E: { /* n:"BrtInfo" */ },
  18639. 0x018F: { /* n:"BrtCUsr" */ },
  18640. 0x0190: { /* n:"BrtUsr" */ },
  18641. 0x0191: { /* n:"BrtBeginUsers", */ T:1 },
  18642. 0x0193: { /* n:"BrtEOF" */ },
  18643. 0x0194: { /* n:"BrtUCR" */ },
  18644. 0x0195: { /* n:"BrtRRInsDel" */ },
  18645. 0x0196: { /* n:"BrtRREndInsDel" */ },
  18646. 0x0197: { /* n:"BrtRRMove" */ },
  18647. 0x0198: { /* n:"BrtRREndMove" */ },
  18648. 0x0199: { /* n:"BrtRRChgCell" */ },
  18649. 0x019A: { /* n:"BrtRREndChgCell" */ },
  18650. 0x019B: { /* n:"BrtRRHeader" */ },
  18651. 0x019C: { /* n:"BrtRRUserView" */ },
  18652. 0x019D: { /* n:"BrtRRRenSheet" */ },
  18653. 0x019E: { /* n:"BrtRRInsertSh" */ },
  18654. 0x019F: { /* n:"BrtRRDefName" */ },
  18655. 0x01A0: { /* n:"BrtRRNote" */ },
  18656. 0x01A1: { /* n:"BrtRRConflict" */ },
  18657. 0x01A2: { /* n:"BrtRRTQSIF" */ },
  18658. 0x01A3: { /* n:"BrtRRFormat" */ },
  18659. 0x01A4: { /* n:"BrtRREndFormat" */ },
  18660. 0x01A5: { /* n:"BrtRRAutoFmt" */ },
  18661. 0x01A6: { /* n:"BrtBeginUserShViews", */ T:1 },
  18662. 0x01A7: { /* n:"BrtBeginUserShView", */ T:1 },
  18663. 0x01A8: { /* n:"BrtEndUserShView", */ T:-1 },
  18664. 0x01A9: { /* n:"BrtEndUserShViews", */ T:-1 },
  18665. 0x01AA: { /* n:"BrtArrFmla", */ f:parse_BrtArrFmla },
  18666. 0x01AB: { /* n:"BrtShrFmla", */ f:parse_BrtShrFmla },
  18667. 0x01AC: { /* n:"BrtTable" */ },
  18668. 0x01AD: { /* n:"BrtBeginExtConnections", */ T:1 },
  18669. 0x01AE: { /* n:"BrtEndExtConnections", */ T:-1 },
  18670. 0x01AF: { /* n:"BrtBeginPCDCalcMems", */ T:1 },
  18671. 0x01B0: { /* n:"BrtEndPCDCalcMems", */ T:-1 },
  18672. 0x01B1: { /* n:"BrtBeginPCDCalcMem", */ T:1 },
  18673. 0x01B2: { /* n:"BrtEndPCDCalcMem", */ T:-1 },
  18674. 0x01B3: { /* n:"BrtBeginPCDHGLevels", */ T:1 },
  18675. 0x01B4: { /* n:"BrtEndPCDHGLevels", */ T:-1 },
  18676. 0x01B5: { /* n:"BrtBeginPCDHGLevel", */ T:1 },
  18677. 0x01B6: { /* n:"BrtEndPCDHGLevel", */ T:-1 },
  18678. 0x01B7: { /* n:"BrtBeginPCDHGLGroups", */ T:1 },
  18679. 0x01B8: { /* n:"BrtEndPCDHGLGroups", */ T:-1 },
  18680. 0x01B9: { /* n:"BrtBeginPCDHGLGroup", */ T:1 },
  18681. 0x01BA: { /* n:"BrtEndPCDHGLGroup", */ T:-1 },
  18682. 0x01BB: { /* n:"BrtBeginPCDHGLGMembers", */ T:1 },
  18683. 0x01BC: { /* n:"BrtEndPCDHGLGMembers", */ T:-1 },
  18684. 0x01BD: { /* n:"BrtBeginPCDHGLGMember", */ T:1 },
  18685. 0x01BE: { /* n:"BrtEndPCDHGLGMember", */ T:-1 },
  18686. 0x01BF: { /* n:"BrtBeginQSI", */ T:1 },
  18687. 0x01C0: { /* n:"BrtEndQSI", */ T:-1 },
  18688. 0x01C1: { /* n:"BrtBeginQSIR", */ T:1 },
  18689. 0x01C2: { /* n:"BrtEndQSIR", */ T:-1 },
  18690. 0x01C3: { /* n:"BrtBeginDeletedNames", */ T:1 },
  18691. 0x01C4: { /* n:"BrtEndDeletedNames", */ T:-1 },
  18692. 0x01C5: { /* n:"BrtBeginDeletedName", */ T:1 },
  18693. 0x01C6: { /* n:"BrtEndDeletedName", */ T:-1 },
  18694. 0x01C7: { /* n:"BrtBeginQSIFs", */ T:1 },
  18695. 0x01C8: { /* n:"BrtEndQSIFs", */ T:-1 },
  18696. 0x01C9: { /* n:"BrtBeginQSIF", */ T:1 },
  18697. 0x01CA: { /* n:"BrtEndQSIF", */ T:-1 },
  18698. 0x01CB: { /* n:"BrtBeginAutoSortScope", */ T:1 },
  18699. 0x01CC: { /* n:"BrtEndAutoSortScope", */ T:-1 },
  18700. 0x01CD: { /* n:"BrtBeginConditionalFormatting", */ T:1 },
  18701. 0x01CE: { /* n:"BrtEndConditionalFormatting", */ T:-1 },
  18702. 0x01CF: { /* n:"BrtBeginCFRule", */ T:1 },
  18703. 0x01D0: { /* n:"BrtEndCFRule", */ T:-1 },
  18704. 0x01D1: { /* n:"BrtBeginIconSet", */ T:1 },
  18705. 0x01D2: { /* n:"BrtEndIconSet", */ T:-1 },
  18706. 0x01D3: { /* n:"BrtBeginDatabar", */ T:1 },
  18707. 0x01D4: { /* n:"BrtEndDatabar", */ T:-1 },
  18708. 0x01D5: { /* n:"BrtBeginColorScale", */ T:1 },
  18709. 0x01D6: { /* n:"BrtEndColorScale", */ T:-1 },
  18710. 0x01D7: { /* n:"BrtCFVO" */ },
  18711. 0x01D8: { /* n:"BrtExternValueMeta" */ },
  18712. 0x01D9: { /* n:"BrtBeginColorPalette", */ T:1 },
  18713. 0x01DA: { /* n:"BrtEndColorPalette", */ T:-1 },
  18714. 0x01DB: { /* n:"BrtIndexedColor" */ },
  18715. 0x01DC: { /* n:"BrtMargins", */ f:parse_BrtMargins },
  18716. 0x01DD: { /* n:"BrtPrintOptions" */ },
  18717. 0x01DE: { /* n:"BrtPageSetup" */ },
  18718. 0x01DF: { /* n:"BrtBeginHeaderFooter", */ T:1 },
  18719. 0x01E0: { /* n:"BrtEndHeaderFooter", */ T:-1 },
  18720. 0x01E1: { /* n:"BrtBeginSXCrtFormat", */ T:1 },
  18721. 0x01E2: { /* n:"BrtEndSXCrtFormat", */ T:-1 },
  18722. 0x01E3: { /* n:"BrtBeginSXCrtFormats", */ T:1 },
  18723. 0x01E4: { /* n:"BrtEndSXCrtFormats", */ T:-1 },
  18724. 0x01E5: { /* n:"BrtWsFmtInfo", */ f:parse_BrtWsFmtInfo },
  18725. 0x01E6: { /* n:"BrtBeginMgs", */ T:1 },
  18726. 0x01E7: { /* n:"BrtEndMGs", */ T:-1 },
  18727. 0x01E8: { /* n:"BrtBeginMGMaps", */ T:1 },
  18728. 0x01E9: { /* n:"BrtEndMGMaps", */ T:-1 },
  18729. 0x01EA: { /* n:"BrtBeginMG", */ T:1 },
  18730. 0x01EB: { /* n:"BrtEndMG", */ T:-1 },
  18731. 0x01EC: { /* n:"BrtBeginMap", */ T:1 },
  18732. 0x01ED: { /* n:"BrtEndMap", */ T:-1 },
  18733. 0x01EE: { /* n:"BrtHLink", */ f:parse_BrtHLink },
  18734. 0x01EF: { /* n:"BrtBeginDCon", */ T:1 },
  18735. 0x01F0: { /* n:"BrtEndDCon", */ T:-1 },
  18736. 0x01F1: { /* n:"BrtBeginDRefs", */ T:1 },
  18737. 0x01F2: { /* n:"BrtEndDRefs", */ T:-1 },
  18738. 0x01F3: { /* n:"BrtDRef" */ },
  18739. 0x01F4: { /* n:"BrtBeginScenMan", */ T:1 },
  18740. 0x01F5: { /* n:"BrtEndScenMan", */ T:-1 },
  18741. 0x01F6: { /* n:"BrtBeginSct", */ T:1 },
  18742. 0x01F7: { /* n:"BrtEndSct", */ T:-1 },
  18743. 0x01F8: { /* n:"BrtSlc" */ },
  18744. 0x01F9: { /* n:"BrtBeginDXFs", */ T:1 },
  18745. 0x01FA: { /* n:"BrtEndDXFs", */ T:-1 },
  18746. 0x01FB: { /* n:"BrtDXF" */ },
  18747. 0x01FC: { /* n:"BrtBeginTableStyles", */ T:1 },
  18748. 0x01FD: { /* n:"BrtEndTableStyles", */ T:-1 },
  18749. 0x01FE: { /* n:"BrtBeginTableStyle", */ T:1 },
  18750. 0x01FF: { /* n:"BrtEndTableStyle", */ T:-1 },
  18751. 0x0200: { /* n:"BrtTableStyleElement" */ },
  18752. 0x0201: { /* n:"BrtTableStyleClient" */ },
  18753. 0x0202: { /* n:"BrtBeginVolDeps", */ T:1 },
  18754. 0x0203: { /* n:"BrtEndVolDeps", */ T:-1 },
  18755. 0x0204: { /* n:"BrtBeginVolType", */ T:1 },
  18756. 0x0205: { /* n:"BrtEndVolType", */ T:-1 },
  18757. 0x0206: { /* n:"BrtBeginVolMain", */ T:1 },
  18758. 0x0207: { /* n:"BrtEndVolMain", */ T:-1 },
  18759. 0x0208: { /* n:"BrtBeginVolTopic", */ T:1 },
  18760. 0x0209: { /* n:"BrtEndVolTopic", */ T:-1 },
  18761. 0x020A: { /* n:"BrtVolSubtopic" */ },
  18762. 0x020B: { /* n:"BrtVolRef" */ },
  18763. 0x020C: { /* n:"BrtVolNum" */ },
  18764. 0x020D: { /* n:"BrtVolErr" */ },
  18765. 0x020E: { /* n:"BrtVolStr" */ },
  18766. 0x020F: { /* n:"BrtVolBool" */ },
  18767. 0x0210: { /* n:"BrtBeginCalcChain$", */ T:1 },
  18768. 0x0211: { /* n:"BrtEndCalcChain$", */ T:-1 },
  18769. 0x0212: { /* n:"BrtBeginSortState", */ T:1 },
  18770. 0x0213: { /* n:"BrtEndSortState", */ T:-1 },
  18771. 0x0214: { /* n:"BrtBeginSortCond", */ T:1 },
  18772. 0x0215: { /* n:"BrtEndSortCond", */ T:-1 },
  18773. 0x0216: { /* n:"BrtBookProtection" */ },
  18774. 0x0217: { /* n:"BrtSheetProtection" */ },
  18775. 0x0218: { /* n:"BrtRangeProtection" */ },
  18776. 0x0219: { /* n:"BrtPhoneticInfo" */ },
  18777. 0x021A: { /* n:"BrtBeginECTxtWiz", */ T:1 },
  18778. 0x021B: { /* n:"BrtEndECTxtWiz", */ T:-1 },
  18779. 0x021C: { /* n:"BrtBeginECTWFldInfoLst", */ T:1 },
  18780. 0x021D: { /* n:"BrtEndECTWFldInfoLst", */ T:-1 },
  18781. 0x021E: { /* n:"BrtBeginECTwFldInfo", */ T:1 },
  18782. 0x0224: { /* n:"BrtFileSharing" */ },
  18783. 0x0225: { /* n:"BrtOleSize" */ },
  18784. 0x0226: { /* n:"BrtDrawing", */ f:parse_RelID },
  18785. 0x0227: { /* n:"BrtLegacyDrawing" */ },
  18786. 0x0228: { /* n:"BrtLegacyDrawingHF" */ },
  18787. 0x0229: { /* n:"BrtWebOpt" */ },
  18788. 0x022A: { /* n:"BrtBeginWebPubItems", */ T:1 },
  18789. 0x022B: { /* n:"BrtEndWebPubItems", */ T:-1 },
  18790. 0x022C: { /* n:"BrtBeginWebPubItem", */ T:1 },
  18791. 0x022D: { /* n:"BrtEndWebPubItem", */ T:-1 },
  18792. 0x022E: { /* n:"BrtBeginSXCondFmt", */ T:1 },
  18793. 0x022F: { /* n:"BrtEndSXCondFmt", */ T:-1 },
  18794. 0x0230: { /* n:"BrtBeginSXCondFmts", */ T:1 },
  18795. 0x0231: { /* n:"BrtEndSXCondFmts", */ T:-1 },
  18796. 0x0232: { /* n:"BrtBkHim" */ },
  18797. 0x0234: { /* n:"BrtColor" */ },
  18798. 0x0235: { /* n:"BrtBeginIndexedColors", */ T:1 },
  18799. 0x0236: { /* n:"BrtEndIndexedColors", */ T:-1 },
  18800. 0x0239: { /* n:"BrtBeginMRUColors", */ T:1 },
  18801. 0x023A: { /* n:"BrtEndMRUColors", */ T:-1 },
  18802. 0x023C: { /* n:"BrtMRUColor" */ },
  18803. 0x023D: { /* n:"BrtBeginDVals", */ T:1 },
  18804. 0x023E: { /* n:"BrtEndDVals", */ T:-1 },
  18805. 0x0241: { /* n:"BrtSupNameStart" */ },
  18806. 0x0242: { /* n:"BrtSupNameValueStart" */ },
  18807. 0x0243: { /* n:"BrtSupNameValueEnd" */ },
  18808. 0x0244: { /* n:"BrtSupNameNum" */ },
  18809. 0x0245: { /* n:"BrtSupNameErr" */ },
  18810. 0x0246: { /* n:"BrtSupNameSt" */ },
  18811. 0x0247: { /* n:"BrtSupNameNil" */ },
  18812. 0x0248: { /* n:"BrtSupNameBool" */ },
  18813. 0x0249: { /* n:"BrtSupNameFmla" */ },
  18814. 0x024A: { /* n:"BrtSupNameBits" */ },
  18815. 0x024B: { /* n:"BrtSupNameEnd" */ },
  18816. 0x024C: { /* n:"BrtEndSupBook", */ T:-1 },
  18817. 0x024D: { /* n:"BrtCellSmartTagProperty" */ },
  18818. 0x024E: { /* n:"BrtBeginCellSmartTag", */ T:1 },
  18819. 0x024F: { /* n:"BrtEndCellSmartTag", */ T:-1 },
  18820. 0x0250: { /* n:"BrtBeginCellSmartTags", */ T:1 },
  18821. 0x0251: { /* n:"BrtEndCellSmartTags", */ T:-1 },
  18822. 0x0252: { /* n:"BrtBeginSmartTags", */ T:1 },
  18823. 0x0253: { /* n:"BrtEndSmartTags", */ T:-1 },
  18824. 0x0254: { /* n:"BrtSmartTagType" */ },
  18825. 0x0255: { /* n:"BrtBeginSmartTagTypes", */ T:1 },
  18826. 0x0256: { /* n:"BrtEndSmartTagTypes", */ T:-1 },
  18827. 0x0257: { /* n:"BrtBeginSXFilters", */ T:1 },
  18828. 0x0258: { /* n:"BrtEndSXFilters", */ T:-1 },
  18829. 0x0259: { /* n:"BrtBeginSXFILTER", */ T:1 },
  18830. 0x025A: { /* n:"BrtEndSXFilter", */ T:-1 },
  18831. 0x025B: { /* n:"BrtBeginFills", */ T:1 },
  18832. 0x025C: { /* n:"BrtEndFills", */ T:-1 },
  18833. 0x025D: { /* n:"BrtBeginCellWatches", */ T:1 },
  18834. 0x025E: { /* n:"BrtEndCellWatches", */ T:-1 },
  18835. 0x025F: { /* n:"BrtCellWatch" */ },
  18836. 0x0260: { /* n:"BrtBeginCRErrs", */ T:1 },
  18837. 0x0261: { /* n:"BrtEndCRErrs", */ T:-1 },
  18838. 0x0262: { /* n:"BrtCrashRecErr" */ },
  18839. 0x0263: { /* n:"BrtBeginFonts", */ T:1 },
  18840. 0x0264: { /* n:"BrtEndFonts", */ T:-1 },
  18841. 0x0265: { /* n:"BrtBeginBorders", */ T:1 },
  18842. 0x0266: { /* n:"BrtEndBorders", */ T:-1 },
  18843. 0x0267: { /* n:"BrtBeginFmts", */ T:1 },
  18844. 0x0268: { /* n:"BrtEndFmts", */ T:-1 },
  18845. 0x0269: { /* n:"BrtBeginCellXFs", */ T:1 },
  18846. 0x026A: { /* n:"BrtEndCellXFs", */ T:-1 },
  18847. 0x026B: { /* n:"BrtBeginStyles", */ T:1 },
  18848. 0x026C: { /* n:"BrtEndStyles", */ T:-1 },
  18849. 0x0271: { /* n:"BrtBigName" */ },
  18850. 0x0272: { /* n:"BrtBeginCellStyleXFs", */ T:1 },
  18851. 0x0273: { /* n:"BrtEndCellStyleXFs", */ T:-1 },
  18852. 0x0274: { /* n:"BrtBeginComments", */ T:1 },
  18853. 0x0275: { /* n:"BrtEndComments", */ T:-1 },
  18854. 0x0276: { /* n:"BrtBeginCommentAuthors", */ T:1 },
  18855. 0x0277: { /* n:"BrtEndCommentAuthors", */ T:-1 },
  18856. 0x0278: { /* n:"BrtCommentAuthor", */ f:parse_BrtCommentAuthor },
  18857. 0x0279: { /* n:"BrtBeginCommentList", */ T:1 },
  18858. 0x027A: { /* n:"BrtEndCommentList", */ T:-1 },
  18859. 0x027B: { /* n:"BrtBeginComment", */ T:1, f:parse_BrtBeginComment},
  18860. 0x027C: { /* n:"BrtEndComment", */ T:-1 },
  18861. 0x027D: { /* n:"BrtCommentText", */ f:parse_BrtCommentText },
  18862. 0x027E: { /* n:"BrtBeginOleObjects", */ T:1 },
  18863. 0x027F: { /* n:"BrtOleObject" */ },
  18864. 0x0280: { /* n:"BrtEndOleObjects", */ T:-1 },
  18865. 0x0281: { /* n:"BrtBeginSxrules", */ T:1 },
  18866. 0x0282: { /* n:"BrtEndSxRules", */ T:-1 },
  18867. 0x0283: { /* n:"BrtBeginActiveXControls", */ T:1 },
  18868. 0x0284: { /* n:"BrtActiveX" */ },
  18869. 0x0285: { /* n:"BrtEndActiveXControls", */ T:-1 },
  18870. 0x0286: { /* n:"BrtBeginPCDSDTCEMembersSortBy", */ T:1 },
  18871. 0x0288: { /* n:"BrtBeginCellIgnoreECs", */ T:1 },
  18872. 0x0289: { /* n:"BrtCellIgnoreEC" */ },
  18873. 0x028A: { /* n:"BrtEndCellIgnoreECs", */ T:-1 },
  18874. 0x028B: { /* n:"BrtCsProp", */ f:parse_BrtCsProp },
  18875. 0x028C: { /* n:"BrtCsPageSetup" */ },
  18876. 0x028D: { /* n:"BrtBeginUserCsViews", */ T:1 },
  18877. 0x028E: { /* n:"BrtEndUserCsViews", */ T:-1 },
  18878. 0x028F: { /* n:"BrtBeginUserCsView", */ T:1 },
  18879. 0x0290: { /* n:"BrtEndUserCsView", */ T:-1 },
  18880. 0x0291: { /* n:"BrtBeginPcdSFCIEntries", */ T:1 },
  18881. 0x0292: { /* n:"BrtEndPCDSFCIEntries", */ T:-1 },
  18882. 0x0293: { /* n:"BrtPCDSFCIEntry" */ },
  18883. 0x0294: { /* n:"BrtBeginListParts", */ T:1 },
  18884. 0x0295: { /* n:"BrtListPart" */ },
  18885. 0x0296: { /* n:"BrtEndListParts", */ T:-1 },
  18886. 0x0297: { /* n:"BrtSheetCalcProp" */ },
  18887. 0x0298: { /* n:"BrtBeginFnGroup", */ T:1 },
  18888. 0x0299: { /* n:"BrtFnGroup" */ },
  18889. 0x029A: { /* n:"BrtEndFnGroup", */ T:-1 },
  18890. 0x029B: { /* n:"BrtSupAddin" */ },
  18891. 0x029C: { /* n:"BrtSXTDMPOrder" */ },
  18892. 0x029D: { /* n:"BrtCsProtection" */ },
  18893. 0x029F: { /* n:"BrtBeginWsSortMap", */ T:1 },
  18894. 0x02A0: { /* n:"BrtEndWsSortMap", */ T:-1 },
  18895. 0x02A1: { /* n:"BrtBeginRRSort", */ T:1 },
  18896. 0x02A2: { /* n:"BrtEndRRSort", */ T:-1 },
  18897. 0x02A3: { /* n:"BrtRRSortItem" */ },
  18898. 0x02A4: { /* n:"BrtFileSharingIso" */ },
  18899. 0x02A5: { /* n:"BrtBookProtectionIso" */ },
  18900. 0x02A6: { /* n:"BrtSheetProtectionIso" */ },
  18901. 0x02A7: { /* n:"BrtCsProtectionIso" */ },
  18902. 0x02A8: { /* n:"BrtRangeProtectionIso" */ },
  18903. 0x02A9: { /* n:"BrtDValList" */ },
  18904. 0x0400: { /* n:"BrtRwDescent" */ },
  18905. 0x0401: { /* n:"BrtKnownFonts" */ },
  18906. 0x0402: { /* n:"BrtBeginSXTupleSet", */ T:1 },
  18907. 0x0403: { /* n:"BrtEndSXTupleSet", */ T:-1 },
  18908. 0x0404: { /* n:"BrtBeginSXTupleSetHeader", */ T:1 },
  18909. 0x0405: { /* n:"BrtEndSXTupleSetHeader", */ T:-1 },
  18910. 0x0406: { /* n:"BrtSXTupleSetHeaderItem" */ },
  18911. 0x0407: { /* n:"BrtBeginSXTupleSetData", */ T:1 },
  18912. 0x0408: { /* n:"BrtEndSXTupleSetData", */ T:-1 },
  18913. 0x0409: { /* n:"BrtBeginSXTupleSetRow", */ T:1 },
  18914. 0x040A: { /* n:"BrtEndSXTupleSetRow", */ T:-1 },
  18915. 0x040B: { /* n:"BrtSXTupleSetRowItem" */ },
  18916. 0x040C: { /* n:"BrtNameExt" */ },
  18917. 0x040D: { /* n:"BrtPCDH14" */ },
  18918. 0x040E: { /* n:"BrtBeginPCDCalcMem14", */ T:1 },
  18919. 0x040F: { /* n:"BrtEndPCDCalcMem14", */ T:-1 },
  18920. 0x0410: { /* n:"BrtSXTH14" */ },
  18921. 0x0411: { /* n:"BrtBeginSparklineGroup", */ T:1 },
  18922. 0x0412: { /* n:"BrtEndSparklineGroup", */ T:-1 },
  18923. 0x0413: { /* n:"BrtSparkline" */ },
  18924. 0x0414: { /* n:"BrtSXDI14" */ },
  18925. 0x0415: { /* n:"BrtWsFmtInfoEx14" */ },
  18926. 0x0416: { /* n:"BrtBeginConditionalFormatting14", */ T:1 },
  18927. 0x0417: { /* n:"BrtEndConditionalFormatting14", */ T:-1 },
  18928. 0x0418: { /* n:"BrtBeginCFRule14", */ T:1 },
  18929. 0x0419: { /* n:"BrtEndCFRule14", */ T:-1 },
  18930. 0x041A: { /* n:"BrtCFVO14" */ },
  18931. 0x041B: { /* n:"BrtBeginDatabar14", */ T:1 },
  18932. 0x041C: { /* n:"BrtBeginIconSet14", */ T:1 },
  18933. 0x041D: { /* n:"BrtDVal14", */ f: parse_BrtDVal14 },
  18934. 0x041E: { /* n:"BrtBeginDVals14", */ T:1 },
  18935. 0x041F: { /* n:"BrtColor14" */ },
  18936. 0x0420: { /* n:"BrtBeginSparklines", */ T:1 },
  18937. 0x0421: { /* n:"BrtEndSparklines", */ T:-1 },
  18938. 0x0422: { /* n:"BrtBeginSparklineGroups", */ T:1 },
  18939. 0x0423: { /* n:"BrtEndSparklineGroups", */ T:-1 },
  18940. 0x0425: { /* n:"BrtSXVD14" */ },
  18941. 0x0426: { /* n:"BrtBeginSXView14", */ T:1 },
  18942. 0x0427: { /* n:"BrtEndSXView14", */ T:-1 },
  18943. 0x0428: { /* n:"BrtBeginSXView16", */ T:1 },
  18944. 0x0429: { /* n:"BrtEndSXView16", */ T:-1 },
  18945. 0x042A: { /* n:"BrtBeginPCD14", */ T:1 },
  18946. 0x042B: { /* n:"BrtEndPCD14", */ T:-1 },
  18947. 0x042C: { /* n:"BrtBeginExtConn14", */ T:1 },
  18948. 0x042D: { /* n:"BrtEndExtConn14", */ T:-1 },
  18949. 0x042E: { /* n:"BrtBeginSlicerCacheIDs", */ T:1 },
  18950. 0x042F: { /* n:"BrtEndSlicerCacheIDs", */ T:-1 },
  18951. 0x0430: { /* n:"BrtBeginSlicerCacheID", */ T:1 },
  18952. 0x0431: { /* n:"BrtEndSlicerCacheID", */ T:-1 },
  18953. 0x0433: { /* n:"BrtBeginSlicerCache", */ T:1 },
  18954. 0x0434: { /* n:"BrtEndSlicerCache", */ T:-1 },
  18955. 0x0435: { /* n:"BrtBeginSlicerCacheDef", */ T:1 },
  18956. 0x0436: { /* n:"BrtEndSlicerCacheDef", */ T:-1 },
  18957. 0x0437: { /* n:"BrtBeginSlicersEx", */ T:1 },
  18958. 0x0438: { /* n:"BrtEndSlicersEx", */ T:-1 },
  18959. 0x0439: { /* n:"BrtBeginSlicerEx", */ T:1 },
  18960. 0x043A: { /* n:"BrtEndSlicerEx", */ T:-1 },
  18961. 0x043B: { /* n:"BrtBeginSlicer", */ T:1 },
  18962. 0x043C: { /* n:"BrtEndSlicer", */ T:-1 },
  18963. 0x043D: { /* n:"BrtSlicerCachePivotTables" */ },
  18964. 0x043E: { /* n:"BrtBeginSlicerCacheOlapImpl", */ T:1 },
  18965. 0x043F: { /* n:"BrtEndSlicerCacheOlapImpl", */ T:-1 },
  18966. 0x0440: { /* n:"BrtBeginSlicerCacheLevelsData", */ T:1 },
  18967. 0x0441: { /* n:"BrtEndSlicerCacheLevelsData", */ T:-1 },
  18968. 0x0442: { /* n:"BrtBeginSlicerCacheLevelData", */ T:1 },
  18969. 0x0443: { /* n:"BrtEndSlicerCacheLevelData", */ T:-1 },
  18970. 0x0444: { /* n:"BrtBeginSlicerCacheSiRanges", */ T:1 },
  18971. 0x0445: { /* n:"BrtEndSlicerCacheSiRanges", */ T:-1 },
  18972. 0x0446: { /* n:"BrtBeginSlicerCacheSiRange", */ T:1 },
  18973. 0x0447: { /* n:"BrtEndSlicerCacheSiRange", */ T:-1 },
  18974. 0x0448: { /* n:"BrtSlicerCacheOlapItem" */ },
  18975. 0x0449: { /* n:"BrtBeginSlicerCacheSelections", */ T:1 },
  18976. 0x044A: { /* n:"BrtSlicerCacheSelection" */ },
  18977. 0x044B: { /* n:"BrtEndSlicerCacheSelections", */ T:-1 },
  18978. 0x044C: { /* n:"BrtBeginSlicerCacheNative", */ T:1 },
  18979. 0x044D: { /* n:"BrtEndSlicerCacheNative", */ T:-1 },
  18980. 0x044E: { /* n:"BrtSlicerCacheNativeItem" */ },
  18981. 0x044F: { /* n:"BrtRangeProtection14" */ },
  18982. 0x0450: { /* n:"BrtRangeProtectionIso14" */ },
  18983. 0x0451: { /* n:"BrtCellIgnoreEC14" */ },
  18984. 0x0457: { /* n:"BrtList14" */ },
  18985. 0x0458: { /* n:"BrtCFIcon" */ },
  18986. 0x0459: { /* n:"BrtBeginSlicerCachesPivotCacheIDs", */ T:1 },
  18987. 0x045A: { /* n:"BrtEndSlicerCachesPivotCacheIDs", */ T:-1 },
  18988. 0x045B: { /* n:"BrtBeginSlicers", */ T:1 },
  18989. 0x045C: { /* n:"BrtEndSlicers", */ T:-1 },
  18990. 0x045D: { /* n:"BrtWbProp14" */ },
  18991. 0x045E: { /* n:"BrtBeginSXEdit", */ T:1 },
  18992. 0x045F: { /* n:"BrtEndSXEdit", */ T:-1 },
  18993. 0x0460: { /* n:"BrtBeginSXEdits", */ T:1 },
  18994. 0x0461: { /* n:"BrtEndSXEdits", */ T:-1 },
  18995. 0x0462: { /* n:"BrtBeginSXChange", */ T:1 },
  18996. 0x0463: { /* n:"BrtEndSXChange", */ T:-1 },
  18997. 0x0464: { /* n:"BrtBeginSXChanges", */ T:1 },
  18998. 0x0465: { /* n:"BrtEndSXChanges", */ T:-1 },
  18999. 0x0466: { /* n:"BrtSXTupleItems" */ },
  19000. 0x0468: { /* n:"BrtBeginSlicerStyle", */ T:1 },
  19001. 0x0469: { /* n:"BrtEndSlicerStyle", */ T:-1 },
  19002. 0x046A: { /* n:"BrtSlicerStyleElement" */ },
  19003. 0x046B: { /* n:"BrtBeginStyleSheetExt14", */ T:1 },
  19004. 0x046C: { /* n:"BrtEndStyleSheetExt14", */ T:-1 },
  19005. 0x046D: { /* n:"BrtBeginSlicerCachesPivotCacheID", */ T:1 },
  19006. 0x046E: { /* n:"BrtEndSlicerCachesPivotCacheID", */ T:-1 },
  19007. 0x046F: { /* n:"BrtBeginConditionalFormattings", */ T:1 },
  19008. 0x0470: { /* n:"BrtEndConditionalFormattings", */ T:-1 },
  19009. 0x0471: { /* n:"BrtBeginPCDCalcMemExt", */ T:1 },
  19010. 0x0472: { /* n:"BrtEndPCDCalcMemExt", */ T:-1 },
  19011. 0x0473: { /* n:"BrtBeginPCDCalcMemsExt", */ T:1 },
  19012. 0x0474: { /* n:"BrtEndPCDCalcMemsExt", */ T:-1 },
  19013. 0x0475: { /* n:"BrtPCDField14" */ },
  19014. 0x0476: { /* n:"BrtBeginSlicerStyles", */ T:1 },
  19015. 0x0477: { /* n:"BrtEndSlicerStyles", */ T:-1 },
  19016. 0x0478: { /* n:"BrtBeginSlicerStyleElements", */ T:1 },
  19017. 0x0479: { /* n:"BrtEndSlicerStyleElements", */ T:-1 },
  19018. 0x047A: { /* n:"BrtCFRuleExt" */ },
  19019. 0x047B: { /* n:"BrtBeginSXCondFmt14", */ T:1 },
  19020. 0x047C: { /* n:"BrtEndSXCondFmt14", */ T:-1 },
  19021. 0x047D: { /* n:"BrtBeginSXCondFmts14", */ T:1 },
  19022. 0x047E: { /* n:"BrtEndSXCondFmts14", */ T:-1 },
  19023. 0x0480: { /* n:"BrtBeginSortCond14", */ T:1 },
  19024. 0x0481: { /* n:"BrtEndSortCond14", */ T:-1 },
  19025. 0x0482: { /* n:"BrtEndDVals14", */ T:-1 },
  19026. 0x0483: { /* n:"BrtEndIconSet14", */ T:-1 },
  19027. 0x0484: { /* n:"BrtEndDatabar14", */ T:-1 },
  19028. 0x0485: { /* n:"BrtBeginColorScale14", */ T:1 },
  19029. 0x0486: { /* n:"BrtEndColorScale14", */ T:-1 },
  19030. 0x0487: { /* n:"BrtBeginSxrules14", */ T:1 },
  19031. 0x0488: { /* n:"BrtEndSxrules14", */ T:-1 },
  19032. 0x0489: { /* n:"BrtBeginPRule14", */ T:1 },
  19033. 0x048A: { /* n:"BrtEndPRule14", */ T:-1 },
  19034. 0x048B: { /* n:"BrtBeginPRFilters14", */ T:1 },
  19035. 0x048C: { /* n:"BrtEndPRFilters14", */ T:-1 },
  19036. 0x048D: { /* n:"BrtBeginPRFilter14", */ T:1 },
  19037. 0x048E: { /* n:"BrtEndPRFilter14", */ T:-1 },
  19038. 0x048F: { /* n:"BrtBeginPRFItem14", */ T:1 },
  19039. 0x0490: { /* n:"BrtEndPRFItem14", */ T:-1 },
  19040. 0x0491: { /* n:"BrtBeginCellIgnoreECs14", */ T:1 },
  19041. 0x0492: { /* n:"BrtEndCellIgnoreECs14", */ T:-1 },
  19042. 0x0493: { /* n:"BrtDxf14" */ },
  19043. 0x0494: { /* n:"BrtBeginDxF14s", */ T:1 },
  19044. 0x0495: { /* n:"BrtEndDxf14s", */ T:-1 },
  19045. 0x0499: { /* n:"BrtFilter14" */ },
  19046. 0x049A: { /* n:"BrtBeginCustomFilters14", */ T:1 },
  19047. 0x049C: { /* n:"BrtCustomFilter14" */ },
  19048. 0x049D: { /* n:"BrtIconFilter14" */ },
  19049. 0x049E: { /* n:"BrtPivotCacheConnectionName" */ },
  19050. 0x0800: { /* n:"BrtBeginDecoupledPivotCacheIDs", */ T:1 },
  19051. 0x0801: { /* n:"BrtEndDecoupledPivotCacheIDs", */ T:-1 },
  19052. 0x0802: { /* n:"BrtDecoupledPivotCacheID" */ },
  19053. 0x0803: { /* n:"BrtBeginPivotTableRefs", */ T:1 },
  19054. 0x0804: { /* n:"BrtEndPivotTableRefs", */ T:-1 },
  19055. 0x0805: { /* n:"BrtPivotTableRef" */ },
  19056. 0x0806: { /* n:"BrtSlicerCacheBookPivotTables" */ },
  19057. 0x0807: { /* n:"BrtBeginSxvcells", */ T:1 },
  19058. 0x0808: { /* n:"BrtEndSxvcells", */ T:-1 },
  19059. 0x0809: { /* n:"BrtBeginSxRow", */ T:1 },
  19060. 0x080A: { /* n:"BrtEndSxRow", */ T:-1 },
  19061. 0x080C: { /* n:"BrtPcdCalcMem15" */ },
  19062. 0x0813: { /* n:"BrtQsi15" */ },
  19063. 0x0814: { /* n:"BrtBeginWebExtensions", */ T:1 },
  19064. 0x0815: { /* n:"BrtEndWebExtensions", */ T:-1 },
  19065. 0x0816: { /* n:"BrtWebExtension" */ },
  19066. 0x0817: { /* n:"BrtAbsPath15" */ },
  19067. 0x0818: { /* n:"BrtBeginPivotTableUISettings", */ T:1 },
  19068. 0x0819: { /* n:"BrtEndPivotTableUISettings", */ T:-1 },
  19069. 0x081B: { /* n:"BrtTableSlicerCacheIDs" */ },
  19070. 0x081C: { /* n:"BrtTableSlicerCacheID" */ },
  19071. 0x081D: { /* n:"BrtBeginTableSlicerCache", */ T:1 },
  19072. 0x081E: { /* n:"BrtEndTableSlicerCache", */ T:-1 },
  19073. 0x081F: { /* n:"BrtSxFilter15" */ },
  19074. 0x0820: { /* n:"BrtBeginTimelineCachePivotCacheIDs", */ T:1 },
  19075. 0x0821: { /* n:"BrtEndTimelineCachePivotCacheIDs", */ T:-1 },
  19076. 0x0822: { /* n:"BrtTimelineCachePivotCacheID" */ },
  19077. 0x0823: { /* n:"BrtBeginTimelineCacheIDs", */ T:1 },
  19078. 0x0824: { /* n:"BrtEndTimelineCacheIDs", */ T:-1 },
  19079. 0x0825: { /* n:"BrtBeginTimelineCacheID", */ T:1 },
  19080. 0x0826: { /* n:"BrtEndTimelineCacheID", */ T:-1 },
  19081. 0x0827: { /* n:"BrtBeginTimelinesEx", */ T:1 },
  19082. 0x0828: { /* n:"BrtEndTimelinesEx", */ T:-1 },
  19083. 0x0829: { /* n:"BrtBeginTimelineEx", */ T:1 },
  19084. 0x082A: { /* n:"BrtEndTimelineEx", */ T:-1 },
  19085. 0x082B: { /* n:"BrtWorkBookPr15" */ },
  19086. 0x082C: { /* n:"BrtPCDH15" */ },
  19087. 0x082D: { /* n:"BrtBeginTimelineStyle", */ T:1 },
  19088. 0x082E: { /* n:"BrtEndTimelineStyle", */ T:-1 },
  19089. 0x082F: { /* n:"BrtTimelineStyleElement" */ },
  19090. 0x0830: { /* n:"BrtBeginTimelineStylesheetExt15", */ T:1 },
  19091. 0x0831: { /* n:"BrtEndTimelineStylesheetExt15", */ T:-1 },
  19092. 0x0832: { /* n:"BrtBeginTimelineStyles", */ T:1 },
  19093. 0x0833: { /* n:"BrtEndTimelineStyles", */ T:-1 },
  19094. 0x0834: { /* n:"BrtBeginTimelineStyleElements", */ T:1 },
  19095. 0x0835: { /* n:"BrtEndTimelineStyleElements", */ T:-1 },
  19096. 0x0836: { /* n:"BrtDxf15" */ },
  19097. 0x0837: { /* n:"BrtBeginDxfs15", */ T:1 },
  19098. 0x0838: { /* n:"BrtEndDxfs15", */ T:-1 },
  19099. 0x0839: { /* n:"BrtSlicerCacheHideItemsWithNoData" */ },
  19100. 0x083A: { /* n:"BrtBeginItemUniqueNames", */ T:1 },
  19101. 0x083B: { /* n:"BrtEndItemUniqueNames", */ T:-1 },
  19102. 0x083C: { /* n:"BrtItemUniqueName" */ },
  19103. 0x083D: { /* n:"BrtBeginExtConn15", */ T:1 },
  19104. 0x083E: { /* n:"BrtEndExtConn15", */ T:-1 },
  19105. 0x083F: { /* n:"BrtBeginOledbPr15", */ T:1 },
  19106. 0x0840: { /* n:"BrtEndOledbPr15", */ T:-1 },
  19107. 0x0841: { /* n:"BrtBeginDataFeedPr15", */ T:1 },
  19108. 0x0842: { /* n:"BrtEndDataFeedPr15", */ T:-1 },
  19109. 0x0843: { /* n:"BrtTextPr15" */ },
  19110. 0x0844: { /* n:"BrtRangePr15" */ },
  19111. 0x0845: { /* n:"BrtDbCommand15" */ },
  19112. 0x0846: { /* n:"BrtBeginDbTables15", */ T:1 },
  19113. 0x0847: { /* n:"BrtEndDbTables15", */ T:-1 },
  19114. 0x0848: { /* n:"BrtDbTable15" */ },
  19115. 0x0849: { /* n:"BrtBeginDataModel", */ T:1 },
  19116. 0x084A: { /* n:"BrtEndDataModel", */ T:-1 },
  19117. 0x084B: { /* n:"BrtBeginModelTables", */ T:1 },
  19118. 0x084C: { /* n:"BrtEndModelTables", */ T:-1 },
  19119. 0x084D: { /* n:"BrtModelTable" */ },
  19120. 0x084E: { /* n:"BrtBeginModelRelationships", */ T:1 },
  19121. 0x084F: { /* n:"BrtEndModelRelationships", */ T:-1 },
  19122. 0x0850: { /* n:"BrtModelRelationship" */ },
  19123. 0x0851: { /* n:"BrtBeginECTxtWiz15", */ T:1 },
  19124. 0x0852: { /* n:"BrtEndECTxtWiz15", */ T:-1 },
  19125. 0x0853: { /* n:"BrtBeginECTWFldInfoLst15", */ T:1 },
  19126. 0x0854: { /* n:"BrtEndECTWFldInfoLst15", */ T:-1 },
  19127. 0x0855: { /* n:"BrtBeginECTWFldInfo15", */ T:1 },
  19128. 0x0856: { /* n:"BrtFieldListActiveItem" */ },
  19129. 0x0857: { /* n:"BrtPivotCacheIdVersion" */ },
  19130. 0x0858: { /* n:"BrtSXDI15" */ },
  19131. 0x0859: { /* n:"BrtBeginModelTimeGroupings", */ T:1 },
  19132. 0x085A: { /* n:"BrtEndModelTimeGroupings", */ T:-1 },
  19133. 0x085B: { /* n:"BrtBeginModelTimeGrouping", */ T:1 },
  19134. 0x085C: { /* n:"BrtEndModelTimeGrouping", */ T:-1 },
  19135. 0x085D: { /* n:"BrtModelTimeGroupingCalcCol" */ },
  19136. 0x0C00: { /* n:"BrtUid" */ },
  19137. 0x0C01: { /* n:"BrtRevisionPtr" */ },
  19138. 0x1000: { /* n:"BrtBeginDynamicArrayPr", */ T:1 },
  19139. 0x1001: { /* n:"BrtEndDynamicArrayPr", */ T:-1 },
  19140. 0x138A: { /* n:"BrtBeginRichValueBlock", */ T:1 },
  19141. 0x138B: { /* n:"BrtEndRichValueBlock", */ T:-1 },
  19142. 0x13D9: { /* n:"BrtBeginRichFilters", */ T:1 },
  19143. 0x13DA: { /* n:"BrtEndRichFilters", */ T:-1 },
  19144. 0x13DB: { /* n:"BrtRichFilter" */ },
  19145. 0x13DC: { /* n:"BrtBeginRichFilterColumn", */ T:1 },
  19146. 0x13DD: { /* n:"BrtEndRichFilterColumn", */ T:-1 },
  19147. 0x13DE: { /* n:"BrtBeginCustomRichFilters", */ T:1 },
  19148. 0x13DF: { /* n:"BrtEndCustomRichFilters", */ T:-1 },
  19149. 0x13E0: { /* n:"BrtCustomRichFilter" */ },
  19150. 0x13E1: { /* n:"BrtTop10RichFilter" */ },
  19151. 0x13E2: { /* n:"BrtDynamicRichFilter" */ },
  19152. 0x13E4: { /* n:"BrtBeginRichSortCondition", */ T:1 },
  19153. 0x13E5: { /* n:"BrtEndRichSortCondition", */ T:-1 },
  19154. 0x13E6: { /* n:"BrtRichFilterDateGroupItem" */ },
  19155. 0x13E7: { /* n:"BrtBeginCalcFeatures", */ T:1 },
  19156. 0x13E8: { /* n:"BrtEndCalcFeatures", */ T:-1 },
  19157. 0x13E9: { /* n:"BrtCalcFeature" */ },
  19158. 0x13EB: { /* n:"BrtExternalLinksPr" */ },
  19159. 0xFFFF: { n:"" }
  19160. };
  19161. /* [MS-XLS] 2.3 Record Enumeration (and other sources) */
  19162. var XLSRecordEnum = {
  19163. /* [MS-XLS] 2.3 Record Enumeration 2021-08-17 */
  19164. 0x0006: { /* n:"Formula", */ f:parse_Formula },
  19165. 0x000a: { /* n:"EOF", */ f:parsenoop2 },
  19166. 0x000c: { /* n:"CalcCount", */ f:parseuint16 }, //
  19167. 0x000d: { /* n:"CalcMode", */ f:parseuint16 }, //
  19168. 0x000e: { /* n:"CalcPrecision", */ f:parsebool }, //
  19169. 0x000f: { /* n:"CalcRefMode", */ f:parsebool }, //
  19170. 0x0010: { /* n:"CalcDelta", */ f:parse_Xnum }, //
  19171. 0x0011: { /* n:"CalcIter", */ f:parsebool }, //
  19172. 0x0012: { /* n:"Protect", */ f:parsebool },
  19173. 0x0013: { /* n:"Password", */ f:parseuint16 },
  19174. 0x0014: { /* n:"Header", */ f:parse_XLHeaderFooter },
  19175. 0x0015: { /* n:"Footer", */ f:parse_XLHeaderFooter },
  19176. 0x0017: { /* n:"ExternSheet", */ f:parse_ExternSheet },
  19177. 0x0018: { /* n:"Lbl", */ f:parse_Lbl },
  19178. 0x0019: { /* n:"WinProtect", */ f:parsebool },
  19179. 0x001a: { /* n:"VerticalPageBreaks", */ },
  19180. 0x001b: { /* n:"HorizontalPageBreaks", */ },
  19181. 0x001c: { /* n:"Note", */ f:parse_Note },
  19182. 0x001d: { /* n:"Selection", */ },
  19183. 0x0022: { /* n:"Date1904", */ f:parsebool },
  19184. 0x0023: { /* n:"ExternName", */ f:parse_ExternName },
  19185. 0x0026: { /* n:"LeftMargin", */ f:parse_Xnum }, // *
  19186. 0x0027: { /* n:"RightMargin", */ f:parse_Xnum }, // *
  19187. 0x0028: { /* n:"TopMargin", */ f:parse_Xnum }, // *
  19188. 0x0029: { /* n:"BottomMargin", */ f:parse_Xnum }, // *
  19189. 0x002a: { /* n:"PrintRowCol", */ f:parsebool },
  19190. 0x002b: { /* n:"PrintGrid", */ f:parsebool },
  19191. 0x002f: { /* n:"FilePass", */ f:parse_FilePass },
  19192. 0x0031: { /* n:"Font", */ f:parse_Font },
  19193. 0x0033: { /* n:"PrintSize", */ f:parseuint16 },
  19194. 0x003c: { /* n:"Continue", */ },
  19195. 0x003d: { /* n:"Window1", */ f:parse_Window1 },
  19196. 0x0040: { /* n:"Backup", */ f:parsebool },
  19197. 0x0041: { /* n:"Pane", */ f:parse_Pane },
  19198. 0x0042: { /* n:"CodePage", */ f:parseuint16 },
  19199. 0x004d: { /* n:"Pls", */ },
  19200. 0x0050: { /* n:"DCon", */ },
  19201. 0x0051: { /* n:"DConRef", */ },
  19202. 0x0052: { /* n:"DConName", */ },
  19203. 0x0055: { /* n:"DefColWidth", */ f:parseuint16 },
  19204. 0x0059: { /* n:"XCT", */ },
  19205. 0x005a: { /* n:"CRN", */ },
  19206. 0x005b: { /* n:"FileSharing", */ },
  19207. 0x005c: { /* n:"WriteAccess", */ f:parse_WriteAccess },
  19208. 0x005d: { /* n:"Obj", */ f:parse_Obj },
  19209. 0x005e: { /* n:"Uncalced", */ },
  19210. 0x005f: { /* n:"CalcSaveRecalc", */ f:parsebool }, //
  19211. 0x0060: { /* n:"Template", */ },
  19212. 0x0061: { /* n:"Intl", */ },
  19213. 0x0063: { /* n:"ObjProtect", */ f:parsebool },
  19214. 0x007d: { /* n:"ColInfo", */ f:parse_ColInfo },
  19215. 0x0080: { /* n:"Guts", */ f:parse_Guts },
  19216. 0x0081: { /* n:"WsBool", */ f:parse_WsBool },
  19217. 0x0082: { /* n:"GridSet", */ f:parseuint16 },
  19218. 0x0083: { /* n:"HCenter", */ f:parsebool },
  19219. 0x0084: { /* n:"VCenter", */ f:parsebool },
  19220. 0x0085: { /* n:"BoundSheet8", */ f:parse_BoundSheet8 },
  19221. 0x0086: { /* n:"WriteProtect", */ },
  19222. 0x008c: { /* n:"Country", */ f:parse_Country },
  19223. 0x008d: { /* n:"HideObj", */ f:parseuint16 },
  19224. 0x0090: { /* n:"Sort", */ },
  19225. 0x0092: { /* n:"Palette", */ f:parse_Palette },
  19226. 0x0097: { /* n:"Sync", */ },
  19227. 0x0098: { /* n:"LPr", */ },
  19228. 0x0099: { /* n:"DxGCol", */ },
  19229. 0x009a: { /* n:"FnGroupName", */ },
  19230. 0x009b: { /* n:"FilterMode", */ },
  19231. 0x009c: { /* n:"BuiltInFnGroupCount", */ f:parseuint16 },
  19232. 0x009d: { /* n:"AutoFilterInfo", */ },
  19233. 0x009e: { /* n:"AutoFilter", */ },
  19234. 0x00a0: { /* n:"Scl", */ f:parse_Scl },
  19235. 0x00a1: { /* n:"Setup", */ f:parse_Setup },
  19236. 0x00ae: { /* n:"ScenMan", */ },
  19237. 0x00af: { /* n:"SCENARIO", */ },
  19238. 0x00b0: { /* n:"SxView", */ },
  19239. 0x00b1: { /* n:"Sxvd", */ },
  19240. 0x00b2: { /* n:"SXVI", */ },
  19241. 0x00b4: { /* n:"SxIvd", */ },
  19242. 0x00b5: { /* n:"SXLI", */ },
  19243. 0x00b6: { /* n:"SXPI", */ },
  19244. 0x00b8: { /* n:"DocRoute", */ },
  19245. 0x00b9: { /* n:"RecipName", */ },
  19246. 0x00bd: { /* n:"MulRk", */ f:parse_MulRk },
  19247. 0x00be: { /* n:"MulBlank", */ f:parse_MulBlank },
  19248. 0x00c1: { /* n:"Mms", */ f:parsenoop2 },
  19249. 0x00c5: { /* n:"SXDI", */ },
  19250. 0x00c6: { /* n:"SXDB", */ },
  19251. 0x00c7: { /* n:"SXFDB", */ },
  19252. 0x00c8: { /* n:"SXDBB", */ },
  19253. 0x00c9: { /* n:"SXNum", */ },
  19254. 0x00ca: { /* n:"SxBool", */ f:parsebool },
  19255. 0x00cb: { /* n:"SxErr", */ },
  19256. 0x00cc: { /* n:"SXInt", */ },
  19257. 0x00cd: { /* n:"SXString", */ },
  19258. 0x00ce: { /* n:"SXDtr", */ },
  19259. 0x00cf: { /* n:"SxNil", */ },
  19260. 0x00d0: { /* n:"SXTbl", */ },
  19261. 0x00d1: { /* n:"SXTBRGIITM", */ },
  19262. 0x00d2: { /* n:"SxTbpg", */ },
  19263. 0x00d3: { /* n:"ObProj", */ },
  19264. 0x00d5: { /* n:"SXStreamID", */ },
  19265. 0x00d7: { /* n:"DBCell", */ },
  19266. 0x00d8: { /* n:"SXRng", */ },
  19267. 0x00d9: { /* n:"SxIsxoper", */ },
  19268. 0x00da: { /* n:"BookBool", */ f:parseuint16 },
  19269. 0x00dc: { /* n:"DbOrParamQry", */ },
  19270. 0x00dd: { /* n:"ScenarioProtect", */ f:parsebool },
  19271. 0x00de: { /* n:"OleObjectSize", */ },
  19272. 0x00e0: { /* n:"XF", */ f:parse_XF },
  19273. 0x00e1: { /* n:"InterfaceHdr", */ f:parse_InterfaceHdr },
  19274. 0x00e2: { /* n:"InterfaceEnd", */ f:parsenoop2 },
  19275. 0x00e3: { /* n:"SXVS", */ },
  19276. 0x00e5: { /* n:"MergeCells", */ f:parse_MergeCells },
  19277. 0x00e9: { /* n:"BkHim", */ },
  19278. 0x00eb: { /* n:"MsoDrawingGroup", */ },
  19279. 0x00ec: { /* n:"MsoDrawing", */ },
  19280. 0x00ed: { /* n:"MsoDrawingSelection", */ },
  19281. 0x00ef: { /* n:"PhoneticInfo", */ },
  19282. 0x00f0: { /* n:"SxRule", */ },
  19283. 0x00f1: { /* n:"SXEx", */ },
  19284. 0x00f2: { /* n:"SxFilt", */ },
  19285. 0x00f4: { /* n:"SxDXF", */ },
  19286. 0x00f5: { /* n:"SxItm", */ },
  19287. 0x00f6: { /* n:"SxName", */ },
  19288. 0x00f7: { /* n:"SxSelect", */ },
  19289. 0x00f8: { /* n:"SXPair", */ },
  19290. 0x00f9: { /* n:"SxFmla", */ },
  19291. 0x00fb: { /* n:"SxFormat", */ },
  19292. 0x00fc: { /* n:"SST", */ f:parse_SST },
  19293. 0x00fd: { /* n:"LabelSst", */ f:parse_LabelSst },
  19294. 0x00ff: { /* n:"ExtSST", */ f:parse_ExtSST },
  19295. 0x0100: { /* n:"SXVDEx", */ },
  19296. 0x0103: { /* n:"SXFormula", */ },
  19297. 0x0122: { /* n:"SXDBEx", */ },
  19298. 0x0137: { /* n:"RRDInsDel", */ },
  19299. 0x0138: { /* n:"RRDHead", */ },
  19300. 0x013b: { /* n:"RRDChgCell", */ },
  19301. 0x013d: { /* n:"RRTabId", */ f:parseuint16a },
  19302. 0x013e: { /* n:"RRDRenSheet", */ },
  19303. 0x013f: { /* n:"RRSort", */ },
  19304. 0x0140: { /* n:"RRDMove", */ },
  19305. 0x014a: { /* n:"RRFormat", */ },
  19306. 0x014b: { /* n:"RRAutoFmt", */ },
  19307. 0x014d: { /* n:"RRInsertSh", */ },
  19308. 0x014e: { /* n:"RRDMoveBegin", */ },
  19309. 0x014f: { /* n:"RRDMoveEnd", */ },
  19310. 0x0150: { /* n:"RRDInsDelBegin", */ },
  19311. 0x0151: { /* n:"RRDInsDelEnd", */ },
  19312. 0x0152: { /* n:"RRDConflict", */ },
  19313. 0x0153: { /* n:"RRDDefName", */ },
  19314. 0x0154: { /* n:"RRDRstEtxp", */ },
  19315. 0x015f: { /* n:"LRng", */ },
  19316. 0x0160: { /* n:"UsesELFs", */ f:parsebool },
  19317. 0x0161: { /* n:"DSF", */ f:parsenoop2 },
  19318. 0x0191: { /* n:"CUsr", */ },
  19319. 0x0192: { /* n:"CbUsr", */ },
  19320. 0x0193: { /* n:"UsrInfo", */ },
  19321. 0x0194: { /* n:"UsrExcl", */ },
  19322. 0x0195: { /* n:"FileLock", */ },
  19323. 0x0196: { /* n:"RRDInfo", */ },
  19324. 0x0197: { /* n:"BCUsrs", */ },
  19325. 0x0198: { /* n:"UsrChk", */ },
  19326. 0x01a9: { /* n:"UserBView", */ },
  19327. 0x01aa: { /* n:"UserSViewBegin", */ },
  19328. 0x01ab: { /* n:"UserSViewEnd", */ },
  19329. 0x01ac: { /* n:"RRDUserView", */ },
  19330. 0x01ad: { /* n:"Qsi", */ },
  19331. 0x01ae: { /* n:"SupBook", */ f:parse_SupBook },
  19332. 0x01af: { /* n:"Prot4Rev", */ f:parsebool },
  19333. 0x01b0: { /* n:"CondFmt", */ },
  19334. 0x01b1: { /* n:"CF", */ },
  19335. 0x01b2: { /* n:"DVal", */ },
  19336. 0x01b5: { /* n:"DConBin", */ },
  19337. 0x01b6: { /* n:"TxO", */ f:parse_TxO },
  19338. 0x01b7: { /* n:"RefreshAll", */ f:parsebool }, //
  19339. 0x01b8: { /* n:"HLink", */ f:parse_HLink },
  19340. 0x01b9: { /* n:"Lel", */ },
  19341. 0x01ba: { /* n:"CodeName", */ f:parse_XLUnicodeString },
  19342. 0x01bb: { /* n:"SXFDBType", */ },
  19343. 0x01bc: { /* n:"Prot4RevPass", */ f:parseuint16 },
  19344. 0x01bd: { /* n:"ObNoMacros", */ },
  19345. 0x01be: { /* n:"Dv", */ },
  19346. 0x01c0: { /* n:"Excel9File", */ f:parsenoop2 },
  19347. 0x01c1: { /* n:"RecalcId", */ f:parse_RecalcId, r:2},
  19348. 0x01c2: { /* n:"EntExU2", */ f:parsenoop2 },
  19349. 0x0200: { /* n:"Dimensions", */ f:parse_Dimensions },
  19350. 0x0201: { /* n:"Blank", */ f:parse_Blank },
  19351. 0x0203: { /* n:"Number", */ f:parse_Number },
  19352. 0x0204: { /* n:"Label", */ f:parse_Label },
  19353. 0x0205: { /* n:"BoolErr", */ f:parse_BoolErr },
  19354. 0x0207: { /* n:"String", */ f:parse_String },
  19355. 0x0208: { /* n:"Row", */ f:parse_Row },
  19356. 0x020b: { /* n:"Index", */ },
  19357. 0x0221: { /* n:"Array", */ f:parse_Array },
  19358. 0x0225: { /* n:"DefaultRowHeight", */ f:parse_DefaultRowHeight },
  19359. 0x0236: { /* n:"Table", */ },
  19360. 0x023e: { /* n:"Window2", */ f:parse_Window2 },
  19361. 0x027e: { /* n:"RK", */ f:parse_RK },
  19362. 0x0293: { /* n:"Style", */ },
  19363. 0x0418: { /* n:"BigName", */ },
  19364. 0x041e: { /* n:"Format", */ f:parse_Format },
  19365. 0x043c: { /* n:"ContinueBigName", */ },
  19366. 0x04bc: { /* n:"ShrFmla", */ f:parse_ShrFmla },
  19367. 0x0800: { /* n:"HLinkTooltip", */ f:parse_HLinkTooltip },
  19368. 0x0801: { /* n:"WebPub", */ },
  19369. 0x0802: { /* n:"QsiSXTag", */ },
  19370. 0x0803: { /* n:"DBQueryExt", */ },
  19371. 0x0804: { /* n:"ExtString", */ },
  19372. 0x0805: { /* n:"TxtQry", */ },
  19373. 0x0806: { /* n:"Qsir", */ },
  19374. 0x0807: { /* n:"Qsif", */ },
  19375. 0x0808: { /* n:"RRDTQSIF", */ },
  19376. 0x0809: { /* n:"BOF", */ f:parse_BOF },
  19377. 0x080a: { /* n:"OleDbConn", */ },
  19378. 0x080b: { /* n:"WOpt", */ },
  19379. 0x080c: { /* n:"SXViewEx", */ },
  19380. 0x080d: { /* n:"SXTH", */ },
  19381. 0x080e: { /* n:"SXPIEx", */ },
  19382. 0x080f: { /* n:"SXVDTEx", */ },
  19383. 0x0810: { /* n:"SXViewEx9", */ },
  19384. 0x0812: { /* n:"ContinueFrt", */ },
  19385. 0x0813: { /* n:"RealTimeData", */ },
  19386. 0x0850: { /* n:"ChartFrtInfo", */ },
  19387. 0x0851: { /* n:"FrtWrapper", */ },
  19388. 0x0852: { /* n:"StartBlock", */ },
  19389. 0x0853: { /* n:"EndBlock", */ },
  19390. 0x0854: { /* n:"StartObject", */ },
  19391. 0x0855: { /* n:"EndObject", */ },
  19392. 0x0856: { /* n:"CatLab", */ },
  19393. 0x0857: { /* n:"YMult", */ },
  19394. 0x0858: { /* n:"SXViewLink", */ },
  19395. 0x0859: { /* n:"PivotChartBits", */ },
  19396. 0x085a: { /* n:"FrtFontList", */ },
  19397. 0x0862: { /* n:"SheetExt", */ },
  19398. 0x0863: { /* n:"BookExt", */ r:12},
  19399. 0x0864: { /* n:"SXAddl", */ },
  19400. 0x0865: { /* n:"CrErr", */ },
  19401. 0x0866: { /* n:"HFPicture", */ },
  19402. 0x0867: { /* n:"FeatHdr", */ f:parsenoop2 },
  19403. 0x0868: { /* n:"Feat", */ },
  19404. 0x086a: { /* n:"DataLabExt", */ },
  19405. 0x086b: { /* n:"DataLabExtContents", */ },
  19406. 0x086c: { /* n:"CellWatch", */ },
  19407. 0x0871: { /* n:"FeatHdr11", */ },
  19408. 0x0872: { /* n:"Feature11", */ },
  19409. 0x0874: { /* n:"DropDownObjIds", */ },
  19410. 0x0875: { /* n:"ContinueFrt11", */ },
  19411. 0x0876: { /* n:"DConn", */ },
  19412. 0x0877: { /* n:"List12", */ },
  19413. 0x0878: { /* n:"Feature12", */ },
  19414. 0x0879: { /* n:"CondFmt12", */ },
  19415. 0x087a: { /* n:"CF12", */ },
  19416. 0x087b: { /* n:"CFEx", */ },
  19417. 0x087c: { /* n:"XFCRC", */ f:parse_XFCRC, r:12 },
  19418. 0x087d: { /* n:"XFExt", */ f:parse_XFExt, r:12 },
  19419. 0x087e: { /* n:"AutoFilter12", */ },
  19420. 0x087f: { /* n:"ContinueFrt12", */ },
  19421. 0x0884: { /* n:"MDTInfo", */ },
  19422. 0x0885: { /* n:"MDXStr", */ },
  19423. 0x0886: { /* n:"MDXTuple", */ },
  19424. 0x0887: { /* n:"MDXSet", */ },
  19425. 0x0888: { /* n:"MDXProp", */ },
  19426. 0x0889: { /* n:"MDXKPI", */ },
  19427. 0x088a: { /* n:"MDB", */ },
  19428. 0x088b: { /* n:"PLV", */ },
  19429. 0x088c: { /* n:"Compat12", */ f:parsebool, r:12 },
  19430. 0x088d: { /* n:"DXF", */ },
  19431. 0x088e: { /* n:"TableStyles", */ r:12 },
  19432. 0x088f: { /* n:"TableStyle", */ },
  19433. 0x0890: { /* n:"TableStyleElement", */ },
  19434. 0x0892: { /* n:"StyleExt", */ },
  19435. 0x0893: { /* n:"NamePublish", */ },
  19436. 0x0894: { /* n:"NameCmt", */ f:parse_NameCmt, r:12 },
  19437. 0x0895: { /* n:"SortData", */ },
  19438. 0x0896: { /* n:"Theme", */ f:parse_Theme, r:12 },
  19439. 0x0897: { /* n:"GUIDTypeLib", */ },
  19440. 0x0898: { /* n:"FnGrp12", */ },
  19441. 0x0899: { /* n:"NameFnGrp12", */ },
  19442. 0x089a: { /* n:"MTRSettings", */ f:parse_MTRSettings, r:12 },
  19443. 0x089b: { /* n:"CompressPictures", */ f:parsenoop2 },
  19444. 0x089c: { /* n:"HeaderFooter", */ },
  19445. 0x089d: { /* n:"CrtLayout12", */ },
  19446. 0x089e: { /* n:"CrtMlFrt", */ },
  19447. 0x089f: { /* n:"CrtMlFrtContinue", */ },
  19448. 0x08a3: { /* n:"ForceFullCalculation", */ f:parse_ForceFullCalculation },
  19449. 0x08a4: { /* n:"ShapePropsStream", */ },
  19450. 0x08a5: { /* n:"TextPropsStream", */ },
  19451. 0x08a6: { /* n:"RichTextStream", */ },
  19452. 0x08a7: { /* n:"CrtLayout12A", */ },
  19453. 0x1001: { /* n:"Units", */ },
  19454. 0x1002: { /* n:"Chart", */ },
  19455. 0x1003: { /* n:"Series", */ },
  19456. 0x1006: { /* n:"DataFormat", */ },
  19457. 0x1007: { /* n:"LineFormat", */ },
  19458. 0x1009: { /* n:"MarkerFormat", */ },
  19459. 0x100a: { /* n:"AreaFormat", */ },
  19460. 0x100b: { /* n:"PieFormat", */ },
  19461. 0x100c: { /* n:"AttachedLabel", */ },
  19462. 0x100d: { /* n:"SeriesText", */ },
  19463. 0x1014: { /* n:"ChartFormat", */ },
  19464. 0x1015: { /* n:"Legend", */ },
  19465. 0x1016: { /* n:"SeriesList", */ },
  19466. 0x1017: { /* n:"Bar", */ },
  19467. 0x1018: { /* n:"Line", */ },
  19468. 0x1019: { /* n:"Pie", */ },
  19469. 0x101a: { /* n:"Area", */ },
  19470. 0x101b: { /* n:"Scatter", */ },
  19471. 0x101c: { /* n:"CrtLine", */ },
  19472. 0x101d: { /* n:"Axis", */ },
  19473. 0x101e: { /* n:"Tick", */ },
  19474. 0x101f: { /* n:"ValueRange", */ },
  19475. 0x1020: { /* n:"CatSerRange", */ },
  19476. 0x1021: { /* n:"AxisLine", */ },
  19477. 0x1022: { /* n:"CrtLink", */ },
  19478. 0x1024: { /* n:"DefaultText", */ },
  19479. 0x1025: { /* n:"Text", */ },
  19480. 0x1026: { /* n:"FontX", */ f:parseuint16 },
  19481. 0x1027: { /* n:"ObjectLink", */ },
  19482. 0x1032: { /* n:"Frame", */ },
  19483. 0x1033: { /* n:"Begin", */ },
  19484. 0x1034: { /* n:"End", */ },
  19485. 0x1035: { /* n:"PlotArea", */ },
  19486. 0x103a: { /* n:"Chart3d", */ },
  19487. 0x103c: { /* n:"PicF", */ },
  19488. 0x103d: { /* n:"DropBar", */ },
  19489. 0x103e: { /* n:"Radar", */ },
  19490. 0x103f: { /* n:"Surf", */ },
  19491. 0x1040: { /* n:"RadarArea", */ },
  19492. 0x1041: { /* n:"AxisParent", */ },
  19493. 0x1043: { /* n:"LegendException", */ },
  19494. 0x1044: { /* n:"ShtProps", */ f:parse_ShtProps },
  19495. 0x1045: { /* n:"SerToCrt", */ },
  19496. 0x1046: { /* n:"AxesUsed", */ },
  19497. 0x1048: { /* n:"SBaseRef", */ },
  19498. 0x104a: { /* n:"SerParent", */ },
  19499. 0x104b: { /* n:"SerAuxTrend", */ },
  19500. 0x104e: { /* n:"IFmtRecord", */ },
  19501. 0x104f: { /* n:"Pos", */ },
  19502. 0x1050: { /* n:"AlRuns", */ },
  19503. 0x1051: { /* n:"BRAI", */ },
  19504. 0x105b: { /* n:"SerAuxErrBar", */ },
  19505. 0x105c: { /* n:"ClrtClient", */ f:parse_ClrtClient },
  19506. 0x105d: { /* n:"SerFmt", */ },
  19507. 0x105f: { /* n:"Chart3DBarShape", */ },
  19508. 0x1060: { /* n:"Fbi", */ },
  19509. 0x1061: { /* n:"BopPop", */ },
  19510. 0x1062: { /* n:"AxcExt", */ },
  19511. 0x1063: { /* n:"Dat", */ },
  19512. 0x1064: { /* n:"PlotGrowth", */ },
  19513. 0x1065: { /* n:"SIIndex", */ },
  19514. 0x1066: { /* n:"GelFrame", */ },
  19515. 0x1067: { /* n:"BopPopCustom", */ },
  19516. 0x1068: { /* n:"Fbi2", */ },
  19517. 0x0000: { /* n:"Dimensions", */ f:parse_Dimensions },
  19518. 0x0001: { /* n:"BIFF2BLANK", */ },
  19519. 0x0002: { /* n:"BIFF2INT", */ f:parse_BIFF2INT },
  19520. 0x0003: { /* n:"BIFF2NUM", */ f:parse_BIFF2NUM },
  19521. 0x0004: { /* n:"BIFF2STR", */ f:parse_BIFF2STR },
  19522. 0x0005: { /* n:"BoolErr", */ f:parse_BoolErr },
  19523. 0x0007: { /* n:"String", */ f:parse_BIFF2STRING },
  19524. 0x0008: { /* n:"BIFF2ROW", */ },
  19525. 0x0009: { /* n:"BOF", */ f:parse_BOF },
  19526. 0x000b: { /* n:"Index", */ },
  19527. 0x0016: { /* n:"ExternCount", */ f:parseuint16 },
  19528. 0x001e: { /* n:"BIFF2FORMAT", */ f:parse_BIFF2Format },
  19529. 0x001f: { /* n:"BIFF2FMTCNT", */ }, /* 16-bit cnt of BIFF2FORMAT records */
  19530. 0x0020: { /* n:"BIFF2COLINFO", */ },
  19531. 0x0021: { /* n:"Array", */ f:parse_Array },
  19532. 0x0024: { /* n:"COLWIDTH", */ },
  19533. 0x0025: { /* n:"DefaultRowHeight", */ f:parse_DefaultRowHeight },
  19534. // 0x2c ??
  19535. // 0x2d ??
  19536. // 0x2e ??
  19537. // 0x30 FONTCOUNT: number of fonts
  19538. 0x0032: { /* n:"BIFF2FONTXTRA", */ f:parse_BIFF2FONTXTRA },
  19539. // 0x35: INFOOPTS
  19540. // 0x36: TABLE (BIFF2 only)
  19541. // 0x37: TABLE2 (BIFF2 only)
  19542. // 0x38: WNDESK
  19543. // 0x39 ??
  19544. // 0x3a: BEGINPREF
  19545. // 0x3b: ENDPREF
  19546. 0x003e: { /* n:"BIFF2WINDOW2", */ },
  19547. // 0x3f ??
  19548. // 0x46: SHOWSCROLL
  19549. // 0x47: SHOWFORMULA
  19550. // 0x48: STATUSBAR
  19551. // 0x49: SHORTMENUS
  19552. // 0x4A:
  19553. // 0x4B:
  19554. // 0x4C:
  19555. // 0x4E:
  19556. // 0x4F:
  19557. // 0x58: TOOLBAR (BIFF3)
  19558. /* - - - */
  19559. 0x0034: { /* n:"DDEObjName", */ },
  19560. 0x0043: { /* n:"BIFF2XF", */ },
  19561. 0x0044: { /* n:"BIFF2XFINDEX", */ f:parseuint16 },
  19562. 0x0045: { /* n:"BIFF2FONTCLR", */ },
  19563. 0x0056: { /* n:"BIFF4FMTCNT", */ }, /* 16-bit cnt, similar to BIFF2 */
  19564. 0x007e: { /* n:"RK", */ }, /* Not necessarily same as 0x027e */
  19565. 0x007f: { /* n:"ImData", */ f:parse_ImData },
  19566. 0x0087: { /* n:"Addin", */ },
  19567. 0x0088: { /* n:"Edg", */ },
  19568. 0x0089: { /* n:"Pub", */ },
  19569. // 0x8A
  19570. // 0x8B LH: alternate menu key flag (BIFF3/4)
  19571. // 0x8E
  19572. // 0x8F
  19573. 0x0091: { /* n:"Sub", */ },
  19574. // 0x93 STYLE
  19575. 0x0094: { /* n:"LHRecord", */ },
  19576. 0x0095: { /* n:"LHNGraph", */ },
  19577. 0x0096: { /* n:"Sound", */ },
  19578. // 0xA2 FNPROTO: function prototypes (BIFF4)
  19579. // 0xA3
  19580. // 0xA8
  19581. 0x00a9: { /* n:"CoordList", */ },
  19582. 0x00ab: { /* n:"GCW", */ },
  19583. 0x00bc: { /* n:"ShrFmla", */ }, /* Not necessarily same as 0x04bc */
  19584. 0x00bf: { /* n:"ToolbarHdr", */ },
  19585. 0x00c0: { /* n:"ToolbarEnd", */ },
  19586. 0x00c2: { /* n:"AddMenu", */ },
  19587. 0x00c3: { /* n:"DelMenu", */ },
  19588. 0x00d6: { /* n:"RString", */ f:parse_RString },
  19589. 0x00df: { /* n:"UDDesc", */ },
  19590. 0x00ea: { /* n:"TabIdConf", */ },
  19591. 0x0162: { /* n:"XL5Modify", */ },
  19592. 0x01a5: { /* n:"FileSharing2", */ },
  19593. 0x0206: { /* n:"Formula", */ f:parse_Formula },
  19594. 0x0209: { /* n:"BOF", */ f:parse_BOF },
  19595. 0x0218: { /* n:"Lbl", */ f:parse_Lbl },
  19596. 0x0223: { /* n:"ExternName", */ f:parse_ExternName },
  19597. 0x0231: { /* n:"Font", */ },
  19598. 0x0243: { /* n:"BIFF3XF", */ },
  19599. 0x0406: { /* n:"Formula", */ f:parse_Formula },
  19600. 0x0409: { /* n:"BOF", */ f:parse_BOF },
  19601. 0x0443: { /* n:"BIFF4XF", */ },
  19602. 0x086d: { /* n:"FeatInfo", */ },
  19603. 0x0873: { /* n:"FeatInfo11", */ },
  19604. 0x0881: { /* n:"SXAddl12", */ },
  19605. 0x08c0: { /* n:"AutoWebPub", */ },
  19606. 0x08c1: { /* n:"ListObj", */ },
  19607. 0x08c2: { /* n:"ListField", */ },
  19608. 0x08c3: { /* n:"ListDV", */ },
  19609. 0x08c4: { /* n:"ListCondFmt", */ },
  19610. 0x08c5: { /* n:"ListCF", */ },
  19611. 0x08c6: { /* n:"FMQry", */ },
  19612. 0x08c7: { /* n:"FMSQry", */ },
  19613. 0x08c8: { /* n:"PLV", */ },
  19614. 0x08c9: { /* n:"LnExt", */ },
  19615. 0x08ca: { /* n:"MkrExt", */ },
  19616. 0x08cb: { /* n:"CrtCoopt", */ },
  19617. 0x08d6: { /* n:"FRTArchId$", */ r:12 },
  19618. /* --- multiplan 4 records --- */
  19619. 0x0065: { /* n:"", */ }, // one per window
  19620. 0x0066: { /* n:"", */ }, // calc settings
  19621. 0x0069: { /* n:"", */ }, // print header
  19622. 0x006a: { /* n:"", */ }, // print footer
  19623. 0x006b: { /* n:"", */ }, // print settings
  19624. 0x006d: { /* n:"", */ }, // one per window
  19625. 0x0070: { /* n:"", */ }, // includes default col width
  19626. 0x0072: { /* n:"", */ }, // includes selected cell
  19627. 0x7262: {}
  19628. };
  19629. function write_biff_rec(ba, type, payload, length) {
  19630. var t = type;
  19631. if(isNaN(t)) return;
  19632. var len = length || (payload||[]).length || 0;
  19633. var o = ba.next(4);
  19634. o.write_shift(2, t);
  19635. o.write_shift(2, len);
  19636. if(len > 0 && is_buf(payload)) ba.push(payload);
  19637. }
  19638. function write_biff_continue(ba, type, payload, length) {
  19639. var len = length || (payload||[]).length || 0;
  19640. if(len <= 8224) return write_biff_rec(ba, type, payload, len);
  19641. var t = type;
  19642. if(isNaN(t)) return;
  19643. var parts = payload.parts || [], sidx = 0;
  19644. var i = 0, w = 0;
  19645. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  19646. var o = ba.next(4);
  19647. o.write_shift(2, t);
  19648. o.write_shift(2, w);
  19649. ba.push(payload.slice(i, i + w));
  19650. i += w;
  19651. while(i < len) {
  19652. o = ba.next(4);
  19653. o.write_shift(2, 0x3c); // TODO: figure out correct continue type
  19654. w = 0;
  19655. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  19656. o.write_shift(2, w);
  19657. ba.push(payload.slice(i, i+w)); i+= w;
  19658. }
  19659. }
  19660. function write_BIFF2Cell(out, r, c) {
  19661. if(!out) out = new_buf(7);
  19662. out.write_shift(2, r);
  19663. out.write_shift(2, c);
  19664. out.write_shift(2, 0);
  19665. out.write_shift(1, 0);
  19666. return out;
  19667. }
  19668. function write_BIFF2BERR(r, c, val, t) {
  19669. var out = new_buf(9);
  19670. write_BIFF2Cell(out, r, c);
  19671. write_Bes(val, t || 'b', out);
  19672. return out;
  19673. }
  19674. /* TODO: codepage, large strings */
  19675. function write_BIFF2LABEL(r, c, val) {
  19676. var out = new_buf(8 + 2*val.length);
  19677. write_BIFF2Cell(out, r, c);
  19678. out.write_shift(1, val.length);
  19679. out.write_shift(val.length, val, 'sbcs');
  19680. return out.l < out.length ? out.slice(0, out.l) : out;
  19681. }
  19682. function write_ws_biff2_cell(ba, cell, R, C) {
  19683. if(cell.v != null) switch(cell.t) {
  19684. case 'd': case 'n':
  19685. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  19686. if((v == (v|0)) && (v >= 0) && (v < 65536))
  19687. write_biff_rec(ba, 0x0002, write_BIFF2INT(R, C, v));
  19688. else
  19689. write_biff_rec(ba, 0x0003, write_BIFF2NUM(R,C, v));
  19690. return;
  19691. case 'b': case 'e': write_biff_rec(ba, 0x0005, write_BIFF2BERR(R, C, cell.v, cell.t)); return;
  19692. /* TODO: codepage, sst */
  19693. case 's': case 'str':
  19694. write_biff_rec(ba, 0x0004, write_BIFF2LABEL(R, C, cell.v == null ? "" : String(cell.v).slice(0,255)));
  19695. return;
  19696. }
  19697. write_biff_rec(ba, 0x0001, write_BIFF2Cell(null, R, C));
  19698. }
  19699. function write_ws_biff2(ba, ws, idx, opts) {
  19700. var dense = Array.isArray(ws);
  19701. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  19702. if(range.e.c > 0xFF || range.e.r > 0x3FFF) {
  19703. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  19704. range.e.c = Math.min(range.e.c, 0xFF);
  19705. range.e.r = Math.min(range.e.c, 0x3FFF);
  19706. ref = encode_range(range);
  19707. }
  19708. for(var R = range.s.r; R <= range.e.r; ++R) {
  19709. rr = encode_row(R);
  19710. for(var C = range.s.c; C <= range.e.c; ++C) {
  19711. if(R === range.s.r) cols[C] = encode_col(C);
  19712. ref = cols[C] + rr;
  19713. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  19714. if(!cell) continue;
  19715. /* write cell */
  19716. write_ws_biff2_cell(ba, cell, R, C, opts);
  19717. }
  19718. }
  19719. }
  19720. /* Based on test files */
  19721. function write_biff2_buf(wb, opts) {
  19722. var o = opts || {};
  19723. if(DENSE != null && o.dense == null) o.dense = DENSE;
  19724. var ba = buf_array();
  19725. var idx = 0;
  19726. for(var i=0;i<wb.SheetNames.length;++i) if(wb.SheetNames[i] == o.sheet) idx=i;
  19727. if(idx == 0 && !!o.sheet && wb.SheetNames[0] != o.sheet) throw new Error("Sheet not found: " + o.sheet);
  19728. write_biff_rec(ba, (o.biff == 4 ? 0x0409 : (o.biff == 3 ? 0x0209 : 0x0009)), write_BOF(wb, 0x10, o));
  19729. /* ... */
  19730. write_ws_biff2(ba, wb.Sheets[wb.SheetNames[idx]], idx, o, wb);
  19731. /* ... */
  19732. write_biff_rec(ba, 0x000A);
  19733. return ba.end();
  19734. }
  19735. function write_FONTS_biff8(ba, data, opts) {
  19736. write_biff_rec(ba, 0x0031 /* Font */, write_Font({
  19737. sz:12,
  19738. color: {theme:1},
  19739. name: "Arial",
  19740. family: 2,
  19741. scheme: "minor"
  19742. }, opts));
  19743. }
  19744. function write_FMTS_biff8(ba, NF, opts) {
  19745. if(!NF) return;
  19746. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  19747. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_biff_rec(ba, 0x041E /* Format */, write_Format(i, NF[i], opts));
  19748. });
  19749. }
  19750. function write_FEAT(ba, ws) {
  19751. /* [MS-XLS] 2.4.112 */
  19752. var o = new_buf(19);
  19753. o.write_shift(4, 0x867); o.write_shift(4, 0); o.write_shift(4, 0);
  19754. o.write_shift(2, 3); o.write_shift(1, 1); o.write_shift(4, 0);
  19755. write_biff_rec(ba, 0x0867 /* FeatHdr */, o);
  19756. /* [MS-XLS] 2.4.111 */
  19757. o = new_buf(39);
  19758. o.write_shift(4, 0x868); o.write_shift(4, 0); o.write_shift(4, 0);
  19759. o.write_shift(2, 3); o.write_shift(1, 0); o.write_shift(4, 0);
  19760. o.write_shift(2, 1); o.write_shift(4, 4); o.write_shift(2, 0);
  19761. write_Ref8U(safe_decode_range(ws['!ref']||"A1"), o);
  19762. o.write_shift(4, 4);
  19763. write_biff_rec(ba, 0x0868 /* Feat */, o);
  19764. }
  19765. function write_CELLXFS_biff8(ba, opts) {
  19766. for(var i = 0; i < 16; ++i) write_biff_rec(ba, 0x00e0 /* XF */, write_XF({numFmtId:0, style:true}, 0, opts));
  19767. opts.cellXfs.forEach(function(c) {
  19768. write_biff_rec(ba, 0x00e0 /* XF */, write_XF(c, 0, opts));
  19769. });
  19770. }
  19771. function write_ws_biff8_hlinks(ba, ws) {
  19772. for(var R=0; R<ws['!links'].length; ++R) {
  19773. var HL = ws['!links'][R];
  19774. write_biff_rec(ba, 0x01b8 /* HLink */, write_HLink(HL));
  19775. if(HL[1].Tooltip) write_biff_rec(ba, 0x0800 /* HLinkTooltip */, write_HLinkTooltip(HL));
  19776. }
  19777. delete ws['!links'];
  19778. }
  19779. function write_ws_cols_biff8(ba, cols) {
  19780. if(!cols) return;
  19781. var cnt = 0;
  19782. cols.forEach(function(col, idx) {
  19783. if(++cnt <= 256 && col) {
  19784. write_biff_rec(ba, 0x007d /* ColInfo */, write_ColInfo(col_obj_w(idx, col), idx));
  19785. }
  19786. });
  19787. }
  19788. function write_ws_biff8_cell(ba, cell, R, C, opts) {
  19789. var os = 16 + get_cell_style(opts.cellXfs, cell, opts);
  19790. if(cell.v == null && !cell.bf) {
  19791. write_biff_rec(ba, 0x0201 /* Blank */, write_XLSCell(R, C, os));
  19792. return;
  19793. }
  19794. if(cell.bf) write_biff_rec(ba, 0x0006 /* Formula */, write_Formula(cell, R, C, opts, os));
  19795. else switch(cell.t) {
  19796. case 'd': case 'n':
  19797. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  19798. /* TODO: emit RK as appropriate */
  19799. write_biff_rec(ba, 0x0203 /* Number */, write_Number(R, C, v, os, opts));
  19800. break;
  19801. case 'b': case 'e':
  19802. write_biff_rec(ba, 0x0205 /* BoolErr */, write_BoolErr(R, C, cell.v, os, opts, cell.t));
  19803. break;
  19804. /* TODO: codepage, sst */
  19805. case 's': case 'str':
  19806. if(opts.bookSST) {
  19807. var isst = get_sst_id(opts.Strings, cell.v == null ? "" : String(cell.v), opts.revStrings);
  19808. write_biff_rec(ba, 0x00fd /* LabelSst */, write_LabelSst(R, C, isst, os, opts));
  19809. } else write_biff_rec(ba, 0x0204 /* Label */, write_Label(R, C, (cell.v == null ? "" : String(cell.v)).slice(0,255), os, opts));
  19810. break;
  19811. default:
  19812. write_biff_rec(ba, 0x0201 /* Blank */, write_XLSCell(R, C, os));
  19813. }
  19814. }
  19815. /* [MS-XLS] 2.1.7.20.5 */
  19816. function write_ws_biff8(idx, opts, wb) {
  19817. var ba = buf_array();
  19818. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  19819. var _WB = ((wb||{}).Workbook||{});
  19820. var _sheet = ((_WB.Sheets||[])[idx]||{});
  19821. var dense = Array.isArray(ws);
  19822. var b8 = opts.biff == 8;
  19823. var ref, rr = "", cols = [];
  19824. var range = safe_decode_range(ws['!ref'] || "A1");
  19825. var MAX_ROWS = b8 ? 65536 : 16384;
  19826. if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
  19827. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  19828. range.e.c = Math.min(range.e.c, 0xFF);
  19829. range.e.r = Math.min(range.e.c, MAX_ROWS-1);
  19830. }
  19831. write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
  19832. /* [Uncalced] Index */
  19833. write_biff_rec(ba, 0x000d /* CalcMode */, writeuint16(1));
  19834. write_biff_rec(ba, 0x000c /* CalcCount */, writeuint16(100));
  19835. write_biff_rec(ba, 0x000f /* CalcRefMode */, writebool(true));
  19836. write_biff_rec(ba, 0x0011 /* CalcIter */, writebool(false));
  19837. write_biff_rec(ba, 0x0010 /* CalcDelta */, write_Xnum(0.001));
  19838. write_biff_rec(ba, 0x005f /* CalcSaveRecalc */, writebool(true));
  19839. write_biff_rec(ba, 0x002a /* PrintRowCol */, writebool(false));
  19840. write_biff_rec(ba, 0x002b /* PrintGrid */, writebool(false));
  19841. write_biff_rec(ba, 0x0082 /* GridSet */, writeuint16(1));
  19842. write_biff_rec(ba, 0x0080 /* Guts */, write_Guts([0,0]));
  19843. /* DefaultRowHeight WsBool [Sync] [LPr] [HorizontalPageBreaks] [VerticalPageBreaks] */
  19844. /* Header (string) */
  19845. /* Footer (string) */
  19846. write_biff_rec(ba, 0x0083 /* HCenter */, writebool(false));
  19847. write_biff_rec(ba, 0x0084 /* VCenter */, writebool(false));
  19848. /* ... */
  19849. if(b8) write_ws_cols_biff8(ba, ws["!cols"]);
  19850. /* ... */
  19851. write_biff_rec(ba, 0x0200 /* Dimensions */, write_Dimensions(range, opts));
  19852. /* ... */
  19853. if(b8) ws['!links'] = [];
  19854. var comments = [];
  19855. for(var R = range.s.r; R <= range.e.r; ++R) {
  19856. rr = encode_row(R);
  19857. for(var C = range.s.c; C <= range.e.c; ++C) {
  19858. if(R === range.s.r) cols[C] = encode_col(C);
  19859. ref = cols[C] + rr;
  19860. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  19861. if(!cell) continue;
  19862. /* write cell */
  19863. write_ws_biff8_cell(ba, cell, R, C, opts);
  19864. if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
  19865. if(b8 && cell.c) comments.push([ref, cell.c]);
  19866. }
  19867. }
  19868. var cname = _sheet.CodeName || _sheet.name || s;
  19869. /* ... */
  19870. // if(b8) comments.forEach(function(comment) { write_biff_rec(ba, 0x001c /* Note */, write_NoteSh(comment)); });
  19871. /* ... */
  19872. if(b8) write_biff_rec(ba, 0x023e /* Window2 */, write_Window2((_WB.Views||[])[0]));
  19873. /* ... */
  19874. if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, 0x00e5 /* MergeCells */, write_MergeCells(ws['!merges']));
  19875. /* [LRng] *QUERYTABLE [PHONETICINFO] CONDFMTS */
  19876. if(b8) write_ws_biff8_hlinks(ba, ws);
  19877. /* [DVAL] */
  19878. write_biff_rec(ba, 0x01ba /* CodeName */, write_XLUnicodeString(cname, opts));
  19879. /* *WebPub *CellWatch [SheetExt] */
  19880. if(b8) write_FEAT(ba, ws);
  19881. /* *FEAT11 *RECORD12 */
  19882. write_biff_rec(ba, 0x000a /* EOF */);
  19883. return ba.end();
  19884. }
  19885. /* [MS-XLS] 2.1.7.20.3 */
  19886. function write_biff8_global(wb, bufs, opts) {
  19887. var A = buf_array();
  19888. var _WB = ((wb||{}).Workbook||{});
  19889. var _sheets = (_WB.Sheets||[]);
  19890. var _wb = _WB.WBProps||{};
  19891. var b8 = opts.biff == 8, b5 = opts.biff == 5;
  19892. write_biff_rec(A, 0x0809, write_BOF(wb, 0x05, opts));
  19893. if(opts.bookType == "xla") write_biff_rec(A, 0x0087 /* Addin */);
  19894. write_biff_rec(A, 0x00e1 /* InterfaceHdr */, b8 ? writeuint16(0x04b0) : null);
  19895. write_biff_rec(A, 0x00c1 /* Mms */, writezeroes(2));
  19896. if(b5) write_biff_rec(A, 0x00bf /* ToolbarHdr */);
  19897. if(b5) write_biff_rec(A, 0x00c0 /* ToolbarEnd */);
  19898. write_biff_rec(A, 0x00e2 /* InterfaceEnd */);
  19899. write_biff_rec(A, 0x005c /* WriteAccess */, write_WriteAccess("SheetJS", opts));
  19900. /* [FileSharing] */
  19901. write_biff_rec(A, 0x0042 /* CodePage */, writeuint16(b8 ? 0x04b0 : 0x04E4));
  19902. /* *2047 Lel */
  19903. if(b8) write_biff_rec(A, 0x0161 /* DSF */, writeuint16(0));
  19904. if(b8) write_biff_rec(A, 0x01c0 /* Excel9File */);
  19905. write_biff_rec(A, 0x013d /* RRTabId */, write_RRTabId(wb.SheetNames.length));
  19906. if(b8 && wb.vbaraw) write_biff_rec(A, 0x00d3 /* ObProj */);
  19907. /* [ObNoMacros] */
  19908. if(b8 && wb.vbaraw) {
  19909. var cname = _wb.CodeName || "ThisWorkbook";
  19910. write_biff_rec(A, 0x01ba /* CodeName */, write_XLUnicodeString(cname, opts));
  19911. }
  19912. write_biff_rec(A, 0x009c /* BuiltInFnGroupCount */, writeuint16(0x11));
  19913. /* *FnGroupName *FnGrp12 */
  19914. /* *Lbl */
  19915. /* [OleObjectSize] */
  19916. write_biff_rec(A, 0x0019 /* WinProtect */, writebool(false));
  19917. write_biff_rec(A, 0x0012 /* Protect */, writebool(false));
  19918. write_biff_rec(A, 0x0013 /* Password */, writeuint16(0));
  19919. if(b8) write_biff_rec(A, 0x01af /* Prot4Rev */, writebool(false));
  19920. if(b8) write_biff_rec(A, 0x01bc /* Prot4RevPass */, writeuint16(0));
  19921. write_biff_rec(A, 0x003d /* Window1 */, write_Window1(opts));
  19922. write_biff_rec(A, 0x0040 /* Backup */, writebool(false));
  19923. write_biff_rec(A, 0x008d /* HideObj */, writeuint16(0));
  19924. write_biff_rec(A, 0x0022 /* Date1904 */, writebool(safe1904(wb)=="true"));
  19925. write_biff_rec(A, 0x000e /* CalcPrecision */, writebool(true));
  19926. if(b8) write_biff_rec(A, 0x01b7 /* RefreshAll */, writebool(false));
  19927. write_biff_rec(A, 0x00DA /* BookBool */, writeuint16(0));
  19928. /* ... */
  19929. write_FONTS_biff8(A, wb, opts);
  19930. write_FMTS_biff8(A, wb.SSF, opts);
  19931. write_CELLXFS_biff8(A, opts);
  19932. /* ... */
  19933. if(b8) write_biff_rec(A, 0x0160 /* UsesELFs */, writebool(false));
  19934. var a = A.end();
  19935. var C = buf_array();
  19936. /* METADATA [MTRSettings] [ForceFullCalculation] */
  19937. if(b8) write_biff_rec(C, 0x008C /* Country */, write_Country());
  19938. /* *SUPBOOK *LBL *RTD [RecalcId] *HFPicture *MSODRAWINGGROUP */
  19939. /* BIFF8: [SST *Continue] ExtSST */
  19940. if(b8 && opts.Strings) write_biff_continue(C, 0x00FC /* SST */, write_SST(opts.Strings, opts));
  19941. /* *WebPub [WOpt] [CrErr] [BookExt] *FeatHdr *DConn [THEME] [CompressPictures] [Compat12] [GUIDTypeLib] */
  19942. write_biff_rec(C, 0x000A /* EOF */);
  19943. var c = C.end();
  19944. var B = buf_array();
  19945. var blen = 0, j = 0;
  19946. for(j = 0; j < wb.SheetNames.length; ++j) blen += (b8 ? 12 : 11) + (b8 ? 2 : 1) * wb.SheetNames[j].length;
  19947. var start = a.length + blen + c.length;
  19948. for(j = 0; j < wb.SheetNames.length; ++j) {
  19949. var _sheet = _sheets[j] || ({});
  19950. write_biff_rec(B, 0x0085 /* BoundSheet8 */, write_BoundSheet8({pos:start, hs:_sheet.Hidden||0, dt:0, name:wb.SheetNames[j]}, opts));
  19951. start += bufs[j].length;
  19952. }
  19953. /* 1*BoundSheet8 */
  19954. var b = B.end();
  19955. if(blen != b.length) throw new Error("BS8 " + blen + " != " + b.length);
  19956. var out = [];
  19957. if(a.length) out.push(a);
  19958. if(b.length) out.push(b);
  19959. if(c.length) out.push(c);
  19960. return bconcat(out);
  19961. }
  19962. /* [MS-XLS] 2.1.7.20 Workbook Stream */
  19963. function write_biff8_buf(wb, opts) {
  19964. var o = opts || {};
  19965. var bufs = [];
  19966. if(wb && !wb.SSF) {
  19967. wb.SSF = dup(table_fmt);
  19968. }
  19969. if(wb && wb.SSF) {
  19970. make_ssf(); SSF_load_table(wb.SSF);
  19971. // $FlowIgnore
  19972. o.revssf = evert_num(wb.SSF); o.revssf[wb.SSF[65535]] = 0;
  19973. o.ssf = wb.SSF;
  19974. }
  19975. o.Strings = []; o.Strings.Count = 0; o.Strings.Unique = 0;
  19976. fix_write_opts(o);
  19977. o.cellXfs = [];
  19978. get_cell_style(o.cellXfs, {}, {revssf:{"General":0}});
  19979. if(!wb.Props) wb.Props = {};
  19980. for(var i = 0; i < wb.SheetNames.length; ++i) bufs[bufs.length] = write_ws_biff8(i, o, wb);
  19981. bufs.unshift(write_biff8_global(wb, bufs, o));
  19982. return bconcat(bufs);
  19983. }
  19984. function write_biff_buf(wb, opts) {
  19985. for(var i = 0; i <= wb.SheetNames.length; ++i) {
  19986. var ws = wb.Sheets[wb.SheetNames[i]];
  19987. if(!ws || !ws["!ref"]) continue;
  19988. var range = decode_range(ws["!ref"]);
  19989. if(range.e.c > 255) { // note: 255 is IV
  19990. if(typeof console != "undefined" && console.error) console.error("Worksheet '" + wb.SheetNames[i] + "' extends beyond column IV (255). Data may be lost.");
  19991. }
  19992. }
  19993. var o = opts || {};
  19994. switch(o.biff || 2) {
  19995. case 8: case 5: return write_biff8_buf(wb, opts);
  19996. case 4: case 3: case 2: return write_biff2_buf(wb, opts);
  19997. }
  19998. throw new Error("invalid type " + o.bookType + " for BIFF");
  19999. }
  20000. /* note: browser DOM element cannot see mso- style attrs, must parse */
  20001. function html_to_sheet(str, _opts) {
  20002. var opts = _opts || {};
  20003. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  20004. var ws = opts.dense ? ([]) : ({});
  20005. str = str.replace(/<!--.*?-->/g, "");
  20006. var mtch = str.match(/<table/i);
  20007. if(!mtch) throw new Error("Invalid HTML: could not find <table>");
  20008. var mtch2 = str.match(/<\/table/i);
  20009. var i = mtch.index, j = mtch2 && mtch2.index || str.length;
  20010. var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
  20011. var R = -1, C = 0, RS = 0, CS = 0;
  20012. var range = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
  20013. var merges = [];
  20014. for(i = 0; i < rows.length; ++i) {
  20015. var row = rows[i].trim();
  20016. var hd = row.slice(0,3).toLowerCase();
  20017. if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
  20018. if(hd != "<td" && hd != "<th") continue;
  20019. var cells = row.split(/<\/t[dh]>/i);
  20020. for(j = 0; j < cells.length; ++j) {
  20021. var cell = cells[j].trim();
  20022. if(!cell.match(/<t[dh]/i)) continue;
  20023. var m = cell, cc = 0;
  20024. /* TODO: parse styles etc */
  20025. while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
  20026. for(var midx = 0; midx < merges.length; ++midx) {
  20027. var _merge = merges[midx];
  20028. if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
  20029. }
  20030. var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
  20031. CS = tag.colspan ? +tag.colspan : 1;
  20032. if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
  20033. var _t = tag.t || tag["data-t"] || "";
  20034. /* TODO: generate stub cells */
  20035. if(!m.length) { C += CS; continue; }
  20036. m = htmldecode(m);
  20037. if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
  20038. if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
  20039. if(!m.length) { C += CS; continue; }
  20040. var o = {t:'s', v:m};
  20041. if(opts.raw || !m.trim().length || _t == 's'){}
  20042. else if(m === 'TRUE') o = {t:'b', v:true};
  20043. else if(m === 'FALSE') o = {t:'b', v:false};
  20044. else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
  20045. else if(!isNaN(fuzzydate(m).getDate())) {
  20046. o = ({t:'d', v:parseDate(m)});
  20047. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  20048. o.z = opts.dateNF || table_fmt[14];
  20049. }
  20050. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
  20051. else ws[encode_cell({r:R, c:C})] = o;
  20052. C += CS;
  20053. }
  20054. }
  20055. ws['!ref'] = encode_range(range);
  20056. if(merges.length) ws["!merges"] = merges;
  20057. return ws;
  20058. }
  20059. function make_html_row(ws, r, R, o) {
  20060. var M = (ws['!merges'] ||[]);
  20061. var oo = [];
  20062. var sp = ({});
  20063. for(var C = r.s.c; C <= r.e.c; ++C) {
  20064. var RS = 0, CS = 0;
  20065. for(var j = 0; j < M.length; ++j) {
  20066. if(M[j].s.r > R || M[j].s.c > C) continue;
  20067. if(M[j].e.r < R || M[j].e.c < C) continue;
  20068. if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
  20069. RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
  20070. }
  20071. if(RS < 0) continue;
  20072. var coord = encode_cell({r:R,c:C});
  20073. var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
  20074. /* TODO: html entities */
  20075. var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
  20076. sp = ({});
  20077. if(RS > 1) sp.rowspan = RS;
  20078. if(CS > 1) sp.colspan = CS;
  20079. if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
  20080. else if(cell) {
  20081. sp["data-t"] = cell && cell.t || 'z';
  20082. if(cell.v != null) sp["data-v"] = cell.v;
  20083. if(cell.z != null) sp["data-z"] = cell.z;
  20084. if(cell.l && (cell.l.Target || "#").charAt(0) != "#") w = '<a href="' + cell.l.Target +'">' + w + '</a>';
  20085. }
  20086. sp.id = (o.id || "sjs") + "-" + coord;
  20087. oo.push(writextag('td', w, sp));
  20088. }
  20089. var preamble = "<tr>";
  20090. return preamble + oo.join("") + "</tr>";
  20091. }
  20092. var HTML_BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
  20093. var HTML_END = '</body></html>';
  20094. function html_to_workbook(str, opts) {
  20095. var mtch = str.match(/<table[\s\S]*?>[\s\S]*?<\/table>/gi);
  20096. if(!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find <table>");
  20097. if(mtch.length == 1) {
  20098. var w = sheet_to_workbook(html_to_sheet(mtch[0], opts), opts);
  20099. w.bookType = "html";
  20100. return w;
  20101. }
  20102. var wb = book_new();
  20103. mtch.forEach(function(s, idx) { book_append_sheet(wb, html_to_sheet(s, opts), "Sheet" + (idx+1)); });
  20104. wb.bookType = "html";
  20105. return wb;
  20106. }
  20107. function make_html_preamble(ws, R, o) {
  20108. var out = [];
  20109. return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
  20110. }
  20111. function sheet_to_html(ws, opts/*, wb:?Workbook*/) {
  20112. var o = opts || {};
  20113. var header = o.header != null ? o.header : HTML_BEGIN;
  20114. var footer = o.footer != null ? o.footer : HTML_END;
  20115. var out = [header];
  20116. var r = decode_range(ws['!ref']);
  20117. o.dense = Array.isArray(ws);
  20118. out.push(make_html_preamble(ws, r, o));
  20119. for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
  20120. out.push("</table>" + footer);
  20121. return out.join("");
  20122. }
  20123. function sheet_add_dom(ws, table, _opts) {
  20124. var rows = table.rows;
  20125. if(!rows) {
  20126. /* not an HTML TABLE */
  20127. throw "Unsupported origin when " + table.tagName + " is not a TABLE";
  20128. }
  20129. var opts = _opts || {};
  20130. if(DENSE != null) opts.dense = DENSE;
  20131. var or_R = 0, or_C = 0;
  20132. if(opts.origin != null) {
  20133. if(typeof opts.origin == 'number') or_R = opts.origin;
  20134. else {
  20135. var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
  20136. or_R = _origin.r; or_C = _origin.c;
  20137. }
  20138. }
  20139. var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
  20140. var range = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
  20141. if(ws["!ref"]) {
  20142. var _range = decode_range(ws["!ref"]);
  20143. range.s.r = Math.min(range.s.r, _range.s.r);
  20144. range.s.c = Math.min(range.s.c, _range.s.c);
  20145. range.e.r = Math.max(range.e.r, _range.e.r);
  20146. range.e.c = Math.max(range.e.c, _range.e.c);
  20147. if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
  20148. }
  20149. var merges = [], midx = 0;
  20150. var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  20151. var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  20152. if(!ws["!cols"]) ws['!cols'] = [];
  20153. for(; _R < rows.length && R < sheetRows; ++_R) {
  20154. var row = rows[_R];
  20155. if (is_dom_element_hidden(row)) {
  20156. if (opts.display) continue;
  20157. rowinfo[R] = {hidden: true};
  20158. }
  20159. var elts = (row.cells);
  20160. for(_C = C = 0; _C < elts.length; ++_C) {
  20161. var elt = elts[_C];
  20162. if (opts.display && is_dom_element_hidden(elt)) continue;
  20163. var v = elt.hasAttribute('data-v') ? elt.getAttribute('data-v') : elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
  20164. var z = elt.getAttribute('data-z') || elt.getAttribute('z');
  20165. for(midx = 0; midx < merges.length; ++midx) {
  20166. var m = merges[midx];
  20167. 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; }
  20168. }
  20169. /* TODO: figure out how to extract nonstandard mso- style */
  20170. CS = +elt.getAttribute("colspan") || 1;
  20171. 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}});
  20172. var o = {t:'s', v:v};
  20173. var _t = elt.getAttribute("data-t") || elt.getAttribute("t") || "";
  20174. if(v != null) {
  20175. if(v.length == 0) o.t = _t || 'z';
  20176. else if(opts.raw || v.trim().length == 0 || _t == "s"){}
  20177. else if(v === 'TRUE') o = {t:'b', v:true};
  20178. else if(v === 'FALSE') o = {t:'b', v:false};
  20179. else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
  20180. else if(!isNaN(fuzzydate(v).getDate())) {
  20181. o = ({t:'d', v:parseDate(v)});
  20182. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  20183. o.z = opts.dateNF || table_fmt[14];
  20184. }
  20185. }
  20186. if(o.z === undefined && z != null) o.z = z;
  20187. /* The first link is used. Links are assumed to be fully specified.
  20188. * TODO: The right way to process relative links is to make a new <a> */
  20189. var l = "", Aelts = elt.getElementsByTagName("A");
  20190. if(Aelts && Aelts.length) for(var Aelti = 0; Aelti < Aelts.length; ++Aelti) if(Aelts[Aelti].hasAttribute("href")) {
  20191. l = Aelts[Aelti].getAttribute("href"); if(l.charAt(0) != "#") break;
  20192. }
  20193. if(l && l.charAt(0) != "#" && l.slice(0, 11).toLowerCase() != 'javascript:') o.l = ({ Target: l });
  20194. if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
  20195. else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
  20196. if(range.e.c < C + or_C) range.e.c = C + or_C;
  20197. C += CS;
  20198. }
  20199. ++R;
  20200. }
  20201. if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
  20202. range.e.r = Math.max(range.e.r, R - 1 + or_R);
  20203. ws['!ref'] = encode_range(range);
  20204. 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
  20205. return ws;
  20206. }
  20207. function parse_dom_table(table, _opts) {
  20208. var opts = _opts || {};
  20209. var ws = opts.dense ? ([]) : ({});
  20210. return sheet_add_dom(ws, table, _opts);
  20211. }
  20212. function table_to_book(table, opts) {
  20213. var o = sheet_to_workbook(parse_dom_table(table, opts), opts);
  20214. //o.bookType = "dom"; // TODO: define a type for this
  20215. return o;
  20216. }
  20217. function is_dom_element_hidden(element) {
  20218. var display = '';
  20219. var get_computed_style = get_get_computed_style_function(element);
  20220. if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
  20221. if(!display) display = element.style && element.style.display;
  20222. return display === 'none';
  20223. }
  20224. /* global getComputedStyle */
  20225. function get_get_computed_style_function(element) {
  20226. // The proper getComputedStyle implementation is the one defined in the element window
  20227. if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
  20228. // If it is not available, try to get one from the global namespace
  20229. if(typeof getComputedStyle === 'function') return getComputedStyle;
  20230. return null;
  20231. }
  20232. /* OpenDocument */
  20233. function parse_text_p(text) {
  20234. /* 6.1.2 White Space Characters */
  20235. var fixed = text
  20236. .replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ")
  20237. .replace(/<text:s\/>/g," ")
  20238. .replace(/<text:s text:c="(\d+)"\/>/g, function($$,$1) { return Array(parseInt($1,10)+1).join(" "); })
  20239. .replace(/<text:tab[^>]*\/>/g,"\t")
  20240. .replace(/<text:line-break\/>/g,"\n");
  20241. var v = unescapexml(fixed.replace(/<[^>]*>/g,""));
  20242. return [v];
  20243. }
  20244. /* Note: ODS can stick styles in content.xml or styles.xml, FODS blurs lines */
  20245. function parse_ods_styles(d, _opts, _nfm) {
  20246. var number_format_map = _nfm || {};
  20247. var str = xlml_normalize(d);
  20248. xlmlregex.lastIndex = 0;
  20249. str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  20250. var Rn, NFtag, NF = "", tNF = "", y, etpos = 0, tidx = -1, infmt = false, payload = "";
  20251. while((Rn = xlmlregex.exec(str))) {
  20252. switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {
  20253. /* Number Format Definitions */
  20254. case 'number-style': // <number:number-style> 16.29.2
  20255. case 'currency-style': // <number:currency-style> 16.29.8
  20256. case 'percentage-style': // <number:percentage-style> 16.29.10
  20257. case 'date-style': // <number:date-style> 16.29.11
  20258. case 'time-style': // <number:time-style> 16.29.19
  20259. case 'text-style': // <number:text-style> 16.29.26
  20260. if(Rn[1]==='/') {
  20261. infmt = false;
  20262. if(NFtag['truncate-on-overflow'] == "false") {
  20263. if(NF.match(/h/)) NF = NF.replace(/h+/, "[$&]");
  20264. else if(NF.match(/m/)) NF = NF.replace(/m+/, "[$&]");
  20265. else if(NF.match(/s/)) NF = NF.replace(/s+/, "[$&]");
  20266. }
  20267. number_format_map[NFtag.name] = NF;
  20268. NF = "";
  20269. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20270. infmt = true;
  20271. NF = "";
  20272. NFtag = parsexmltag(Rn[0], false);
  20273. } break;
  20274. // LibreOffice bug https://bugs.documentfoundation.org/show_bug.cgi?id=149484
  20275. case 'boolean-style': // <number:boolean-style> 16.29.24
  20276. if(Rn[1]==='/') {
  20277. infmt = false;
  20278. number_format_map[NFtag.name] = "General";
  20279. NF = "";
  20280. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20281. infmt = true;
  20282. NF = "";
  20283. NFtag = parsexmltag(Rn[0], false);
  20284. } break;
  20285. /* Number Format Elements */
  20286. case 'boolean': // <number:boolean> 16.29.25
  20287. NF += "General"; // ODF spec is unfortunately underspecified here
  20288. break;
  20289. case 'text': // <number:text> 16.29.27
  20290. if(Rn[1]==='/') {
  20291. payload = str.slice(tidx, xlmlregex.lastIndex - Rn[0].length);
  20292. // NOTE: Excel has a different interpretation of "%%" and friends
  20293. if(payload == "%" && NFtag[0] == '<number:percentage-style') NF += "%";
  20294. else NF += '"' + payload.replace(/"/g, '""') + '"';
  20295. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20296. tidx = xlmlregex.lastIndex;
  20297. } break;
  20298. case 'day': { // <number:day> 16.29.12
  20299. y = parsexmltag(Rn[0], false);
  20300. switch(y["style"]) {
  20301. case "short": NF += "d"; break;
  20302. case "long": NF += "dd"; break;
  20303. default: NF += "dd"; break; // TODO: error condition
  20304. }
  20305. } break;
  20306. case 'day-of-week': { // <number:day-of-week> 16.29.16
  20307. y = parsexmltag(Rn[0], false);
  20308. switch(y["style"]) {
  20309. case "short": NF += "ddd"; break;
  20310. case "long": NF += "dddd"; break;
  20311. default: NF += "ddd"; break;
  20312. }
  20313. } break;
  20314. case 'era': { // <number:era> 16.29.15 TODO: proper mapping
  20315. y = parsexmltag(Rn[0], false);
  20316. switch(y["style"]) {
  20317. case "short": NF += "ee"; break;
  20318. case "long": NF += "eeee"; break;
  20319. default: NF += "eeee"; break; // TODO: error condition
  20320. }
  20321. } break;
  20322. case 'hours': { // <number:hours> 16.29.20
  20323. y = parsexmltag(Rn[0], false);
  20324. switch(y["style"]) {
  20325. case "short": NF += "h"; break;
  20326. case "long": NF += "hh"; break;
  20327. default: NF += "hh"; break; // TODO: error condition
  20328. }
  20329. } break;
  20330. case 'minutes': { // <number:minutes> 16.29.21
  20331. y = parsexmltag(Rn[0], false);
  20332. switch(y["style"]) {
  20333. case "short": NF += "m"; break;
  20334. case "long": NF += "mm"; break;
  20335. default: NF += "mm"; break; // TODO: error condition
  20336. }
  20337. } break;
  20338. case 'month': { // <number:month> 16.29.13
  20339. y = parsexmltag(Rn[0], false);
  20340. if(y["textual"]) NF += "mm";
  20341. switch(y["style"]) {
  20342. case "short": NF += "m"; break;
  20343. case "long": NF += "mm"; break;
  20344. default: NF += "m"; break;
  20345. }
  20346. } break;
  20347. case 'seconds': { // <number:seconds> 16.29.22
  20348. y = parsexmltag(Rn[0], false);
  20349. switch(y["style"]) {
  20350. case "short": NF += "s"; break;
  20351. case "long": NF += "ss"; break;
  20352. default: NF += "ss"; break; // TODO: error condition
  20353. }
  20354. if(y["decimal-places"]) NF += "." + fill("0", +y["decimal-places"]);
  20355. } break;
  20356. case 'year': { // <number:year> 16.29.14
  20357. y = parsexmltag(Rn[0], false);
  20358. switch(y["style"]) {
  20359. case "short": NF += "yy"; break;
  20360. case "long": NF += "yyyy"; break;
  20361. default: NF += "yy"; break; // TODO: error condition
  20362. }
  20363. } break;
  20364. case 'am-pm': // <number:am-pm> 16.29.23
  20365. NF += "AM/PM"; // LO autocorrects A/P -> AM/PM
  20366. break;
  20367. case 'week-of-year': // <number:week-of-year> 16.29.17
  20368. case 'quarter': // <number:quarter> 16.29.18
  20369. console.error("Excel does not support ODS format token " + Rn[3]);
  20370. break;
  20371. case 'fill-character': // <number:fill-character> 16.29.5
  20372. if(Rn[1]==='/') {
  20373. payload = str.slice(tidx, xlmlregex.lastIndex - Rn[0].length);
  20374. // NOTE: Excel has a different interpretation of "%%" and friends
  20375. NF += '"' + payload.replace(/"/g, '""') + '"*';
  20376. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20377. tidx = xlmlregex.lastIndex;
  20378. } break;
  20379. case 'scientific-number': // <number:scientific-number> 16.29.6
  20380. // TODO: find a mapping for all parameters
  20381. y = parsexmltag(Rn[0], false);
  20382. NF += "0." + fill("0", +y["min-decimal-places"] || +y["decimal-places"] || 2) + fill("?", +y["decimal-places"] - +y["min-decimal-places"] || 0) + "E" + (parsexmlbool(y["forced-exponent-sign"]) ? "+" : "") + fill("0", +y["min-exponent-digits"] || 2);
  20383. break;
  20384. case 'fraction': // <number:fraction> 16.29.7
  20385. // TODO: find a mapping for all parameters
  20386. y = parsexmltag(Rn[0], false);
  20387. if(!+y["min-integer-digits"]) NF += "#";
  20388. else NF += fill("0", +y["min-integer-digits"]);
  20389. NF += " ";
  20390. NF += fill("?", +y["min-numerator-digits"] || 1);
  20391. NF += "/";
  20392. if(+y["denominator-value"]) NF += y["denominator-value"];
  20393. else NF += fill("?", +y["min-denominator-digits"] || 1);
  20394. break;
  20395. case 'currency-symbol': // <number:currency-symbol> 16.29.9
  20396. // TODO: localization with [$-...]
  20397. if(Rn[1]==='/') {
  20398. NF += '"' + str.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"';
  20399. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20400. tidx = xlmlregex.lastIndex;
  20401. } else NF += "$";
  20402. break;
  20403. case 'text-properties': // <style:text-properties> 16.29.29
  20404. y = parsexmltag(Rn[0], false);
  20405. switch((y["color"]||"").toLowerCase().replace("#", "")) {
  20406. case "ff0000": case "red": NF = "[Red]" + NF; break;
  20407. }
  20408. break;
  20409. case 'text-content': // <number:text-content> 16.29.28
  20410. NF += "@";
  20411. break;
  20412. case 'map': // <style:map> 16.3
  20413. // TODO: handle more complex maps
  20414. y = parsexmltag(Rn[0], false);
  20415. if(unescapexml(y["condition"]) == "value()>=0") NF = number_format_map[y["apply-style-name"]] + ";" + NF;
  20416. else console.error("ODS number format may be incorrect: " + y["condition"]);
  20417. break;
  20418. case 'number': // <number:number> 16.29.3
  20419. // TODO: handle all the attributes
  20420. if(Rn[1]==='/') break;
  20421. y = parsexmltag(Rn[0], false);
  20422. tNF = "";
  20423. tNF += fill("0", +y["min-integer-digits"] || 1);
  20424. if(parsexmlbool(y["grouping"])) tNF = commaify(fill("#", Math.max(0, 4 - tNF.length)) + tNF);
  20425. if(+y["min-decimal-places"] || +y["decimal-places"]) tNF += ".";
  20426. if(+y["min-decimal-places"]) tNF += fill("0", +y["min-decimal-places"] || 1);
  20427. if(+y["decimal-places"] - (+y["min-decimal-places"]||0)) tNF += fill("0", +y["decimal-places"] - (+y["min-decimal-places"]||0)); // TODO: should this be "#" ?
  20428. NF += tNF;
  20429. break;
  20430. case 'embedded-text': // <number:embedded-text> 16.29.4
  20431. // TODO: verify interplay with grouping et al
  20432. if(Rn[1]==='/') {
  20433. if(etpos == 0) NF += '"' + str.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"';
  20434. else NF = NF.slice(0, etpos) + '"' + str.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"' + NF.slice(etpos);
  20435. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20436. tidx = xlmlregex.lastIndex;
  20437. etpos = -+parsexmltag(Rn[0], false)["position"] || 0;
  20438. } break;
  20439. }}
  20440. return number_format_map;
  20441. }
  20442. function parse_content_xml(d, _opts, _nfm) {
  20443. var opts = _opts || {};
  20444. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  20445. var str = xlml_normalize(d);
  20446. var state = [], tmp;
  20447. var tag;
  20448. var nfidx, NF = "", pidx = 0;
  20449. var sheetag;
  20450. var rowtag;
  20451. var Sheets = {}, SheetNames = [];
  20452. var ws = opts.dense ? ([]) : ({});
  20453. var Rn, q;
  20454. var ctag = ({value:""});
  20455. var textp = "", textpidx = 0, textptag;
  20456. var textR = [];
  20457. var R = -1, C = -1, range = {s: {r:1000000,c:10000000}, e: {r:0, c:0}};
  20458. var row_ol = 0;
  20459. var number_format_map = _nfm || {}, styles = {};
  20460. var merges = [], mrange = {}, mR = 0, mC = 0;
  20461. var rowinfo = [], rowpeat = 1, colpeat = 1;
  20462. var arrayf = [];
  20463. var WB = {Names:[], WBProps:{}};
  20464. var atag = ({});
  20465. var _Ref = ["", ""];
  20466. var comments = [], comment = ({});
  20467. var creator = "", creatoridx = 0;
  20468. var isstub = false, intable = false;
  20469. var i = 0;
  20470. var baddate = 0;
  20471. xlmlregex.lastIndex = 0;
  20472. str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  20473. while((Rn = xlmlregex.exec(str))) switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {
  20474. case 'table': case '工作表': // 9.1.2 <table:table>
  20475. if(Rn[1]==='/') {
  20476. if(range.e.c >= range.s.c && range.e.r >= range.s.r) ws['!ref'] = encode_range(range);
  20477. else ws['!ref'] = "A1:A1";
  20478. if(opts.sheetRows > 0 && opts.sheetRows <= range.e.r) {
  20479. ws['!fullref'] = ws['!ref'];
  20480. range.e.r = opts.sheetRows - 1;
  20481. ws['!ref'] = encode_range(range);
  20482. }
  20483. if(merges.length) ws['!merges'] = merges;
  20484. if(rowinfo.length) ws["!rows"] = rowinfo;
  20485. sheetag.name = sheetag['名称'] || sheetag.name;
  20486. if(typeof JSON !== 'undefined') JSON.stringify(sheetag);
  20487. SheetNames.push(sheetag.name);
  20488. Sheets[sheetag.name] = ws;
  20489. intable = false;
  20490. }
  20491. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20492. sheetag = parsexmltag(Rn[0], false);
  20493. R = C = -1;
  20494. range.s.r = range.s.c = 10000000; range.e.r = range.e.c = 0;
  20495. ws = opts.dense ? ([]) : ({}); merges = [];
  20496. rowinfo = [];
  20497. intable = true;
  20498. }
  20499. break;
  20500. case 'table-row-group': // 9.1.9 <table:table-row-group>
  20501. if(Rn[1] === "/") --row_ol; else ++row_ol;
  20502. break;
  20503. case 'table-row': case '行': // 9.1.3 <table:table-row>
  20504. if(Rn[1] === '/') { R+=rowpeat; rowpeat = 1; break; }
  20505. rowtag = parsexmltag(Rn[0], false);
  20506. if(rowtag['行号']) R = rowtag['行号'] - 1; else if(R == -1) R = 0;
  20507. rowpeat = +rowtag['number-rows-repeated'] || 1;
  20508. /* TODO: remove magic */
  20509. if(rowpeat < 10) for(i = 0; i < rowpeat; ++i) if(row_ol > 0) rowinfo[R + i] = {level: row_ol};
  20510. C = -1; break;
  20511. case 'covered-table-cell': // 9.1.5 <table:covered-table-cell>
  20512. if(Rn[1] !== '/') ++C;
  20513. if(opts.sheetStubs) {
  20514. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = {t:'z'}; }
  20515. else ws[encode_cell({r:R,c:C})] = {t:'z'};
  20516. }
  20517. textp = ""; textR = [];
  20518. break; /* stub */
  20519. case 'table-cell': case '数据':
  20520. if(Rn[0].charAt(Rn[0].length-2) === '/') {
  20521. ++C;
  20522. ctag = parsexmltag(Rn[0], false);
  20523. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  20524. q = ({t:'z', v:null});
  20525. if(ctag.formula && opts.cellFormula != false) q.f = ods_to_csf_formula(unescapexml(ctag.formula));
  20526. if(ctag["style-name"] && styles[ctag["style-name"]]) q.z = styles[ctag["style-name"]];
  20527. if((ctag['数据类型'] || ctag['value-type']) == "string") {
  20528. q.t = "s"; q.v = unescapexml(ctag['string-value'] || "");
  20529. if(opts.dense) {
  20530. if(!ws[R]) ws[R] = [];
  20531. ws[R][C] = q;
  20532. } else {
  20533. ws[encode_cell({r:R,c:C})] = q;
  20534. }
  20535. }
  20536. C+= colpeat-1;
  20537. } else if(Rn[1]!=='/') {
  20538. ++C;
  20539. textp = ""; textpidx = 0; textR = [];
  20540. colpeat = 1;
  20541. var rptR = rowpeat ? R + rowpeat - 1 : R;
  20542. if(C > range.e.c) range.e.c = C;
  20543. if(C < range.s.c) range.s.c = C;
  20544. if(R < range.s.r) range.s.r = R;
  20545. if(rptR > range.e.r) range.e.r = rptR;
  20546. ctag = parsexmltag(Rn[0], false);
  20547. comments = []; comment = ({});
  20548. q = ({t:ctag['数据类型'] || ctag['value-type'], v:null});
  20549. if(ctag["style-name"] && styles[ctag["style-name"]]) q.z = styles[ctag["style-name"]];
  20550. if(opts.cellFormula) {
  20551. if(ctag.formula) ctag.formula = unescapexml(ctag.formula);
  20552. if(ctag['number-matrix-columns-spanned'] && ctag['number-matrix-rows-spanned']) {
  20553. mR = parseInt(ctag['number-matrix-rows-spanned'],10) || 0;
  20554. mC = parseInt(ctag['number-matrix-columns-spanned'],10) || 0;
  20555. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  20556. q.F = encode_range(mrange);
  20557. arrayf.push([mrange, q.F]);
  20558. }
  20559. if(ctag.formula) q.f = ods_to_csf_formula(ctag.formula);
  20560. else for(i = 0; i < arrayf.length; ++i)
  20561. if(R >= arrayf[i][0].s.r && R <= arrayf[i][0].e.r)
  20562. if(C >= arrayf[i][0].s.c && C <= arrayf[i][0].e.c)
  20563. q.F = arrayf[i][1];
  20564. }
  20565. if(ctag['number-columns-spanned'] || ctag['number-rows-spanned']) {
  20566. mR = parseInt(ctag['number-rows-spanned'],10) || 0;
  20567. mC = parseInt(ctag['number-columns-spanned'],10) || 0;
  20568. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  20569. merges.push(mrange);
  20570. }
  20571. /* 19.675.2 table:number-columns-repeated */
  20572. if(ctag['number-columns-repeated']) colpeat = parseInt(ctag['number-columns-repeated'], 10);
  20573. /* 19.385 office:value-type */
  20574. switch(q.t) {
  20575. case 'boolean': q.t = 'b'; q.v = parsexmlbool(ctag['boolean-value']) || (+ctag['boolean-value'] >= 1); break;
  20576. case 'float': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  20577. case 'percentage': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  20578. case 'currency': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  20579. case 'date': q.t = 'd'; q.v = parseDate(ctag['date-value']);
  20580. if(!opts.cellDates) { q.t = 'n'; q.v = datenum(q.v, WB.WBProps.date1904) - baddate; }
  20581. if(!q.z) q.z = 'm/d/yy'; break;
  20582. case 'time': q.t = 'n'; q.v = parse_isodur(ctag['time-value'])/86400;
  20583. if(opts.cellDates) { q.t = 'd'; q.v = numdate(q.v); }
  20584. if(!q.z) q.z = 'HH:MM:SS'; break;
  20585. case 'number': q.t = 'n'; q.v = parseFloat(ctag['数据数值']); break;
  20586. default:
  20587. if(q.t === 'string' || q.t === 'text' || !q.t) {
  20588. q.t = 's';
  20589. if(ctag['string-value'] != null) { textp = unescapexml(ctag['string-value']); textR = []; }
  20590. } else throw new Error('Unsupported value type ' + q.t);
  20591. }
  20592. } else {
  20593. isstub = false;
  20594. if(q.t === 's') {
  20595. q.v = textp || '';
  20596. if(textR.length) q.R = textR;
  20597. isstub = textpidx == 0;
  20598. }
  20599. if(atag.Target) q.l = atag;
  20600. if(comments.length > 0) { q.c = comments; comments = []; }
  20601. if(textp && opts.cellText !== false) q.w = textp;
  20602. if(isstub) { q.t = "z"; delete q.v; }
  20603. if(!isstub || opts.sheetStubs) {
  20604. if(!(opts.sheetRows && opts.sheetRows <= R)) {
  20605. for(var rpt = 0; rpt < rowpeat; ++rpt) {
  20606. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  20607. if(opts.dense) {
  20608. if(!ws[R + rpt]) ws[R + rpt] = [];
  20609. ws[R + rpt][C] = rpt == 0 ? q : dup(q);
  20610. while(--colpeat > 0) ws[R + rpt][C + colpeat] = dup(q);
  20611. } else {
  20612. ws[encode_cell({r:R + rpt,c:C})] = q;
  20613. while(--colpeat > 0) ws[encode_cell({r:R + rpt,c:C + colpeat})] = dup(q);
  20614. }
  20615. if(range.e.c <= C) range.e.c = C;
  20616. }
  20617. }
  20618. }
  20619. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  20620. C += colpeat-1; colpeat = 0;
  20621. q = {};
  20622. textp = ""; textR = [];
  20623. }
  20624. atag = ({});
  20625. break; // 9.1.4 <table:table-cell>
  20626. /* pure state */
  20627. case 'document': // TODO: <office:document> is the root for FODS
  20628. case 'document-content': case '电子表格文档': // 3.1.3.2 <office:document-content>
  20629. case 'spreadsheet': case '主体': // 3.7 <office:spreadsheet>
  20630. case 'scripts': // 3.12 <office:scripts>
  20631. case 'styles': // TODO <office:styles>
  20632. case 'font-face-decls': // 3.14 <office:font-face-decls>
  20633. case 'master-styles': // 3.15.4 <office:master-styles> -- relevant for FODS
  20634. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  20635. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  20636. break;
  20637. case 'annotation': // 14.1 <office:annotation>
  20638. if(Rn[1]==='/'){
  20639. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  20640. comment.t = textp;
  20641. if(textR.length) comment.R = textR;
  20642. comment.a = creator;
  20643. comments.push(comment);
  20644. }
  20645. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {state.push([Rn[3], false]);}
  20646. creator = ""; creatoridx = 0;
  20647. textp = ""; textpidx = 0; textR = [];
  20648. break;
  20649. case 'creator': // 4.3.2.7 <dc:creator>
  20650. if(Rn[1]==='/') { creator = str.slice(creatoridx,Rn.index); }
  20651. else creatoridx = Rn.index + Rn[0].length;
  20652. break;
  20653. /* ignore state */
  20654. case 'meta': case '元数据': // TODO: <office:meta> <uof:元数据> FODS/UOF
  20655. case 'settings': // TODO: <office:settings>
  20656. case 'config-item-set': // TODO: <office:config-item-set>
  20657. case 'config-item-map-indexed': // TODO: <office:config-item-map-indexed>
  20658. case 'config-item-map-entry': // TODO: <office:config-item-map-entry>
  20659. case 'config-item-map-named': // TODO: <office:config-item-map-entry>
  20660. case 'shapes': // 9.2.8 <table:shapes>
  20661. case 'frame': // 10.4.2 <draw:frame>
  20662. case 'text-box': // 10.4.3 <draw:text-box>
  20663. case 'image': // 10.4.4 <draw:image>
  20664. case 'data-pilot-tables': // 9.6.2 <table:data-pilot-tables>
  20665. case 'list-style': // 16.30 <text:list-style>
  20666. case 'form': // 13.13 <form:form>
  20667. case 'dde-links': // 9.8 <table:dde-links>
  20668. case 'event-listeners': // TODO
  20669. case 'chart': // TODO
  20670. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  20671. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], false]);
  20672. textp = ""; textpidx = 0; textR = [];
  20673. break;
  20674. case 'scientific-number': // <number:scientific-number>
  20675. case 'currency-symbol': // <number:currency-symbol>
  20676. case 'fill-character': // 16.29.5 <number:fill-character>
  20677. break;
  20678. case 'text-style': // 16.27.25 <number:text-style>
  20679. case 'boolean-style': // 16.27.23 <number:boolean-style>
  20680. case 'number-style': // 16.27.2 <number:number-style>
  20681. case 'currency-style': // 16.29.8 <number:currency-style>
  20682. case 'percentage-style': // 16.27.9 <number:percentage-style>
  20683. case 'date-style': // 16.27.10 <number:date-style>
  20684. case 'time-style': // 16.27.18 <number:time-style>
  20685. if(Rn[1]==='/'){
  20686. var xlmlidx = xlmlregex.lastIndex;
  20687. parse_ods_styles(str.slice(nfidx, xlmlregex.lastIndex), _opts, number_format_map);
  20688. xlmlregex.lastIndex = xlmlidx;
  20689. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  20690. nfidx = xlmlregex.lastIndex - Rn[0].length;
  20691. } break;
  20692. case 'script': break; // 3.13 <office:script>
  20693. case 'libraries': break; // TODO: <ooo:libraries>
  20694. case 'automatic-styles': break; // 3.15.3 <office:automatic-styles>
  20695. case 'default-style': // TODO: <style:default-style>
  20696. case 'page-layout': break; // TODO: <style:page-layout>
  20697. case 'style': { // 16.2 <style:style>
  20698. var styletag = parsexmltag(Rn[0], false);
  20699. if(styletag["family"] == "table-cell" && number_format_map[styletag["data-style-name"]]) styles[styletag["name"]] = number_format_map[styletag["data-style-name"]];
  20700. } break;
  20701. case 'map': break; // 16.3 <style:map>
  20702. case 'font-face': break; // 16.21 <style:font-face>
  20703. case 'paragraph-properties': break; // 17.6 <style:paragraph-properties>
  20704. case 'table-properties': break; // 17.15 <style:table-properties>
  20705. case 'table-column-properties': break; // 17.16 <style:table-column-properties>
  20706. case 'table-row-properties': break; // 17.17 <style:table-row-properties>
  20707. case 'table-cell-properties': break; // 17.18 <style:table-cell-properties>
  20708. case 'number': // 16.27.3 <number:number>
  20709. break;
  20710. case 'fraction': break; // TODO 16.27.6 <number:fraction>
  20711. case 'day': // 16.27.11 <number:day>
  20712. case 'month': // 16.27.12 <number:month>
  20713. case 'year': // 16.27.13 <number:year>
  20714. case 'era': // 16.27.14 <number:era>
  20715. case 'day-of-week': // 16.27.15 <number:day-of-week>
  20716. case 'week-of-year': // 16.27.16 <number:week-of-year>
  20717. case 'quarter': // 16.27.17 <number:quarter>
  20718. case 'hours': // 16.27.19 <number:hours>
  20719. case 'minutes': // 16.27.20 <number:minutes>
  20720. case 'seconds': // 16.27.21 <number:seconds>
  20721. case 'am-pm': // 16.27.22 <number:am-pm>
  20722. break;
  20723. case 'boolean': break; // 16.27.24 <number:boolean>
  20724. case 'text': // 16.27.26 <number:text>
  20725. if(Rn[0].slice(-2) === "/>") break;
  20726. else if(Rn[1]==="/") switch(state[state.length-1][0]) {
  20727. case 'number-style':
  20728. case 'date-style':
  20729. case 'time-style':
  20730. NF += str.slice(pidx, Rn.index);
  20731. break;
  20732. }
  20733. else pidx = Rn.index + Rn[0].length;
  20734. break;
  20735. case 'named-range': // 9.4.12 <table:named-range>
  20736. tag = parsexmltag(Rn[0], false);
  20737. _Ref = ods_to_csf_3D(tag['cell-range-address']);
  20738. var nrange = ({Name:tag.name, Ref:_Ref[0] + '!' + _Ref[1]});
  20739. if(intable) nrange.Sheet = SheetNames.length;
  20740. WB.Names.push(nrange);
  20741. break;
  20742. case 'text-content': break; // 16.27.27 <number:text-content>
  20743. case 'text-properties': break; // 16.27.27 <style:text-properties>
  20744. case 'embedded-text': break; // 16.27.4 <number:embedded-text>
  20745. case 'body': case '电子表格': break; // 3.3 16.9.6 19.726.3
  20746. case 'forms': break; // 12.25.2 13.2
  20747. case 'table-column': break; // 9.1.6 <table:table-column>
  20748. case 'table-header-rows': break; // 9.1.7 <table:table-header-rows>
  20749. case 'table-rows': break; // 9.1.12 <table:table-rows>
  20750. /* TODO: outline levels */
  20751. case 'table-column-group': break; // 9.1.10 <table:table-column-group>
  20752. case 'table-header-columns': break; // 9.1.11 <table:table-header-columns>
  20753. case 'table-columns': break; // 9.1.12 <table:table-columns>
  20754. case 'null-date': // 9.4.2 <table:null-date>
  20755. tag = parsexmltag(Rn[0], false);
  20756. switch(tag["date-value"]) {
  20757. case "1904-01-01": WB.WBProps.date1904 = true;
  20758. /* falls through */
  20759. case "1900-01-01": baddate = 0;
  20760. }
  20761. break;
  20762. case 'graphic-properties': break; // 17.21 <style:graphic-properties>
  20763. case 'calculation-settings': break; // 9.4.1 <table:calculation-settings>
  20764. case 'named-expressions': break; // 9.4.11 <table:named-expressions>
  20765. case 'label-range': break; // 9.4.9 <table:label-range>
  20766. case 'label-ranges': break; // 9.4.10 <table:label-ranges>
  20767. case 'named-expression': break; // 9.4.13 <table:named-expression>
  20768. case 'sort': break; // 9.4.19 <table:sort>
  20769. case 'sort-by': break; // 9.4.20 <table:sort-by>
  20770. case 'sort-groups': break; // 9.4.22 <table:sort-groups>
  20771. case 'tab': break; // 6.1.4 <text:tab>
  20772. case 'line-break': break; // 6.1.5 <text:line-break>
  20773. case 'span': break; // 6.1.7 <text:span>
  20774. case 'p': case '文本串': // 5.1.3 <text:p>
  20775. if(['master-styles'].indexOf(state[state.length-1][0]) > -1) break;
  20776. if(Rn[1]==='/' && (!ctag || !ctag['string-value'])) {
  20777. var ptp = parse_text_p(str.slice(textpidx,Rn.index), textptag);
  20778. textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
  20779. } else { textptag = parsexmltag(Rn[0], false); textpidx = Rn.index + Rn[0].length; }
  20780. break; // <text:p>
  20781. case 's': break; // <text:s>
  20782. case 'database-range': // 9.4.15 <table:database-range>
  20783. if(Rn[1]==='/') break;
  20784. try {
  20785. _Ref = ods_to_csf_3D(parsexmltag(Rn[0])['target-range-address']);
  20786. Sheets[_Ref[0]]['!autofilter'] = { ref:_Ref[1] };
  20787. } catch(e) {/* empty */}
  20788. break;
  20789. case 'date': break; // <*:date>
  20790. case 'object': break; // 10.4.6.2 <draw:object>
  20791. case 'title': case '标题': break; // <*:title> OR <uof:标题>
  20792. case 'desc': break; // <*:desc>
  20793. case 'binary-data': break; // 10.4.5 TODO: b64 blob
  20794. /* 9.2 Advanced Tables */
  20795. case 'table-source': break; // 9.2.6
  20796. case 'scenario': break; // 9.2.6
  20797. case 'iteration': break; // 9.4.3 <table:iteration>
  20798. case 'content-validations': break; // 9.4.4 <table:
  20799. case 'content-validation': break; // 9.4.5 <table:
  20800. case 'help-message': break; // 9.4.6 <table:
  20801. case 'error-message': break; // 9.4.7 <table:
  20802. case 'database-ranges': break; // 9.4.14 <table:database-ranges>
  20803. case 'filter': break; // 9.5.2 <table:filter>
  20804. case 'filter-and': break; // 9.5.3 <table:filter-and>
  20805. case 'filter-or': break; // 9.5.4 <table:filter-or>
  20806. case 'filter-condition': break; // 9.5.5 <table:filter-condition>
  20807. case 'list-level-style-bullet': break; // 16.31 <text:
  20808. case 'list-level-style-number': break; // 16.32 <text:
  20809. case 'list-level-properties': break; // 17.19 <style:
  20810. /* 7.3 Document Fields */
  20811. case 'sender-firstname': // 7.3.6.2
  20812. case 'sender-lastname': // 7.3.6.3
  20813. case 'sender-initials': // 7.3.6.4
  20814. case 'sender-title': // 7.3.6.5
  20815. case 'sender-position': // 7.3.6.6
  20816. case 'sender-email': // 7.3.6.7
  20817. case 'sender-phone-private': // 7.3.6.8
  20818. case 'sender-fax': // 7.3.6.9
  20819. case 'sender-company': // 7.3.6.10
  20820. case 'sender-phone-work': // 7.3.6.11
  20821. case 'sender-street': // 7.3.6.12
  20822. case 'sender-city': // 7.3.6.13
  20823. case 'sender-postal-code': // 7.3.6.14
  20824. case 'sender-country': // 7.3.6.15
  20825. case 'sender-state-or-province': // 7.3.6.16
  20826. case 'author-name': // 7.3.7.1
  20827. case 'author-initials': // 7.3.7.2
  20828. case 'chapter': // 7.3.8
  20829. case 'file-name': // 7.3.9
  20830. case 'template-name': // 7.3.9
  20831. case 'sheet-name': // 7.3.9
  20832. break;
  20833. case 'event-listener':
  20834. break;
  20835. /* TODO: FODS Properties */
  20836. case 'initial-creator':
  20837. case 'creation-date':
  20838. case 'print-date':
  20839. case 'generator':
  20840. case 'document-statistic':
  20841. case 'user-defined':
  20842. case 'editing-duration':
  20843. case 'editing-cycles':
  20844. break;
  20845. /* TODO: FODS Config */
  20846. case 'config-item':
  20847. break;
  20848. /* TODO: style tokens */
  20849. case 'page-number': break; // TODO <text:page-number>
  20850. case 'page-count': break; // TODO <text:page-count>
  20851. case 'time': break; // TODO <text:time>
  20852. /* 9.3 Advanced Table Cells */
  20853. case 'cell-range-source': break; // 9.3.1 <table:
  20854. case 'detective': break; // 9.3.2 <table:
  20855. case 'operation': break; // 9.3.3 <table:
  20856. case 'highlighted-range': break; // 9.3.4 <table:
  20857. /* 9.6 Data Pilot Tables <table: */
  20858. case 'data-pilot-table': // 9.6.3
  20859. case 'source-cell-range': // 9.6.5
  20860. case 'source-service': // 9.6.6
  20861. case 'data-pilot-field': // 9.6.7
  20862. case 'data-pilot-level': // 9.6.8
  20863. case 'data-pilot-subtotals': // 9.6.9
  20864. case 'data-pilot-subtotal': // 9.6.10
  20865. case 'data-pilot-members': // 9.6.11
  20866. case 'data-pilot-member': // 9.6.12
  20867. case 'data-pilot-display-info': // 9.6.13
  20868. case 'data-pilot-sort-info': // 9.6.14
  20869. case 'data-pilot-layout-info': // 9.6.15
  20870. case 'data-pilot-field-reference': // 9.6.16
  20871. case 'data-pilot-groups': // 9.6.17
  20872. case 'data-pilot-group': // 9.6.18
  20873. case 'data-pilot-group-member': // 9.6.19
  20874. break;
  20875. /* 10.3 Drawing Shapes */
  20876. case 'rect': // 10.3.2
  20877. break;
  20878. /* 14.6 DDE Connections */
  20879. case 'dde-connection-decls': // 14.6.2 <text:
  20880. case 'dde-connection-decl': // 14.6.3 <text:
  20881. case 'dde-link': // 14.6.4 <table:
  20882. case 'dde-source': // 14.6.5 <office:
  20883. break;
  20884. case 'properties': break; // 13.7 <form:properties>
  20885. case 'property': break; // 13.8 <form:property>
  20886. case 'a': // 6.1.8 hyperlink
  20887. if(Rn[1]!== '/') {
  20888. atag = parsexmltag(Rn[0], false);
  20889. if(!atag.href) break;
  20890. atag.Target = unescapexml(atag.href); delete atag.href;
  20891. if(atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
  20892. _Ref = ods_to_csf_3D(atag.Target.slice(1));
  20893. atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
  20894. } else if(atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3);
  20895. }
  20896. break;
  20897. /* non-standard */
  20898. case 'table-protection': break;
  20899. case 'data-pilot-grand-total': break; // <table:
  20900. case 'office-document-common-attrs': break; // bare
  20901. default: switch(Rn[2]) {
  20902. case 'dc:': // TODO: properties
  20903. case 'calcext:': // ignore undocumented extensions
  20904. case 'loext:': // ignore undocumented extensions
  20905. case 'ooo:': // ignore undocumented extensions
  20906. case 'chartooo:': // ignore undocumented extensions
  20907. case 'draw:': // TODO: drawing
  20908. case 'style:': // TODO: styles
  20909. case 'chart:': // TODO: charts
  20910. case 'form:': // TODO: forms
  20911. case 'uof:': // TODO: uof
  20912. case '表:': // TODO: uof
  20913. case '字:': // TODO: uof
  20914. break;
  20915. default: if(opts.WTF) throw new Error(Rn);
  20916. }
  20917. }
  20918. var out = ({
  20919. Sheets: Sheets,
  20920. SheetNames: SheetNames,
  20921. Workbook: WB
  20922. });
  20923. if(opts.bookSheets) delete out.Sheets;
  20924. return out;
  20925. }
  20926. function parse_ods(zip, opts) {
  20927. opts = opts || ({});
  20928. if(safegetzipfile(zip, 'META-INF/manifest.xml')) parse_manifest(getzipdata(zip, 'META-INF/manifest.xml'), opts);
  20929. var styles = getzipstr(zip, 'styles.xml');
  20930. var Styles = styles && parse_ods_styles(utf8read(styles), opts);
  20931. var content = getzipstr(zip, 'content.xml');
  20932. if(!content) throw new Error("Missing content.xml in ODS / UOF file");
  20933. var wb = parse_content_xml(utf8read(content), opts, Styles);
  20934. if(safegetzipfile(zip, 'meta.xml')) wb.Props = parse_core_props(getzipdata(zip, 'meta.xml'));
  20935. wb.bookType = "ods";
  20936. return wb;
  20937. }
  20938. function parse_fods(data, opts) {
  20939. var wb = parse_content_xml(data, opts);
  20940. wb.bookType = "fods";
  20941. return wb;
  20942. }
  20943. /* OpenDocument */
  20944. var write_styles_ods = /* @__PURE__ */(function() {
  20945. var master_styles = [
  20946. '<office:master-styles>',
  20947. '<style:master-page style:name="mp1" style:page-layout-name="mp1">',
  20948. '<style:header/>',
  20949. '<style:header-left style:display="false"/>',
  20950. '<style:footer/>',
  20951. '<style:footer-left style:display="false"/>',
  20952. '</style:master-page>',
  20953. '</office:master-styles>'
  20954. ].join("");
  20955. var payload = '<office:document-styles ' + wxt_helper({
  20956. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  20957. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  20958. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  20959. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  20960. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  20961. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  20962. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  20963. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  20964. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  20965. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  20966. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  20967. 'office:version': "1.2"
  20968. }) + '>' + master_styles + '</office:document-styles>';
  20969. return function wso() {
  20970. return XML_HEADER + payload;
  20971. };
  20972. })();
  20973. // TODO: find out if anyone actually read the spec. LO has some wild errors
  20974. function write_number_format_ods(nf, nfidx) {
  20975. var type = "number", payload = "", nopts = { "style:name": nfidx }, c = "", i = 0;
  20976. nf = nf.replace(/"[$]"/g, "$");
  20977. /* TODO: replace with an actual parser based on a real grammar */
  20978. j: {
  20979. // TODO: support style maps
  20980. if(nf.indexOf(";") > -1) {
  20981. console.error("Unsupported ODS Style Map exported. Using first branch of " + nf);
  20982. nf = nf.slice(0, nf.indexOf(";"));
  20983. }
  20984. if(nf == "@") { type = "text"; payload = "<number:text-content/>"; break j; }
  20985. /* currency flag */
  20986. if(nf.indexOf(/\$/) > -1) { type = "currency"; }
  20987. /* opening string literal */
  20988. if(nf[i] == '"') {
  20989. c = "";
  20990. while(nf[++i] != '"' || nf[++i] == '"') c += nf[i]; --i;
  20991. if(nf[i+1] == "*") {
  20992. i++;
  20993. payload += '<number:fill-character>' + escapexml(c.replace(/""/g, '"')) + '</number:fill-character>';
  20994. } else {
  20995. payload += '<number:text>' + escapexml(c.replace(/""/g, '"')) + '</number:text>';
  20996. }
  20997. nf = nf.slice(i+1); i = 0;
  20998. }
  20999. /* fractions */
  21000. var t = nf.match(/# (\?+)\/(\?+)/);
  21001. if(t) { payload += writextag("number:fraction", null, {"number:min-integer-digits":0, "number:min-numerator-digits": t[1].length, "number:max-denominator-value": Math.max(+(t[1].replace(/./g, "9")), +(t[2].replace(/./g, "9"))) }); break j; }
  21002. if((t=nf.match(/# (\?+)\/(\d+)/))) { payload += writextag("number:fraction", null, {"number:min-integer-digits":0, "number:min-numerator-digits": t[1].length, "number:denominator-value": +t[2]}); break j; }
  21003. /* percentages */
  21004. if((t=nf.match(/(\d+)(|\.\d+)%/))) { type = "percentage"; payload += writextag("number:number", null, {"number:decimal-places": t[2] && t.length - 1 || 0, "number:min-decimal-places": t[2] && t.length - 1 || 0, "number:min-integer-digits": t[1].length }) + "<number:text>%</number:text>"; break j; }
  21005. /* datetime */
  21006. var has_time = false;
  21007. if(["y","m","d"].indexOf(nf[0]) > -1) {
  21008. type = "date";
  21009. k: for(; i < nf.length; ++i) switch((c = nf[i].toLowerCase())) {
  21010. case "h": case "s": has_time = true; --i; break k;
  21011. case "m":
  21012. l: for(var h = i+1; h < nf.length; ++h) switch(nf[h]) {
  21013. case "y": case "d": break l;
  21014. case "h": case "s": has_time = true; --i; break k;
  21015. }
  21016. /* falls through */
  21017. case "y": case "d":
  21018. while((nf[++i]||"").toLowerCase() == c[0]) c += c[0]; --i;
  21019. switch(c) {
  21020. case "y": case "yy": payload += "<number:year/>"; break;
  21021. case "yyy": case "yyyy": payload += '<number:year number:style="long"/>'; break;
  21022. case "mmmmm": console.error("ODS has no equivalent of format |mmmmm|");
  21023. /* falls through */
  21024. case "m": case "mm": case "mmm": case "mmmm":
  21025. payload += '<number:month number:style="' + (c.length % 2 ? "short" : "long") + '" number:textual="' + (c.length >= 3 ? "true" : "false") + '"/>';
  21026. break;
  21027. case "d": case "dd": payload += '<number:day number:style="' + (c.length % 2 ? "short" : "long") + '"/>'; break;
  21028. case "ddd": case "dddd": payload += '<number:day-of-week number:style="' + (c.length % 2 ? "short" : "long") + '"/>'; break;
  21029. }
  21030. break;
  21031. case '"':
  21032. while(nf[++i] != '"' || nf[++i] == '"') c += nf[i]; --i;
  21033. payload += '<number:text>' + escapexml(c.slice(1).replace(/""/g, '"')) + '</number:text>';
  21034. break;
  21035. case '/': payload += '<number:text>' + escapexml(c) + '</number:text>'; break;
  21036. default: console.error("unrecognized character " + c + " in ODF format " + nf);
  21037. }
  21038. if(!has_time) break j;
  21039. nf = nf.slice(i+1); i = 0;
  21040. }
  21041. if(nf.match(/^\[?[hms]/)) {
  21042. if(type == "number") type = "time";
  21043. if(nf.match(/\[/)) {
  21044. nf = nf.replace(/[\[\]]/g, "");
  21045. nopts['number:truncate-on-overflow'] = "false";
  21046. }
  21047. for(; i < nf.length; ++i) switch((c = nf[i].toLowerCase())) {
  21048. case "h": case "m": case "s":
  21049. while((nf[++i]||"").toLowerCase() == c[0]) c += c[0]; --i;
  21050. switch(c) {
  21051. case "h": case "hh": payload += '<number:hours number:style="' + (c.length % 2 ? "short" : "long") + '"/>'; break;
  21052. case "m": case "mm": payload += '<number:minutes number:style="' + (c.length % 2 ? "short" : "long") + '"/>'; break;
  21053. case "s": case "ss":
  21054. if(nf[i+1] == ".") do { c += nf[i+1]; ++i; } while(nf[i+1] == "0");
  21055. payload += '<number:seconds number:style="' + (c.match("ss") ? "long" : "short") + '"' + (c.match(/\./) ? ' number:decimal-places="' + (c.match(/0+/)||[""])[0].length + '"' : "")+ '/>'; break;
  21056. }
  21057. break;
  21058. case '"':
  21059. while(nf[++i] != '"' || nf[++i] == '"') c += nf[i]; --i;
  21060. payload += '<number:text>' + escapexml(c.slice(1).replace(/""/g, '"')) + '</number:text>';
  21061. break;
  21062. case '/': payload += '<number:text>' + escapexml(c) + '</number:text>'; break;
  21063. case "a":
  21064. if(nf.slice(i, i+3).toLowerCase() == "a/p") { payload += '<number:am-pm/>'; i += 2; break; } // Note: ODF does not support A/P
  21065. if(nf.slice(i, i+5).toLowerCase() == "am/pm") { payload += '<number:am-pm/>'; i += 4; break; }
  21066. /* falls through */
  21067. default: console.error("unrecognized character " + c + " in ODF format " + nf);
  21068. }
  21069. break j;
  21070. }
  21071. /* currency flag */
  21072. if(nf.indexOf(/\$/) > -1) { type = "currency"; }
  21073. /* should be in a char loop */
  21074. if(nf[0] == "$") { payload += '<number:currency-symbol number:language="en" number:country="US">$</number:currency-symbol>'; nf = nf.slice(1); i = 0; }
  21075. i = 0; if(nf[i] == '"') {
  21076. while(nf[++i] != '"' || nf[++i] == '"') c += nf[i]; --i;
  21077. if(nf[i+1] == "*") {
  21078. i++;
  21079. payload += '<number:fill-character>' + escapexml(c.replace(/""/g, '"')) + '</number:fill-character>';
  21080. } else {
  21081. payload += '<number:text>' + escapexml(c.replace(/""/g, '"')) + '</number:text>';
  21082. }
  21083. nf = nf.slice(i+1); i = 0;
  21084. }
  21085. /* number TODO: interstitial text e.g. 000)000-0000 */
  21086. var np = nf.match(/([#0][0#,]*)(\.[0#]*|)(E[+]?0*|)/i);
  21087. if(!np || !np[0]) console.error("Could not find numeric part of " + nf);
  21088. else {
  21089. var base = np[1].replace(/,/g, "");
  21090. payload += '<number:' + (np[3] ? "scientific-" : "")+ 'number' +
  21091. ' number:min-integer-digits="' + (base.indexOf("0") == -1 ? "0" : base.length - base.indexOf("0")) + '"' +
  21092. (np[0].indexOf(",") > -1 ? ' number:grouping="true"' : "") +
  21093. (np[2] && ' number:decimal-places="' + (np[2].length - 1) + '"' || ' number:decimal-places="0"') +
  21094. (np[3] && np[3].indexOf("+") > -1 ? ' number:forced-exponent-sign="true"' : "" ) +
  21095. (np[3] ? ' number:min-exponent-digits="' + np[3].match(/0+/)[0].length + '"' : "" ) +
  21096. '>' +
  21097. /* TODO: interstitial text placeholders */
  21098. '</number:' + (np[3] ? "scientific-" : "") + 'number>';
  21099. i = np.index + np[0].length;
  21100. }
  21101. /* residual text */
  21102. if(nf[i] == '"') {
  21103. c = "";
  21104. while(nf[++i] != '"' || nf[++i] == '"') c += nf[i]; --i;
  21105. payload += '<number:text>' + escapexml(c.replace(/""/g, '"')) + '</number:text>';
  21106. }
  21107. }
  21108. if(!payload) { console.error("Could not generate ODS number format for |" + nf + "|"); return ""; }
  21109. return writextag("number:" + type + "-style", payload, nopts);
  21110. }
  21111. function write_names_ods(Names, SheetNames, idx) {
  21112. var scoped = Names.filter(function(name) { return name.Sheet == (idx == -1 ? null : idx); });
  21113. if(!scoped.length) return "";
  21114. return " <table:named-expressions>\n" + scoped.map(function(name) {
  21115. var odsref = csf_to_ods_3D(name.Ref);
  21116. return " " + writextag("table:named-range", null, {
  21117. "table:name": name.Name,
  21118. "table:cell-range-address": odsref,
  21119. "table:base-cell-address": odsref.replace(/[\.]?[^\.]*$/, ".$A$1")
  21120. });
  21121. }).join("\n") + "\n </table:named-expressions>\n";
  21122. }
  21123. var write_content_ods = /* @__PURE__ */(function() {
  21124. /* 6.1.2 White Space Characters */
  21125. var write_text_p = function(text) {
  21126. return escapexml(text)
  21127. .replace(/ +/g, function($$){return '<text:s text:c="'+$$.length+'"/>';})
  21128. .replace(/\t/g, "<text:tab/>")
  21129. .replace(/\n/g, "</text:p><text:p>")
  21130. .replace(/^ /, "<text:s/>").replace(/ $/, "<text:s/>");
  21131. };
  21132. var null_cell_xml = ' <table:table-cell />\n';
  21133. var covered_cell_xml = ' <table:covered-table-cell/>\n';
  21134. var write_ws = function(ws, wb, i, opts, nfs) {
  21135. /* Section 9 Tables */
  21136. var o = [];
  21137. o.push(' <table:table table:name="' + escapexml(wb.SheetNames[i]) + '" table:style-name="ta1">\n');
  21138. var R=0,C=0, range = decode_range(ws['!ref']||"A1");
  21139. var marr = ws['!merges'] || [], mi = 0;
  21140. var dense = Array.isArray(ws);
  21141. if(ws["!cols"]) {
  21142. for(C = 0; C <= range.e.c; ++C) o.push(' <table:table-column' + (ws["!cols"][C] ? ' table:style-name="co' + ws["!cols"][C].ods + '"' : '') + '></table:table-column>\n');
  21143. }
  21144. var H = "", ROWS = ws["!rows"]||[];
  21145. for(R = 0; R < range.s.r; ++R) {
  21146. H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
  21147. o.push(' <table:table-row' + H + '></table:table-row>\n');
  21148. }
  21149. for(; R <= range.e.r; ++R) {
  21150. H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
  21151. o.push(' <table:table-row' + H + '>\n');
  21152. for(C=0; C < range.s.c; ++C) o.push(null_cell_xml);
  21153. for(; C <= range.e.c; ++C) {
  21154. var skip = false, ct = {}, textp = "";
  21155. for(mi = 0; mi != marr.length; ++mi) {
  21156. if(marr[mi].s.c > C) continue;
  21157. if(marr[mi].s.r > R) continue;
  21158. if(marr[mi].e.c < C) continue;
  21159. if(marr[mi].e.r < R) continue;
  21160. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  21161. ct['table:number-columns-spanned'] = (marr[mi].e.c - marr[mi].s.c + 1);
  21162. ct['table:number-rows-spanned'] = (marr[mi].e.r - marr[mi].s.r + 1);
  21163. break;
  21164. }
  21165. if(skip) { o.push(covered_cell_xml); continue; }
  21166. var ref = encode_cell({r:R, c:C}), cell = dense ? (ws[R]||[])[C]: ws[ref];
  21167. if(cell && cell.f) {
  21168. ct['table:formula'] = escapexml(csf_to_ods_formula(cell.f));
  21169. if(cell.F) {
  21170. if(cell.F.slice(0, ref.length) == ref) {
  21171. var _Fref = decode_range(cell.F);
  21172. ct['table:number-matrix-columns-spanned'] = (_Fref.e.c - _Fref.s.c + 1);
  21173. ct['table:number-matrix-rows-spanned'] = (_Fref.e.r - _Fref.s.r + 1);
  21174. }
  21175. }
  21176. }
  21177. if(!cell) { o.push(null_cell_xml); continue; }
  21178. switch(cell.t) {
  21179. case 'b':
  21180. textp = (cell.v ? 'TRUE' : 'FALSE');
  21181. ct['office:value-type'] = "boolean";
  21182. ct['office:boolean-value'] = (cell.v ? 'true' : 'false');
  21183. break;
  21184. case 'n':
  21185. textp = (cell.w||String(cell.v||0));
  21186. ct['office:value-type'] = "float";
  21187. ct['office:value'] = (cell.v||0);
  21188. break;
  21189. case 's': case 'str':
  21190. textp = cell.v == null ? "" : cell.v;
  21191. ct['office:value-type'] = "string";
  21192. break;
  21193. case 'd':
  21194. textp = (cell.w||(parseDate(cell.v).toISOString()));
  21195. ct['office:value-type'] = "date";
  21196. ct['office:date-value'] = (parseDate(cell.v).toISOString());
  21197. ct['table:style-name'] = "ce1";
  21198. break;
  21199. //case 'e':
  21200. default: o.push(null_cell_xml); continue;
  21201. }
  21202. var text_p = write_text_p(textp);
  21203. if(cell.l && cell.l.Target) {
  21204. var _tgt = cell.l.Target;
  21205. _tgt = _tgt.charAt(0) == "#" ? "#" + csf_to_ods_3D(_tgt.slice(1)) : _tgt;
  21206. // TODO: choose correct parent path format based on link delimiters
  21207. if(_tgt.charAt(0) != "#" && !_tgt.match(/^\w+:/)) _tgt = '../' + _tgt;
  21208. text_p = writextag('text:a', text_p, {'xlink:href': _tgt.replace(/&/g, "&amp;")});
  21209. }
  21210. if(nfs[cell.z]) ct["table:style-name"] = "ce" + nfs[cell.z].slice(1);
  21211. o.push(' ' + writextag('table:table-cell', writextag('text:p', text_p, {}), ct) + '\n');
  21212. }
  21213. o.push(' </table:table-row>\n');
  21214. }
  21215. if((wb.Workbook||{}).Names) o.push(write_names_ods(wb.Workbook.Names, wb.SheetNames, i));
  21216. o.push(' </table:table>\n');
  21217. return o.join("");
  21218. };
  21219. var write_automatic_styles_ods = function(o, wb) {
  21220. o.push(' <office:automatic-styles>\n');
  21221. /* column styles */
  21222. var cidx = 0;
  21223. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  21224. if(!ws) return;
  21225. if(ws["!cols"]) {
  21226. for(var C = 0; C < ws["!cols"].length; ++C) if(ws["!cols"][C]) {
  21227. var colobj = ws["!cols"][C];
  21228. if(colobj.width == null && colobj.wpx == null && colobj.wch == null) continue;
  21229. process_col(colobj);
  21230. colobj.ods = cidx;
  21231. var w = ws["!cols"][C].wpx + "px";
  21232. o.push(' <style:style style:name="co' + cidx + '" style:family="table-column">\n');
  21233. o.push(' <style:table-column-properties fo:break-before="auto" style:column-width="' + w + '"/>\n');
  21234. o.push(' </style:style>\n');
  21235. ++cidx;
  21236. }
  21237. }
  21238. });
  21239. /* row styles */
  21240. var ridx = 0;
  21241. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  21242. if(!ws) return;
  21243. if(ws["!rows"]) {
  21244. for(var R = 0; R < ws["!rows"].length; ++R) if(ws["!rows"][R]) {
  21245. ws["!rows"][R].ods = ridx;
  21246. var h = ws["!rows"][R].hpx + "px";
  21247. o.push(' <style:style style:name="ro' + ridx + '" style:family="table-row">\n');
  21248. o.push(' <style:table-row-properties fo:break-before="auto" style:row-height="' + h + '"/>\n');
  21249. o.push(' </style:style>\n');
  21250. ++ridx;
  21251. }
  21252. }
  21253. });
  21254. /* table */
  21255. o.push(' <style:style style:name="ta1" style:family="table" style:master-page-name="mp1">\n');
  21256. o.push(' <style:table-properties table:display="true" style:writing-mode="lr-tb"/>\n');
  21257. o.push(' </style:style>\n');
  21258. o.push(' <number:date-style style:name="N37" number:automatic-order="true">\n');
  21259. o.push(' <number:month number:style="long"/>\n');
  21260. o.push(' <number:text>/</number:text>\n');
  21261. o.push(' <number:day number:style="long"/>\n');
  21262. o.push(' <number:text>/</number:text>\n');
  21263. o.push(' <number:year/>\n');
  21264. o.push(' </number:date-style>\n');
  21265. /* number formats, table cells, text */
  21266. var nfs = {};
  21267. var nfi = 69;
  21268. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  21269. if(!ws) return;
  21270. var range = decode_range(ws["!ref"]);
  21271. for(var R = 0; R <= range.e.r; ++R) for(var C = 0; C <= range.e.c; ++C) {
  21272. var c = Array.isArray(ws) ? (ws[R]||[])[C] : ws[encode_cell({r:R,c:C})];
  21273. if(!c || !c.z || c.z.toLowerCase() == "general") continue;
  21274. if(!nfs[c.z]) {
  21275. var out = write_number_format_ods(c.z, "N" + nfi);
  21276. if(out) { nfs[c.z] = "N" + nfi; ++nfi; o.push(out + "\n"); }
  21277. }
  21278. }
  21279. });
  21280. o.push(' <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N37"/>\n');
  21281. keys(nfs).forEach(function(nf) {
  21282. o.push('<style:style style:name="ce' + nfs[nf].slice(1) + '" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="' + nfs[nf] + '"/>\n');
  21283. });
  21284. /* page-layout */
  21285. o.push(' </office:automatic-styles>\n');
  21286. return nfs;
  21287. };
  21288. return function wcx(wb, opts) {
  21289. var o = [XML_HEADER];
  21290. /* 3.1.3.2 */
  21291. var attr = wxt_helper({
  21292. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  21293. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  21294. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  21295. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  21296. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  21297. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  21298. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  21299. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  21300. 'xmlns:meta': "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
  21301. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  21302. 'xmlns:presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
  21303. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  21304. 'xmlns:chart': "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
  21305. 'xmlns:dr3d': "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
  21306. 'xmlns:math': "http://www.w3.org/1998/Math/MathML",
  21307. 'xmlns:form': "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
  21308. 'xmlns:script': "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
  21309. 'xmlns:ooo': "http://openoffice.org/2004/office",
  21310. 'xmlns:ooow': "http://openoffice.org/2004/writer",
  21311. 'xmlns:oooc': "http://openoffice.org/2004/calc",
  21312. 'xmlns:dom': "http://www.w3.org/2001/xml-events",
  21313. 'xmlns:xforms': "http://www.w3.org/2002/xforms",
  21314. 'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
  21315. 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
  21316. 'xmlns:sheet': "urn:oasis:names:tc:opendocument:sh33tjs:1.0",
  21317. 'xmlns:rpt': "http://openoffice.org/2005/report",
  21318. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  21319. 'xmlns:xhtml': "http://www.w3.org/1999/xhtml",
  21320. 'xmlns:grddl': "http://www.w3.org/2003/g/data-view#",
  21321. 'xmlns:tableooo': "http://openoffice.org/2009/table",
  21322. 'xmlns:drawooo': "http://openoffice.org/2010/draw",
  21323. 'xmlns:calcext': "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
  21324. 'xmlns:loext': "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
  21325. 'xmlns:field': "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
  21326. 'xmlns:formx': "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
  21327. 'xmlns:css3t': "http://www.w3.org/TR/css3-text/",
  21328. 'office:version': "1.2"
  21329. });
  21330. var fods = wxt_helper({
  21331. 'xmlns:config': "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
  21332. 'office:mimetype': "application/vnd.oasis.opendocument.spreadsheet"
  21333. });
  21334. if(opts.bookType == "fods") {
  21335. o.push('<office:document' + attr + fods + '>\n');
  21336. o.push(write_meta_ods().replace(/<office:document-meta.*?>/, "").replace(/<\/office:document-meta>/, "") + "\n");
  21337. // TODO: settings (equiv of settings.xml for ODS)
  21338. } else o.push('<office:document-content' + attr + '>\n');
  21339. // o.push(' <office:scripts/>\n');
  21340. var nfs = write_automatic_styles_ods(o, wb);
  21341. o.push(' <office:body>\n');
  21342. o.push(' <office:spreadsheet>\n');
  21343. if(((wb.Workbook||{}).WBProps||{}).date1904) o.push(' <table:calculation-settings table:case-sensitive="false" table:search-criteria-must-apply-to-whole-cell="true" table:use-wildcards="true" table:use-regular-expressions="false" table:automatic-find-labels="false">\n <table:null-date table:date-value="1904-01-01"/>\n </table:calculation-settings>\n');
  21344. for(var i = 0; i != wb.SheetNames.length; ++i) o.push(write_ws(wb.Sheets[wb.SheetNames[i]], wb, i, opts, nfs));
  21345. if((wb.Workbook||{}).Names) o.push(write_names_ods(wb.Workbook.Names, wb.SheetNames, -1));
  21346. o.push(' </office:spreadsheet>\n');
  21347. o.push(' </office:body>\n');
  21348. if(opts.bookType == "fods") o.push('</office:document>');
  21349. else o.push('</office:document-content>');
  21350. return o.join("");
  21351. };
  21352. })();
  21353. function write_ods(wb, opts) {
  21354. if(opts.bookType == "fods") return write_content_ods(wb, opts);
  21355. var zip = zip_new();
  21356. var f = "";
  21357. var manifest = [];
  21358. var rdf = [];
  21359. /* Part 3 Section 3.3 MIME Media Type */
  21360. f = "mimetype";
  21361. zip_add_file(zip, f, "application/vnd.oasis.opendocument.spreadsheet");
  21362. /* Part 1 Section 2.2 Documents */
  21363. f = "content.xml";
  21364. zip_add_file(zip, f, write_content_ods(wb, opts));
  21365. manifest.push([f, "text/xml"]);
  21366. rdf.push([f, "ContentFile"]);
  21367. /* TODO: these are hard-coded styles to satiate excel */
  21368. f = "styles.xml";
  21369. zip_add_file(zip, f, write_styles_ods(wb, opts));
  21370. manifest.push([f, "text/xml"]);
  21371. rdf.push([f, "StylesFile"]);
  21372. /* TODO: this is hard-coded to satiate excel */
  21373. f = "meta.xml";
  21374. zip_add_file(zip, f, XML_HEADER + write_meta_ods());
  21375. manifest.push([f, "text/xml"]);
  21376. rdf.push([f, "MetadataFile"]);
  21377. /* Part 3 Section 6 Metadata Manifest File */
  21378. f = "manifest.rdf";
  21379. zip_add_file(zip, f, write_rdf(rdf/*, opts*/));
  21380. manifest.push([f, "application/rdf+xml"]);
  21381. /* Part 3 Section 4 Manifest File */
  21382. f = "META-INF/manifest.xml";
  21383. zip_add_file(zip, f, write_manifest(manifest/*, opts*/));
  21384. return zip;
  21385. }
  21386. /*! sheetjs (C) 2013-present SheetJS -- http://sheetjs.com */
  21387. var subarray = function() {
  21388. try {
  21389. if (typeof Uint8Array == "undefined")
  21390. return "slice";
  21391. if (typeof Uint8Array.prototype.subarray == "undefined")
  21392. return "slice";
  21393. if (typeof Buffer !== "undefined") {
  21394. if (typeof Buffer.prototype.subarray == "undefined")
  21395. return "slice";
  21396. if ((typeof Buffer.from == "function" ? Buffer.from([72, 62]) : new Buffer([72, 62])) instanceof Uint8Array)
  21397. return "subarray";
  21398. return "slice";
  21399. }
  21400. return "subarray";
  21401. } catch (e) {
  21402. return "slice";
  21403. }
  21404. }();
  21405. function u8_to_dataview(array) {
  21406. return new DataView(array.buffer, array.byteOffset, array.byteLength);
  21407. }
  21408. function u8str(u8) {
  21409. return typeof TextDecoder != "undefined" ? new TextDecoder().decode(u8) : utf8read(a2s(u8));
  21410. }
  21411. function stru8(str) {
  21412. return typeof TextEncoder != "undefined" ? new TextEncoder().encode(str) : s2a(utf8write(str));
  21413. }
  21414. function u8contains(body, search) {
  21415. var L = body.indexOf(search[0]);
  21416. if (L == -1)
  21417. return false;
  21418. outer:
  21419. for (; L <= body.length - search.length; ++L) {
  21420. for (var j = 0; j < search.length; ++j)
  21421. if (body[L + j] != search[j])
  21422. continue outer;
  21423. return true;
  21424. }
  21425. return false;
  21426. }
  21427. function u8concat(u8a) {
  21428. var len = u8a.reduce(function(acc, x) {
  21429. return acc + x.length;
  21430. }, 0);
  21431. var out = new Uint8Array(len);
  21432. var off = 0;
  21433. u8a.forEach(function(u8) {
  21434. out.set(u8, off);
  21435. off += u8.length;
  21436. });
  21437. return out;
  21438. }
  21439. function popcnt(x) {
  21440. x -= x >> 1 & 1431655765;
  21441. x = (x & 858993459) + (x >> 2 & 858993459);
  21442. return (x + (x >> 4) & 252645135) * 16843009 >>> 24;
  21443. }
  21444. function readDecimal128LE(buf, offset) {
  21445. var exp = (buf[offset + 15] & 127) << 7 | buf[offset + 14] >> 1;
  21446. var mantissa = buf[offset + 14] & 1;
  21447. for (var j = offset + 13; j >= offset; --j)
  21448. mantissa = mantissa * 256 + buf[j];
  21449. return (buf[offset + 15] & 128 ? -mantissa : mantissa) * Math.pow(10, exp - 6176);
  21450. }
  21451. function writeDecimal128LE(buf, offset, value) {
  21452. var exp = Math.floor(value == 0 ? 0 : Math.LOG10E * Math.log(Math.abs(value))) + 6176 - 16;
  21453. var mantissa = value / Math.pow(10, exp - 6176);
  21454. buf[offset + 15] |= exp >> 7;
  21455. buf[offset + 14] |= (exp & 127) << 1;
  21456. for (var i = 0; mantissa >= 1; ++i, mantissa /= 256)
  21457. buf[offset + i] = mantissa & 255;
  21458. buf[offset + 15] |= value >= 0 ? 0 : 128;
  21459. }
  21460. function parse_varint49(buf, ptr) {
  21461. var l = ptr ? ptr[0] : 0;
  21462. var usz = buf[l] & 127;
  21463. varint:
  21464. if (buf[l++] >= 128) {
  21465. usz |= (buf[l] & 127) << 7;
  21466. if (buf[l++] < 128)
  21467. break varint;
  21468. usz |= (buf[l] & 127) << 14;
  21469. if (buf[l++] < 128)
  21470. break varint;
  21471. usz |= (buf[l] & 127) << 21;
  21472. if (buf[l++] < 128)
  21473. break varint;
  21474. usz += (buf[l] & 127) * Math.pow(2, 28);
  21475. ++l;
  21476. if (buf[l++] < 128)
  21477. break varint;
  21478. usz += (buf[l] & 127) * Math.pow(2, 35);
  21479. ++l;
  21480. if (buf[l++] < 128)
  21481. break varint;
  21482. usz += (buf[l] & 127) * Math.pow(2, 42);
  21483. ++l;
  21484. if (buf[l++] < 128)
  21485. break varint;
  21486. }
  21487. if (ptr)
  21488. ptr[0] = l;
  21489. return usz;
  21490. }
  21491. function write_varint49(v) {
  21492. var usz = new Uint8Array(7);
  21493. usz[0] = v & 127;
  21494. var L = 1;
  21495. sz:
  21496. if (v > 127) {
  21497. usz[L - 1] |= 128;
  21498. usz[L] = v >> 7 & 127;
  21499. ++L;
  21500. if (v <= 16383)
  21501. break sz;
  21502. usz[L - 1] |= 128;
  21503. usz[L] = v >> 14 & 127;
  21504. ++L;
  21505. if (v <= 2097151)
  21506. break sz;
  21507. usz[L - 1] |= 128;
  21508. usz[L] = v >> 21 & 127;
  21509. ++L;
  21510. if (v <= 268435455)
  21511. break sz;
  21512. usz[L - 1] |= 128;
  21513. usz[L] = v / 256 >>> 21 & 127;
  21514. ++L;
  21515. if (v <= 34359738367)
  21516. break sz;
  21517. usz[L - 1] |= 128;
  21518. usz[L] = v / 65536 >>> 21 & 127;
  21519. ++L;
  21520. if (v <= 4398046511103)
  21521. break sz;
  21522. usz[L - 1] |= 128;
  21523. usz[L] = v / 16777216 >>> 21 & 127;
  21524. ++L;
  21525. }
  21526. return usz[subarray](0, L);
  21527. }
  21528. function parse_packed_varints(buf) {
  21529. var ptr = [0];
  21530. var out = [];
  21531. while (ptr[0] < buf.length)
  21532. out.push(parse_varint49(buf, ptr));
  21533. return out;
  21534. }
  21535. function write_packed_varints(nums) {
  21536. return u8concat(nums.map(function(x) {
  21537. return write_varint49(x);
  21538. }));
  21539. }
  21540. function varint_to_i32(buf) {
  21541. var l = 0, i32 = buf[l] & 127;
  21542. varint:
  21543. if (buf[l++] >= 128) {
  21544. i32 |= (buf[l] & 127) << 7;
  21545. if (buf[l++] < 128)
  21546. break varint;
  21547. i32 |= (buf[l] & 127) << 14;
  21548. if (buf[l++] < 128)
  21549. break varint;
  21550. i32 |= (buf[l] & 127) << 21;
  21551. if (buf[l++] < 128)
  21552. break varint;
  21553. i32 |= (buf[l] & 127) << 28;
  21554. }
  21555. return i32;
  21556. }
  21557. function varint_to_u64(buf) {
  21558. var l = 0, lo = buf[l] & 127, hi = 0;
  21559. varint:
  21560. if (buf[l++] >= 128) {
  21561. lo |= (buf[l] & 127) << 7;
  21562. if (buf[l++] < 128)
  21563. break varint;
  21564. lo |= (buf[l] & 127) << 14;
  21565. if (buf[l++] < 128)
  21566. break varint;
  21567. lo |= (buf[l] & 127) << 21;
  21568. if (buf[l++] < 128)
  21569. break varint;
  21570. lo |= (buf[l] & 127) << 28;
  21571. hi = buf[l] >> 4 & 7;
  21572. if (buf[l++] < 128)
  21573. break varint;
  21574. hi |= (buf[l] & 127) << 3;
  21575. if (buf[l++] < 128)
  21576. break varint;
  21577. hi |= (buf[l] & 127) << 10;
  21578. if (buf[l++] < 128)
  21579. break varint;
  21580. hi |= (buf[l] & 127) << 17;
  21581. if (buf[l++] < 128)
  21582. break varint;
  21583. hi |= (buf[l] & 127) << 24;
  21584. if (buf[l++] < 128)
  21585. break varint;
  21586. hi |= (buf[l] & 127) << 31;
  21587. }
  21588. return [lo >>> 0, hi >>> 0];
  21589. }
  21590. function parse_shallow(buf) {
  21591. var out = [], ptr = [0];
  21592. while (ptr[0] < buf.length) {
  21593. var off = ptr[0];
  21594. var num = parse_varint49(buf, ptr);
  21595. var type = num & 7;
  21596. num = Math.floor(num / 8);
  21597. var len = 0;
  21598. var res;
  21599. if (num == 0)
  21600. break;
  21601. switch (type) {
  21602. case 0:
  21603. {
  21604. var l = ptr[0];
  21605. while (buf[ptr[0]++] >= 128)
  21606. ;
  21607. res = buf[subarray](l, ptr[0]);
  21608. }
  21609. break;
  21610. case 5:
  21611. len = 4;
  21612. res = buf[subarray](ptr[0], ptr[0] + len);
  21613. ptr[0] += len;
  21614. break;
  21615. case 1:
  21616. len = 8;
  21617. res = buf[subarray](ptr[0], ptr[0] + len);
  21618. ptr[0] += len;
  21619. break;
  21620. case 2:
  21621. len = parse_varint49(buf, ptr);
  21622. res = buf[subarray](ptr[0], ptr[0] + len);
  21623. ptr[0] += len;
  21624. break;
  21625. case 3:
  21626. case 4:
  21627. default:
  21628. throw new Error("PB Type ".concat(type, " for Field ").concat(num, " at offset ").concat(off));
  21629. }
  21630. var v = { data: res, type: type };
  21631. if (out[num] == null)
  21632. out[num] = [v];
  21633. else
  21634. out[num].push(v);
  21635. }
  21636. return out;
  21637. }
  21638. function write_shallow(proto) {
  21639. var out = [];
  21640. proto.forEach(function(field, idx) {
  21641. if (idx == 0)
  21642. return;
  21643. field.forEach(function(item) {
  21644. if (!item.data)
  21645. return;
  21646. out.push(write_varint49(idx * 8 + item.type));
  21647. if (item.type == 2)
  21648. out.push(write_varint49(item.data.length));
  21649. out.push(item.data);
  21650. });
  21651. });
  21652. return u8concat(out);
  21653. }
  21654. function mappa(data, cb) {
  21655. return (data == null ? void 0 : data.map(function(d) {
  21656. return cb(d.data);
  21657. })) || [];
  21658. }
  21659. function parse_iwa_file(buf) {
  21660. var _a;
  21661. var out = [], ptr = [0];
  21662. while (ptr[0] < buf.length) {
  21663. var len = parse_varint49(buf, ptr);
  21664. var ai = parse_shallow(buf[subarray](ptr[0], ptr[0] + len));
  21665. ptr[0] += len;
  21666. var res = {
  21667. id: varint_to_i32(ai[1][0].data),
  21668. messages: []
  21669. };
  21670. ai[2].forEach(function(b) {
  21671. var mi = parse_shallow(b.data);
  21672. var fl = varint_to_i32(mi[3][0].data);
  21673. res.messages.push({
  21674. meta: mi,
  21675. data: buf[subarray](ptr[0], ptr[0] + fl)
  21676. });
  21677. ptr[0] += fl;
  21678. });
  21679. if ((_a = ai[3]) == null ? void 0 : _a[0])
  21680. res.merge = varint_to_i32(ai[3][0].data) >>> 0 > 0;
  21681. out.push(res);
  21682. }
  21683. return out;
  21684. }
  21685. function write_iwa_file(ias) {
  21686. var bufs = [];
  21687. ias.forEach(function(ia) {
  21688. var ai = [
  21689. [],
  21690. [{ data: write_varint49(ia.id), type: 0 }],
  21691. []
  21692. ];
  21693. if (ia.merge != null)
  21694. ai[3] = [{ data: write_varint49(+!!ia.merge), type: 0 }];
  21695. var midata = [];
  21696. ia.messages.forEach(function(mi) {
  21697. midata.push(mi.data);
  21698. mi.meta[3] = [{ type: 0, data: write_varint49(mi.data.length) }];
  21699. ai[2].push({ data: write_shallow(mi.meta), type: 2 });
  21700. });
  21701. var aipayload = write_shallow(ai);
  21702. bufs.push(write_varint49(aipayload.length));
  21703. bufs.push(aipayload);
  21704. midata.forEach(function(mid) {
  21705. return bufs.push(mid);
  21706. });
  21707. });
  21708. return u8concat(bufs);
  21709. }
  21710. function parse_snappy_chunk(type, buf) {
  21711. if (type != 0)
  21712. throw new Error("Unexpected Snappy chunk type ".concat(type));
  21713. var ptr = [0];
  21714. var usz = parse_varint49(buf, ptr);
  21715. var chunks = [];
  21716. while (ptr[0] < buf.length) {
  21717. var tag = buf[ptr[0]] & 3;
  21718. if (tag == 0) {
  21719. var len = buf[ptr[0]++] >> 2;
  21720. if (len < 60)
  21721. ++len;
  21722. else {
  21723. var c = len - 59;
  21724. len = buf[ptr[0]];
  21725. if (c > 1)
  21726. len |= buf[ptr[0] + 1] << 8;
  21727. if (c > 2)
  21728. len |= buf[ptr[0] + 2] << 16;
  21729. if (c > 3)
  21730. len |= buf[ptr[0] + 3] << 24;
  21731. len >>>= 0;
  21732. len++;
  21733. ptr[0] += c;
  21734. }
  21735. chunks.push(buf[subarray](ptr[0], ptr[0] + len));
  21736. ptr[0] += len;
  21737. continue;
  21738. } else {
  21739. var offset = 0, length = 0;
  21740. if (tag == 1) {
  21741. length = (buf[ptr[0]] >> 2 & 7) + 4;
  21742. offset = (buf[ptr[0]++] & 224) << 3;
  21743. offset |= buf[ptr[0]++];
  21744. } else {
  21745. length = (buf[ptr[0]++] >> 2) + 1;
  21746. if (tag == 2) {
  21747. offset = buf[ptr[0]] | buf[ptr[0] + 1] << 8;
  21748. ptr[0] += 2;
  21749. } else {
  21750. offset = (buf[ptr[0]] | buf[ptr[0] + 1] << 8 | buf[ptr[0] + 2] << 16 | buf[ptr[0] + 3] << 24) >>> 0;
  21751. ptr[0] += 4;
  21752. }
  21753. }
  21754. if (offset == 0)
  21755. throw new Error("Invalid offset 0");
  21756. var j = chunks.length - 1, off = offset;
  21757. while (j >= 0 && off >= chunks[j].length) {
  21758. off -= chunks[j].length;
  21759. --j;
  21760. }
  21761. if (j < 0) {
  21762. if (off == 0)
  21763. off = chunks[j = 0].length;
  21764. else
  21765. throw new Error("Invalid offset beyond length");
  21766. }
  21767. if (length < off)
  21768. chunks.push(chunks[j][subarray](chunks[j].length - off, chunks[j].length - off + length));
  21769. else {
  21770. if (off > 0) {
  21771. chunks.push(chunks[j][subarray](chunks[j].length - off));
  21772. length -= off;
  21773. }
  21774. ++j;
  21775. while (length >= chunks[j].length) {
  21776. chunks.push(chunks[j]);
  21777. length -= chunks[j].length;
  21778. ++j;
  21779. }
  21780. if (length)
  21781. chunks.push(chunks[j][subarray](0, length));
  21782. }
  21783. if (chunks.length > 100)
  21784. chunks = [u8concat(chunks)];
  21785. }
  21786. }
  21787. if (chunks.reduce(function(acc, u8) {
  21788. return acc + u8.length;
  21789. }, 0) != usz)
  21790. throw new Error("Unexpected length: ".concat(chunks.reduce(function(acc, u8) {
  21791. return acc + u8.length;
  21792. }, 0), " != ").concat(usz));
  21793. return chunks;
  21794. }
  21795. function decompress_iwa_file(buf) {
  21796. if (Array.isArray(buf))
  21797. buf = new Uint8Array(buf);
  21798. var out = [];
  21799. var l = 0;
  21800. while (l < buf.length) {
  21801. var t = buf[l++];
  21802. var len = buf[l] | buf[l + 1] << 8 | buf[l + 2] << 16;
  21803. l += 3;
  21804. out.push.apply(out, parse_snappy_chunk(t, buf[subarray](l, l + len)));
  21805. l += len;
  21806. }
  21807. if (l !== buf.length)
  21808. throw new Error("data is not a valid framed stream!");
  21809. return u8concat(out);
  21810. }
  21811. function compress_iwa_file(buf) {
  21812. var out = [];
  21813. var l = 0;
  21814. while (l < buf.length) {
  21815. var c = Math.min(buf.length - l, 268435455);
  21816. var frame = new Uint8Array(4);
  21817. out.push(frame);
  21818. var usz = write_varint49(c);
  21819. var L = usz.length;
  21820. out.push(usz);
  21821. if (c <= 60) {
  21822. L++;
  21823. out.push(new Uint8Array([c - 1 << 2]));
  21824. } else if (c <= 256) {
  21825. L += 2;
  21826. out.push(new Uint8Array([240, c - 1 & 255]));
  21827. } else if (c <= 65536) {
  21828. L += 3;
  21829. out.push(new Uint8Array([244, c - 1 & 255, c - 1 >> 8 & 255]));
  21830. } else if (c <= 16777216) {
  21831. L += 4;
  21832. out.push(new Uint8Array([248, c - 1 & 255, c - 1 >> 8 & 255, c - 1 >> 16 & 255]));
  21833. } else if (c <= 4294967296) {
  21834. L += 5;
  21835. out.push(new Uint8Array([252, c - 1 & 255, c - 1 >> 8 & 255, c - 1 >> 16 & 255, c - 1 >>> 24 & 255]));
  21836. }
  21837. out.push(buf[subarray](l, l + c));
  21838. L += c;
  21839. frame[0] = 0;
  21840. frame[1] = L & 255;
  21841. frame[2] = L >> 8 & 255;
  21842. frame[3] = L >> 16 & 255;
  21843. l += c;
  21844. }
  21845. return u8concat(out);
  21846. }
  21847. var numbers_lut_new = function() {
  21848. return { sst: [], rsst: [], ofmt: [], nfmt: [] };
  21849. };
  21850. function numbers_format_cell(cell, t, flags, ofmt, nfmt) {
  21851. var _a, _b, _c, _d;
  21852. var ctype = t & 255, ver = t >> 8;
  21853. var fmt = ver >= 5 ? nfmt : ofmt;
  21854. dur:
  21855. if (flags & (ver > 4 ? 8 : 4) && cell.t == "n" && ctype == 7) {
  21856. var dstyle = ((_a = fmt[7]) == null ? void 0 : _a[0]) ? parse_varint49(fmt[7][0].data) : -1;
  21857. if (dstyle == -1)
  21858. break dur;
  21859. var dmin = ((_b = fmt[15]) == null ? void 0 : _b[0]) ? parse_varint49(fmt[15][0].data) : -1;
  21860. var dmax = ((_c = fmt[16]) == null ? void 0 : _c[0]) ? parse_varint49(fmt[16][0].data) : -1;
  21861. var auto = ((_d = fmt[40]) == null ? void 0 : _d[0]) ? parse_varint49(fmt[40][0].data) : -1;
  21862. var d = cell.v, dd = d;
  21863. autodur:
  21864. if (auto) {
  21865. if (d == 0) {
  21866. dmin = dmax = 2;
  21867. break autodur;
  21868. }
  21869. if (d >= 604800)
  21870. dmin = 1;
  21871. else if (d >= 86400)
  21872. dmin = 2;
  21873. else if (d >= 3600)
  21874. dmin = 4;
  21875. else if (d >= 60)
  21876. dmin = 8;
  21877. else if (d >= 1)
  21878. dmin = 16;
  21879. else
  21880. dmin = 32;
  21881. if (Math.floor(d) != d)
  21882. dmax = 32;
  21883. else if (d % 60)
  21884. dmax = 16;
  21885. else if (d % 3600)
  21886. dmax = 8;
  21887. else if (d % 86400)
  21888. dmax = 4;
  21889. else if (d % 604800)
  21890. dmax = 2;
  21891. if (dmax < dmin)
  21892. dmax = dmin;
  21893. }
  21894. if (dmin == -1 || dmax == -1)
  21895. break dur;
  21896. var dstr = [], zstr = [];
  21897. if (dmin == 1) {
  21898. dd = d / 604800;
  21899. if (dmax == 1) {
  21900. zstr.push('d"d"');
  21901. } else {
  21902. dd |= 0;
  21903. d -= 604800 * dd;
  21904. }
  21905. dstr.push(dd + (dstyle == 2 ? " week" + (dd == 1 ? "" : "s") : dstyle == 1 ? "w" : ""));
  21906. }
  21907. if (dmin <= 2 && dmax >= 2) {
  21908. dd = d / 86400;
  21909. if (dmax > 2) {
  21910. dd |= 0;
  21911. d -= 86400 * dd;
  21912. }
  21913. zstr.push('d"d"');
  21914. dstr.push(dd + (dstyle == 2 ? " day" + (dd == 1 ? "" : "s") : dstyle == 1 ? "d" : ""));
  21915. }
  21916. if (dmin <= 4 && dmax >= 4) {
  21917. dd = d / 3600;
  21918. if (dmax > 4) {
  21919. dd |= 0;
  21920. d -= 3600 * dd;
  21921. }
  21922. zstr.push((dmin >= 4 ? "[h]" : "h") + '"h"');
  21923. dstr.push(dd + (dstyle == 2 ? " hour" + (dd == 1 ? "" : "s") : dstyle == 1 ? "h" : ""));
  21924. }
  21925. if (dmin <= 8 && dmax >= 8) {
  21926. dd = d / 60;
  21927. if (dmax > 8) {
  21928. dd |= 0;
  21929. d -= 60 * dd;
  21930. }
  21931. zstr.push((dmin >= 8 ? "[m]" : "m") + '"m"');
  21932. if (dstyle == 0)
  21933. dstr.push((dmin == 8 && dmax == 8 || dd >= 10 ? "" : "0") + dd);
  21934. else
  21935. dstr.push(dd + (dstyle == 2 ? " minute" + (dd == 1 ? "" : "s") : dstyle == 1 ? "m" : ""));
  21936. }
  21937. if (dmin <= 16 && dmax >= 16) {
  21938. dd = d;
  21939. if (dmax > 16) {
  21940. dd |= 0;
  21941. d -= dd;
  21942. }
  21943. zstr.push((dmin >= 16 ? "[s]" : "s") + '"s"');
  21944. if (dstyle == 0)
  21945. dstr.push((dmax == 16 && dmin == 16 || dd >= 10 ? "" : "0") + dd);
  21946. else
  21947. dstr.push(dd + (dstyle == 2 ? " second" + (dd == 1 ? "" : "s") : dstyle == 1 ? "s" : ""));
  21948. }
  21949. if (dmax >= 32) {
  21950. dd = Math.round(1e3 * d);
  21951. if (dmin < 32)
  21952. zstr.push('.000"ms"');
  21953. if (dstyle == 0)
  21954. dstr.push((dd >= 100 ? "" : dd >= 10 ? "0" : "00") + dd);
  21955. else
  21956. dstr.push(dd + (dstyle == 2 ? " millisecond" + (dd == 1 ? "" : "s") : dstyle == 1 ? "ms" : ""));
  21957. }
  21958. cell.w = dstr.join(dstyle == 0 ? ":" : " ");
  21959. cell.z = zstr.join(dstyle == 0 ? '":"' : " ");
  21960. if (dstyle == 0)
  21961. cell.w = cell.w.replace(/:(\d\d\d)$/, ".$1");
  21962. }
  21963. }
  21964. function parse_old_storage(buf, lut, v) {
  21965. var dv = u8_to_dataview(buf);
  21966. var flags = dv.getUint32(4, true);
  21967. var ridx = -1, sidx = -1, zidx = -1, ieee = NaN, dt = new Date(2001, 0, 1);
  21968. var doff = v > 1 ? 12 : 8;
  21969. if (flags & 2) {
  21970. zidx = dv.getUint32(doff, true);
  21971. doff += 4;
  21972. }
  21973. doff += popcnt(flags & (v > 1 ? 3468 : 396)) * 4;
  21974. if (flags & 512) {
  21975. ridx = dv.getUint32(doff, true);
  21976. doff += 4;
  21977. }
  21978. doff += popcnt(flags & (v > 1 ? 12288 : 4096)) * 4;
  21979. if (flags & 16) {
  21980. sidx = dv.getUint32(doff, true);
  21981. doff += 4;
  21982. }
  21983. if (flags & 32) {
  21984. ieee = dv.getFloat64(doff, true);
  21985. doff += 8;
  21986. }
  21987. if (flags & 64) {
  21988. dt.setTime(dt.getTime() + dv.getFloat64(doff, true) * 1e3);
  21989. doff += 8;
  21990. }
  21991. if (v > 1) {
  21992. flags = dv.getUint32(8, true) >>> 16;
  21993. if (flags & 255) {
  21994. if (zidx == -1)
  21995. zidx = dv.getUint32(doff, true);
  21996. doff += 4;
  21997. }
  21998. }
  21999. var ret;
  22000. var t = buf[v >= 4 ? 1 : 2];
  22001. switch (t) {
  22002. case 0:
  22003. return void 0;
  22004. case 2:
  22005. ret = { t: "n", v: ieee };
  22006. break;
  22007. case 3:
  22008. ret = { t: "s", v: lut.sst[sidx] };
  22009. break;
  22010. case 5:
  22011. ret = { t: "d", v: dt };
  22012. break;
  22013. case 6:
  22014. ret = { t: "b", v: ieee > 0 };
  22015. break;
  22016. case 7:
  22017. ret = { t: "n", v: ieee };
  22018. break;
  22019. case 8:
  22020. ret = { t: "e", v: 0 };
  22021. break;
  22022. case 9:
  22023. {
  22024. if (ridx > -1)
  22025. ret = { t: "s", v: lut.rsst[ridx] };
  22026. else
  22027. throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4)));
  22028. }
  22029. break;
  22030. default:
  22031. throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4)));
  22032. }
  22033. if (zidx > -1)
  22034. numbers_format_cell(ret, t | v << 8, flags, lut.ofmt[zidx], lut.nfmt[zidx]);
  22035. if (t == 7)
  22036. ret.v /= 86400;
  22037. return ret;
  22038. }
  22039. function parse_new_storage(buf, lut) {
  22040. var dv = u8_to_dataview(buf);
  22041. var flags = dv.getUint32(4, true);
  22042. var fields = dv.getUint32(8, true);
  22043. var doff = 12;
  22044. var ridx = -1, sidx = -1, zidx = -1, d128 = NaN, ieee = NaN, dt = new Date(2001, 0, 1);
  22045. if (fields & 1) {
  22046. d128 = readDecimal128LE(buf, doff);
  22047. doff += 16;
  22048. }
  22049. if (fields & 2) {
  22050. ieee = dv.getFloat64(doff, true);
  22051. doff += 8;
  22052. }
  22053. if (fields & 4) {
  22054. dt.setTime(dt.getTime() + dv.getFloat64(doff, true) * 1e3);
  22055. doff += 8;
  22056. }
  22057. if (fields & 8) {
  22058. sidx = dv.getUint32(doff, true);
  22059. doff += 4;
  22060. }
  22061. if (fields & 16) {
  22062. ridx = dv.getUint32(doff, true);
  22063. doff += 4;
  22064. }
  22065. var ret;
  22066. var t = buf[1];
  22067. switch (t) {
  22068. case 0:
  22069. return void 0;
  22070. case 2:
  22071. ret = { t: "n", v: d128 };
  22072. break;
  22073. case 3:
  22074. ret = { t: "s", v: lut.sst[sidx] };
  22075. break;
  22076. case 5:
  22077. ret = { t: "d", v: dt };
  22078. break;
  22079. case 6:
  22080. ret = { t: "b", v: ieee > 0 };
  22081. break;
  22082. case 7:
  22083. ret = { t: "n", v: ieee };
  22084. break;
  22085. case 8:
  22086. ret = { t: "e", v: 0 };
  22087. break;
  22088. case 9:
  22089. ret = { t: "s", v: lut.rsst[ridx] };
  22090. break;
  22091. case 10:
  22092. ret = { t: "n", v: d128 };
  22093. break;
  22094. default:
  22095. throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4)));
  22096. }
  22097. doff += popcnt(fields & 8160) * 4;
  22098. if (fields & 516096) {
  22099. if (zidx == -1)
  22100. zidx = dv.getUint32(doff, true);
  22101. doff += 4;
  22102. }
  22103. if (zidx > -1)
  22104. numbers_format_cell(ret, t | 5 << 8, fields >> 13, lut.ofmt[zidx], lut.nfmt[zidx]);
  22105. if (t == 7)
  22106. ret.v /= 86400;
  22107. return ret;
  22108. }
  22109. function write_new_storage(cell, sst) {
  22110. var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0;
  22111. out[0] = 5;
  22112. switch (cell.t) {
  22113. case "n":
  22114. out[1] = 2;
  22115. writeDecimal128LE(out, l, cell.v);
  22116. flags |= 1;
  22117. l += 16;
  22118. break;
  22119. case "b":
  22120. out[1] = 6;
  22121. dv.setFloat64(l, cell.v ? 1 : 0, true);
  22122. flags |= 2;
  22123. l += 8;
  22124. break;
  22125. case "s":
  22126. var s = cell.v == null ? "" : String(cell.v);
  22127. var isst = sst.indexOf(s);
  22128. if (isst == -1)
  22129. sst[isst = sst.length] = s;
  22130. out[1] = 3;
  22131. dv.setUint32(l, isst, true);
  22132. flags |= 8;
  22133. l += 4;
  22134. break;
  22135. default:
  22136. throw "unsupported cell type " + cell.t;
  22137. }
  22138. dv.setUint32(8, flags, true);
  22139. return out[subarray](0, l);
  22140. }
  22141. function write_old_storage(cell, sst) {
  22142. var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0;
  22143. out[0] = 4;
  22144. switch (cell.t) {
  22145. case "n":
  22146. out[2] = 2;
  22147. dv.setFloat64(l, cell.v, true);
  22148. flags |= 32;
  22149. l += 8;
  22150. break;
  22151. case "b":
  22152. out[2] = 6;
  22153. dv.setFloat64(l, cell.v ? 1 : 0, true);
  22154. flags |= 32;
  22155. l += 8;
  22156. break;
  22157. case "s":
  22158. var s = cell.v == null ? "" : String(cell.v);
  22159. var isst = sst.indexOf(s);
  22160. if (isst == -1)
  22161. sst[isst = sst.length] = s;
  22162. out[2] = 3;
  22163. dv.setUint32(l, isst, true);
  22164. flags |= 16;
  22165. l += 4;
  22166. break;
  22167. default:
  22168. throw "unsupported cell type " + cell.t;
  22169. }
  22170. dv.setUint32(8, flags, true);
  22171. return out[subarray](0, l);
  22172. }
  22173. function parse_cell_storage(buf, lut) {
  22174. switch (buf[0]) {
  22175. case 0:
  22176. case 1:
  22177. case 2:
  22178. case 3:
  22179. case 4:
  22180. return parse_old_storage(buf, lut, buf[0]);
  22181. case 5:
  22182. return parse_new_storage(buf, lut);
  22183. default:
  22184. throw new Error("Unsupported payload version ".concat(buf[0]));
  22185. }
  22186. }
  22187. function parse_TSP_Reference(buf) {
  22188. var pb = parse_shallow(buf);
  22189. return parse_varint49(pb[1][0].data);
  22190. }
  22191. function write_TSP_Reference(idx) {
  22192. return write_shallow([
  22193. [],
  22194. [{ type: 0, data: write_varint49(idx) }]
  22195. ]);
  22196. }
  22197. function numbers_add_oref(iwa, ref) {
  22198. var _a;
  22199. var orefs = ((_a = iwa.messages[0].meta[5]) == null ? void 0 : _a[0]) ? parse_packed_varints(iwa.messages[0].meta[5][0].data) : [];
  22200. var orefidx = orefs.indexOf(ref);
  22201. if (orefidx == -1) {
  22202. orefs.push(ref);
  22203. iwa.messages[0].meta[5] = [{ type: 2, data: write_packed_varints(orefs) }];
  22204. }
  22205. }
  22206. function numbers_del_oref(iwa, ref) {
  22207. var _a;
  22208. var orefs = ((_a = iwa.messages[0].meta[5]) == null ? void 0 : _a[0]) ? parse_packed_varints(iwa.messages[0].meta[5][0].data) : [];
  22209. iwa.messages[0].meta[5] = [{ type: 2, data: write_packed_varints(orefs.filter(function(r) {
  22210. return r != ref;
  22211. })) }];
  22212. }
  22213. function parse_TST_TableDataList(M, root) {
  22214. var pb = parse_shallow(root.data);
  22215. var type = varint_to_i32(pb[1][0].data);
  22216. var entries = pb[3];
  22217. var data = [];
  22218. (entries || []).forEach(function(entry) {
  22219. var le = parse_shallow(entry.data);
  22220. if (!le[1])
  22221. return;
  22222. var key = varint_to_i32(le[1][0].data) >>> 0;
  22223. switch (type) {
  22224. case 1:
  22225. data[key] = u8str(le[3][0].data);
  22226. break;
  22227. case 8:
  22228. {
  22229. var rt = M[parse_TSP_Reference(le[9][0].data)][0];
  22230. var rtp = parse_shallow(rt.data);
  22231. var rtpref = M[parse_TSP_Reference(rtp[1][0].data)][0];
  22232. var mtype = varint_to_i32(rtpref.meta[1][0].data);
  22233. if (mtype != 2001)
  22234. throw new Error("2000 unexpected reference to ".concat(mtype));
  22235. var tswpsa = parse_shallow(rtpref.data);
  22236. data[key] = tswpsa[3].map(function(x) {
  22237. return u8str(x.data);
  22238. }).join("");
  22239. }
  22240. break;
  22241. case 2:
  22242. data[key] = parse_shallow(le[6][0].data);
  22243. break;
  22244. default:
  22245. throw type;
  22246. }
  22247. });
  22248. return data;
  22249. }
  22250. function parse_TST_TileRowInfo(u8, type) {
  22251. var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  22252. var pb = parse_shallow(u8);
  22253. var R = varint_to_i32(pb[1][0].data) >>> 0;
  22254. var cnt = varint_to_i32(pb[2][0].data) >>> 0;
  22255. var wide_offsets = ((_b = (_a = pb[8]) == null ? void 0 : _a[0]) == null ? void 0 : _b.data) && varint_to_i32(pb[8][0].data) > 0 || false;
  22256. var used_storage_u8, used_storage;
  22257. if (((_d = (_c = pb[7]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && type != 0) {
  22258. used_storage_u8 = (_f = (_e = pb[7]) == null ? void 0 : _e[0]) == null ? void 0 : _f.data;
  22259. used_storage = (_h = (_g = pb[6]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data;
  22260. } else if (((_j = (_i = pb[4]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) && type != 1) {
  22261. used_storage_u8 = (_l = (_k = pb[4]) == null ? void 0 : _k[0]) == null ? void 0 : _l.data;
  22262. used_storage = (_n = (_m = pb[3]) == null ? void 0 : _m[0]) == null ? void 0 : _n.data;
  22263. } else
  22264. throw "NUMBERS Tile missing ".concat(type, " cell storage");
  22265. var width = wide_offsets ? 4 : 1;
  22266. var used_storage_offsets = u8_to_dataview(used_storage_u8);
  22267. var offsets = [];
  22268. for (var C = 0; C < used_storage_u8.length / 2; ++C) {
  22269. var off = used_storage_offsets.getUint16(C * 2, true);
  22270. if (off < 65535)
  22271. offsets.push([C, off]);
  22272. }
  22273. if (offsets.length != cnt)
  22274. throw "Expected ".concat(cnt, " cells, found ").concat(offsets.length);
  22275. var cells = [];
  22276. for (C = 0; C < offsets.length - 1; ++C)
  22277. cells[offsets[C][0]] = used_storage[subarray](offsets[C][1] * width, offsets[C + 1][1] * width);
  22278. if (offsets.length >= 1)
  22279. cells[offsets[offsets.length - 1][0]] = used_storage[subarray](offsets[offsets.length - 1][1] * width);
  22280. return { R: R, cells: cells };
  22281. }
  22282. function parse_TST_Tile(M, root) {
  22283. var _a;
  22284. var pb = parse_shallow(root.data);
  22285. var storage = -1;
  22286. if ((_a = pb == null ? void 0 : pb[7]) == null ? void 0 : _a[0]) {
  22287. if (varint_to_i32(pb[7][0].data) >>> 0)
  22288. storage = 1;
  22289. else
  22290. storage = 0;
  22291. }
  22292. var ri = mappa(pb[5], function(u8) {
  22293. return parse_TST_TileRowInfo(u8, storage);
  22294. });
  22295. return {
  22296. nrows: varint_to_i32(pb[4][0].data) >>> 0,
  22297. data: ri.reduce(function(acc, x) {
  22298. if (!acc[x.R])
  22299. acc[x.R] = [];
  22300. x.cells.forEach(function(cell, C) {
  22301. if (acc[x.R][C])
  22302. throw new Error("Duplicate cell r=".concat(x.R, " c=").concat(C));
  22303. acc[x.R][C] = cell;
  22304. });
  22305. return acc;
  22306. }, [])
  22307. };
  22308. }
  22309. function parse_TST_TableModelArchive(M, root, ws) {
  22310. var _a, _b, _c, _d, _e, _f;
  22311. var pb = parse_shallow(root.data);
  22312. var range = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
  22313. range.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1;
  22314. if (range.e.r < 0)
  22315. throw new Error("Invalid row varint ".concat(pb[6][0].data));
  22316. range.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1;
  22317. if (range.e.c < 0)
  22318. throw new Error("Invalid col varint ".concat(pb[7][0].data));
  22319. ws["!ref"] = encode_range(range);
  22320. var dense = Array.isArray(ws);
  22321. var store = parse_shallow(pb[4][0].data);
  22322. var lut = numbers_lut_new();
  22323. if ((_a = store[4]) == null ? void 0 : _a[0])
  22324. lut.sst = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[4][0].data)][0]);
  22325. if ((_b = store[11]) == null ? void 0 : _b[0])
  22326. lut.ofmt = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[11][0].data)][0]);
  22327. if ((_c = store[17]) == null ? void 0 : _c[0])
  22328. lut.rsst = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[17][0].data)][0]);
  22329. if ((_d = store[22]) == null ? void 0 : _d[0])
  22330. lut.nfmt = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[22][0].data)][0]);
  22331. var tile = parse_shallow(store[3][0].data);
  22332. var _R = 0;
  22333. tile[1].forEach(function(t) {
  22334. var tl = parse_shallow(t.data);
  22335. var ref2 = M[parse_TSP_Reference(tl[2][0].data)][0];
  22336. var mtype2 = varint_to_i32(ref2.meta[1][0].data);
  22337. if (mtype2 != 6002)
  22338. throw new Error("6001 unexpected reference to ".concat(mtype2));
  22339. var _tile = parse_TST_Tile(M, ref2);
  22340. _tile.data.forEach(function(row, R) {
  22341. row.forEach(function(buf, C) {
  22342. var res = parse_cell_storage(buf, lut);
  22343. if (res) {
  22344. if (dense) {
  22345. if (!ws[_R + R])
  22346. ws[_R + R] = [];
  22347. ws[_R + R][C] = res;
  22348. } else {
  22349. var addr = encode_cell({ r: _R + R, c: C });
  22350. ws[addr] = res;
  22351. }
  22352. }
  22353. });
  22354. });
  22355. _R += _tile.nrows;
  22356. });
  22357. if ((_e = store[13]) == null ? void 0 : _e[0]) {
  22358. var ref = M[parse_TSP_Reference(store[13][0].data)][0];
  22359. var mtype = varint_to_i32(ref.meta[1][0].data);
  22360. if (mtype != 6144)
  22361. throw new Error("Expected merge type 6144, found ".concat(mtype));
  22362. ws["!merges"] = (_f = parse_shallow(ref.data)) == null ? void 0 : _f[1].map(function(pi) {
  22363. var merge = parse_shallow(pi.data);
  22364. var origin = u8_to_dataview(parse_shallow(merge[1][0].data)[1][0].data), size = u8_to_dataview(parse_shallow(merge[2][0].data)[1][0].data);
  22365. return {
  22366. s: { r: origin.getUint16(0, true), c: origin.getUint16(2, true) },
  22367. e: {
  22368. r: origin.getUint16(0, true) + size.getUint16(0, true) - 1,
  22369. c: origin.getUint16(2, true) + size.getUint16(2, true) - 1
  22370. }
  22371. };
  22372. });
  22373. }
  22374. }
  22375. function parse_TST_TableInfoArchive(M, root, opts) {
  22376. var pb = parse_shallow(root.data);
  22377. var out;
  22378. if (!(opts == null ? void 0 : opts.dense))
  22379. out = { "!ref": "A1" };
  22380. else
  22381. out = [];
  22382. out["!ref"] = "A1";
  22383. var tableref = M[parse_TSP_Reference(pb[2][0].data)];
  22384. var mtype = varint_to_i32(tableref[0].meta[1][0].data);
  22385. if (mtype != 6001)
  22386. throw new Error("6000 unexpected reference to ".concat(mtype));
  22387. parse_TST_TableModelArchive(M, tableref[0], out);
  22388. return out;
  22389. }
  22390. function parse_TN_SheetArchive(M, root, opts) {
  22391. var _a;
  22392. var pb = parse_shallow(root.data);
  22393. var out = {
  22394. name: ((_a = pb[1]) == null ? void 0 : _a[0]) ? u8str(pb[1][0].data) : "",
  22395. sheets: []
  22396. };
  22397. var shapeoffs = mappa(pb[2], parse_TSP_Reference);
  22398. shapeoffs.forEach(function(off) {
  22399. M[off].forEach(function(m) {
  22400. var mtype = varint_to_i32(m.meta[1][0].data);
  22401. if (mtype == 6e3)
  22402. out.sheets.push(parse_TST_TableInfoArchive(M, m, opts));
  22403. });
  22404. });
  22405. return out;
  22406. }
  22407. function parse_TN_DocumentArchive(M, root, opts) {
  22408. var _a;
  22409. var out = book_new();
  22410. var pb = parse_shallow(root.data);
  22411. if ((_a = pb[2]) == null ? void 0 : _a[0])
  22412. throw new Error("Keynote presentations are not supported");
  22413. var sheetoffs = mappa(pb[1], parse_TSP_Reference);
  22414. sheetoffs.forEach(function(off) {
  22415. M[off].forEach(function(m) {
  22416. var mtype = varint_to_i32(m.meta[1][0].data);
  22417. if (mtype == 2) {
  22418. var root2 = parse_TN_SheetArchive(M, m, opts);
  22419. root2.sheets.forEach(function(sheet, idx) {
  22420. book_append_sheet(out, sheet, idx == 0 ? root2.name : root2.name + "_" + idx, true);
  22421. });
  22422. }
  22423. });
  22424. });
  22425. if (out.SheetNames.length == 0)
  22426. throw new Error("Empty NUMBERS file");
  22427. out.bookType = "numbers";
  22428. return out;
  22429. }
  22430. function parse_numbers_iwa(cfb, opts) {
  22431. var _a, _b, _c, _d, _e, _f, _g;
  22432. var M = {}, indices = [];
  22433. cfb.FullPaths.forEach(function(p) {
  22434. if (p.match(/\.iwpv2/))
  22435. throw new Error("Unsupported password protection");
  22436. });
  22437. cfb.FileIndex.forEach(function(s) {
  22438. if (!s.name.match(/\.iwa$/))
  22439. return;
  22440. if (s.content[0] == 98)
  22441. return;
  22442. var o;
  22443. try {
  22444. o = decompress_iwa_file(s.content);
  22445. } catch (e) {
  22446. return console.log("?? " + s.content.length + " " + (e.message || e));
  22447. }
  22448. var packets;
  22449. try {
  22450. packets = parse_iwa_file(o);
  22451. } catch (e) {
  22452. return console.log("## " + (e.message || e));
  22453. }
  22454. packets.forEach(function(packet) {
  22455. M[packet.id] = packet.messages;
  22456. indices.push(packet.id);
  22457. });
  22458. });
  22459. if (!indices.length)
  22460. throw new Error("File has no messages");
  22461. if (((_c = (_b = (_a = M == null ? void 0 : M[1]) == null ? void 0 : _a[0].meta) == null ? void 0 : _b[1]) == null ? void 0 : _c[0].data) && varint_to_i32(M[1][0].meta[1][0].data) == 1e4)
  22462. throw new Error("Pages documents are not supported");
  22463. var docroot = ((_g = (_f = (_e = (_d = M == null ? void 0 : M[1]) == null ? void 0 : _d[0]) == null ? void 0 : _e.meta) == null ? void 0 : _f[1]) == null ? void 0 : _g[0].data) && varint_to_i32(M[1][0].meta[1][0].data) == 1 && M[1][0];
  22464. if (!docroot)
  22465. indices.forEach(function(idx) {
  22466. M[idx].forEach(function(iwam) {
  22467. var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0;
  22468. if (mtype == 1) {
  22469. if (!docroot)
  22470. docroot = iwam;
  22471. else
  22472. throw new Error("Document has multiple roots");
  22473. }
  22474. });
  22475. });
  22476. if (!docroot)
  22477. throw new Error("Cannot find Document root");
  22478. return parse_TN_DocumentArchive(M, docroot, opts);
  22479. }
  22480. function write_TST_TileRowInfo(data, SST, wide) {
  22481. var _a, _b;
  22482. var tri = [
  22483. [],
  22484. [{ type: 0, data: write_varint49(0) }],
  22485. [{ type: 0, data: write_varint49(0) }],
  22486. [{ type: 2, data: new Uint8Array([]) }],
  22487. [{ type: 2, data: new Uint8Array(Array.from({ length: 510 }, function() {
  22488. return 255;
  22489. })) }],
  22490. [{ type: 0, data: write_varint49(5) }],
  22491. [{ type: 2, data: new Uint8Array([]) }],
  22492. [{ type: 2, data: new Uint8Array(Array.from({ length: 510 }, function() {
  22493. return 255;
  22494. })) }],
  22495. [{ type: 0, data: write_varint49(1) }]
  22496. ];
  22497. if (!((_a = tri[6]) == null ? void 0 : _a[0]) || !((_b = tri[7]) == null ? void 0 : _b[0]))
  22498. throw "Mutation only works on post-BNC storages!";
  22499. var cnt = 0;
  22500. if (tri[7][0].data.length < 2 * data.length) {
  22501. var new_7 = new Uint8Array(2 * data.length);
  22502. new_7.set(tri[7][0].data);
  22503. tri[7][0].data = new_7;
  22504. }
  22505. if (tri[4][0].data.length < 2 * data.length) {
  22506. var new_4 = new Uint8Array(2 * data.length);
  22507. new_4.set(tri[4][0].data);
  22508. tri[4][0].data = new_4;
  22509. }
  22510. var dv = u8_to_dataview(tri[7][0].data), last_offset = 0, cell_storage = [];
  22511. var _dv = u8_to_dataview(tri[4][0].data), _last_offset = 0, _cell_storage = [];
  22512. var width = wide ? 4 : 1;
  22513. for (var C = 0; C < data.length; ++C) {
  22514. if (data[C] == null) {
  22515. dv.setUint16(C * 2, 65535, true);
  22516. _dv.setUint16(C * 2, 65535);
  22517. continue;
  22518. }
  22519. dv.setUint16(C * 2, last_offset / width, true);
  22520. _dv.setUint16(C * 2, _last_offset / width, true);
  22521. var celload, _celload;
  22522. switch (typeof data[C]) {
  22523. case "string":
  22524. celload = write_new_storage({ t: "s", v: data[C] }, SST);
  22525. _celload = write_old_storage({ t: "s", v: data[C] }, SST);
  22526. break;
  22527. case "number":
  22528. celload = write_new_storage({ t: "n", v: data[C] }, SST);
  22529. _celload = write_old_storage({ t: "n", v: data[C] }, SST);
  22530. break;
  22531. case "boolean":
  22532. celload = write_new_storage({ t: "b", v: data[C] }, SST);
  22533. _celload = write_old_storage({ t: "b", v: data[C] }, SST);
  22534. break;
  22535. default:
  22536. if (data[C] instanceof Date) {
  22537. celload = write_new_storage({ t: "s", v: data[C].toISOString() }, SST);
  22538. _celload = write_old_storage({ t: "s", v: data[C].toISOString() }, SST);
  22539. break;
  22540. }
  22541. throw new Error("Unsupported value " + data[C]);
  22542. }
  22543. cell_storage.push(celload);
  22544. last_offset += celload.length;
  22545. {
  22546. _cell_storage.push(_celload);
  22547. _last_offset += _celload.length;
  22548. }
  22549. ++cnt;
  22550. }
  22551. tri[2][0].data = write_varint49(cnt);
  22552. tri[5][0].data = write_varint49(5);
  22553. for (; C < tri[7][0].data.length / 2; ++C) {
  22554. dv.setUint16(C * 2, 65535, true);
  22555. _dv.setUint16(C * 2, 65535, true);
  22556. }
  22557. tri[6][0].data = u8concat(cell_storage);
  22558. tri[3][0].data = u8concat(_cell_storage);
  22559. tri[8] = [{ type: 0, data: write_varint49(wide ? 1 : 0) }];
  22560. return tri;
  22561. }
  22562. function write_iwam(type, payload) {
  22563. return {
  22564. meta: [
  22565. [],
  22566. [{ type: 0, data: write_varint49(type) }]
  22567. ],
  22568. data: payload
  22569. };
  22570. }
  22571. function get_unique_msgid(dep, dependents) {
  22572. if (!dependents.last)
  22573. dependents.last = 927262;
  22574. for (var i = dependents.last; i < 2e6; ++i)
  22575. if (!dependents[i]) {
  22576. dependents[dependents.last = i] = dep;
  22577. return i;
  22578. }
  22579. throw new Error("Too many messages");
  22580. }
  22581. function build_numbers_deps(cfb) {
  22582. var dependents = {};
  22583. var indices = [];
  22584. cfb.FileIndex.map(function(fi, idx) {
  22585. return [fi, cfb.FullPaths[idx]];
  22586. }).forEach(function(row) {
  22587. var fi = row[0], fp = row[1];
  22588. if (fi.type != 2)
  22589. return;
  22590. if (!fi.name.match(/\.iwa/))
  22591. return;
  22592. if (fi.name.match(/OperationStorage/))
  22593. return;
  22594. parse_iwa_file(decompress_iwa_file(fi.content)).forEach(function(packet) {
  22595. indices.push(packet.id);
  22596. dependents[packet.id] = { deps: [], location: fp, type: varint_to_i32(packet.messages[0].meta[1][0].data) };
  22597. });
  22598. });
  22599. indices.sort(function(x, y) {
  22600. return x - y;
  22601. });
  22602. var indices_varint = indices.filter(function(x) {
  22603. return x > 1;
  22604. }).map(function(x) {
  22605. return [x, write_varint49(x)];
  22606. });
  22607. cfb.FileIndex.forEach(function(fi) {
  22608. if (!fi.name.match(/\.iwa/))
  22609. return;
  22610. if (fi.name.match(/OperationStorage/))
  22611. return;
  22612. parse_iwa_file(decompress_iwa_file(fi.content)).forEach(function(ia) {
  22613. indices_varint.forEach(function(ivi) {
  22614. if (ia.messages.some(function(mess) {
  22615. return varint_to_i32(mess.meta[1][0].data) != 11006 && u8contains(mess.data, ivi[1]);
  22616. })) {
  22617. dependents[ivi[0]].deps.push(ia.id);
  22618. }
  22619. });
  22620. });
  22621. });
  22622. return dependents;
  22623. }
  22624. function write_numbers_iwa(wb, opts) {
  22625. if (!opts || !opts.numbers)
  22626. throw new Error("Must pass a `numbers` option -- check the README");
  22627. var cfb = CFB.read(opts.numbers, { type: "base64" });
  22628. var deps = build_numbers_deps(cfb);
  22629. var docroot = numbers_iwa_find(cfb, deps, 1);
  22630. if (docroot == null)
  22631. throw "Could not find message ".concat(1, " in Numbers template");
  22632. var sheetrefs = mappa(parse_shallow(docroot.messages[0].data)[1], parse_TSP_Reference);
  22633. if (sheetrefs.length > 1)
  22634. throw new Error("Template NUMBERS file must have exactly one sheet");
  22635. wb.SheetNames.forEach(function(name, idx) {
  22636. if (idx >= 1) {
  22637. numbers_add_ws(cfb, deps, idx + 1);
  22638. docroot = numbers_iwa_find(cfb, deps, 1);
  22639. sheetrefs = mappa(parse_shallow(docroot.messages[0].data)[1], parse_TSP_Reference);
  22640. }
  22641. write_numbers_ws(cfb, deps, wb.Sheets[name], name, idx, sheetrefs[idx]);
  22642. });
  22643. return cfb;
  22644. }
  22645. function numbers_iwa_doit(cfb, deps, id, cb) {
  22646. var entry = CFB.find(cfb, deps[id].location);
  22647. if (!entry)
  22648. throw "Could not find ".concat(deps[id].location, " in Numbers template");
  22649. var x = parse_iwa_file(decompress_iwa_file(entry.content));
  22650. var ainfo = x.find(function(packet) {
  22651. return packet.id == id;
  22652. });
  22653. cb(ainfo, x);
  22654. entry.content = compress_iwa_file(write_iwa_file(x));
  22655. entry.size = entry.content.length;
  22656. }
  22657. function numbers_iwa_find(cfb, deps, id) {
  22658. var entry = CFB.find(cfb, deps[id].location);
  22659. if (!entry)
  22660. throw "Could not find ".concat(deps[id].location, " in Numbers template");
  22661. var x = parse_iwa_file(decompress_iwa_file(entry.content));
  22662. var ainfo = x.find(function(packet) {
  22663. return packet.id == id;
  22664. });
  22665. return ainfo;
  22666. }
  22667. function numbers_add_ws(cfb, deps, wsidx) {
  22668. var sheetref = -1, newsheetref = -1;
  22669. var remap = {};
  22670. numbers_iwa_doit(cfb, deps, 1, function(docroot, arch) {
  22671. var doc = parse_shallow(docroot.messages[0].data);
  22672. sheetref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[1][0].data);
  22673. newsheetref = get_unique_msgid({ deps: [1], location: deps[sheetref].location, type: 2 }, deps);
  22674. remap[sheetref] = newsheetref;
  22675. numbers_add_oref(docroot, newsheetref);
  22676. doc[1].push({ type: 2, data: write_TSP_Reference(newsheetref) });
  22677. var sheet = numbers_iwa_find(cfb, deps, sheetref);
  22678. sheet.id = newsheetref;
  22679. if (deps[1].location == deps[newsheetref].location)
  22680. arch.push(sheet);
  22681. else
  22682. numbers_iwa_doit(cfb, deps, newsheetref, function(_, x) {
  22683. return x.push(sheet);
  22684. });
  22685. docroot.messages[0].data = write_shallow(doc);
  22686. });
  22687. var tiaref = -1;
  22688. numbers_iwa_doit(cfb, deps, newsheetref, function(sheetroot, arch) {
  22689. var sa = parse_shallow(sheetroot.messages[0].data);
  22690. for (var i = 3; i <= 69; ++i)
  22691. delete sa[i];
  22692. var drawables = mappa(sa[2], parse_TSP_Reference);
  22693. drawables.forEach(function(n) {
  22694. return numbers_del_oref(sheetroot, n);
  22695. });
  22696. tiaref = get_unique_msgid({ deps: [newsheetref], location: deps[drawables[0]].location, type: deps[drawables[0]].type }, deps);
  22697. numbers_add_oref(sheetroot, tiaref);
  22698. remap[drawables[0]] = tiaref;
  22699. sa[2] = [{ type: 2, data: write_TSP_Reference(tiaref) }];
  22700. var tia = numbers_iwa_find(cfb, deps, drawables[0]);
  22701. tia.id = tiaref;
  22702. if (deps[drawables[0]].location == deps[newsheetref].location)
  22703. arch.push(tia);
  22704. else {
  22705. var loc2 = deps[newsheetref].location;
  22706. loc2 = loc2.replace(/^Root Entry\//, "");
  22707. loc2 = loc2.replace(/^Index\//, "").replace(/\.iwa$/, "");
  22708. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  22709. var mlist = parse_shallow(ai.messages[0].data);
  22710. var parentidx = mlist[3].findIndex(function(m) {
  22711. var _a, _b;
  22712. var mm = parse_shallow(m.data);
  22713. if ((_a = mm[3]) == null ? void 0 : _a[0])
  22714. return u8str(mm[3][0].data) == loc2;
  22715. if (((_b = mm[2]) == null ? void 0 : _b[0]) && u8str(mm[2][0].data) == loc2)
  22716. return true;
  22717. return false;
  22718. });
  22719. var parent = parse_shallow(mlist[3][parentidx].data);
  22720. if (!parent[6])
  22721. parent[6] = [];
  22722. parent[6].push({
  22723. type: 2,
  22724. data: write_shallow([
  22725. [],
  22726. [{ type: 0, data: write_varint49(tiaref) }]
  22727. ])
  22728. });
  22729. mlist[3][parentidx].data = write_shallow(parent);
  22730. ai.messages[0].data = write_shallow(mlist);
  22731. });
  22732. numbers_iwa_doit(cfb, deps, tiaref, function(_, x) {
  22733. return x.push(tia);
  22734. });
  22735. }
  22736. sheetroot.messages[0].data = write_shallow(sa);
  22737. });
  22738. var tmaref = -1;
  22739. numbers_iwa_doit(cfb, deps, tiaref, function(tiaroot, arch) {
  22740. var tia = parse_shallow(tiaroot.messages[0].data);
  22741. var da = parse_shallow(tia[1][0].data);
  22742. for (var i = 3; i <= 69; ++i)
  22743. delete da[i];
  22744. var dap = parse_TSP_Reference(da[2][0].data);
  22745. da[2][0].data = write_TSP_Reference(remap[dap]);
  22746. tia[1][0].data = write_shallow(da);
  22747. var oldtmaref = parse_TSP_Reference(tia[2][0].data);
  22748. numbers_del_oref(tiaroot, oldtmaref);
  22749. tmaref = get_unique_msgid({ deps: [tiaref], location: deps[oldtmaref].location, type: deps[oldtmaref].type }, deps);
  22750. numbers_add_oref(tiaroot, tmaref);
  22751. remap[oldtmaref] = tmaref;
  22752. tia[2][0].data = write_TSP_Reference(tmaref);
  22753. var tma = numbers_iwa_find(cfb, deps, oldtmaref);
  22754. tma.id = tmaref;
  22755. if (deps[tiaref].location == deps[tmaref].location)
  22756. arch.push(tma);
  22757. else
  22758. numbers_iwa_doit(cfb, deps, tmaref, function(_, x) {
  22759. return x.push(tma);
  22760. });
  22761. tiaroot.messages[0].data = write_shallow(tia);
  22762. });
  22763. var loc = deps[tmaref].location;
  22764. loc = loc.replace(/^Root Entry\//, "");
  22765. loc = loc.replace(/^Index\//, "").replace(/\.iwa$/, "");
  22766. numbers_iwa_doit(cfb, deps, tmaref, function(tmaroot, arch) {
  22767. var _a, _b;
  22768. var tma = parse_shallow(tmaroot.messages[0].data);
  22769. var uuid = u8str(tma[1][0].data), new_uuid = uuid.replace(/-[A-Z0-9]*/, "-".concat(wsidx.toString(16).padStart(4, "0")));
  22770. tma[1][0].data = stru8(new_uuid);
  22771. [12, 13, 29, 31, 32, 33, 39, 44, 47, 81, 82, 84].forEach(function(n) {
  22772. return delete tma[n];
  22773. });
  22774. if (tma[45]) {
  22775. var srrta = parse_shallow(tma[45][0].data);
  22776. var ref = parse_TSP_Reference(srrta[1][0].data);
  22777. numbers_del_oref(tmaroot, ref);
  22778. delete tma[45];
  22779. }
  22780. if (tma[70]) {
  22781. var hsoa = parse_shallow(tma[70][0].data);
  22782. (_a = hsoa[2]) == null ? void 0 : _a.forEach(function(item) {
  22783. var hsa = parse_shallow(item.data);
  22784. [2, 3].map(function(n) {
  22785. return hsa[n][0];
  22786. }).forEach(function(hseadata) {
  22787. var hsea = parse_shallow(hseadata.data);
  22788. if (!hsea[8])
  22789. return;
  22790. var ref2 = parse_TSP_Reference(hsea[8][0].data);
  22791. numbers_del_oref(tmaroot, ref2);
  22792. });
  22793. });
  22794. delete tma[70];
  22795. }
  22796. [
  22797. 46,
  22798. 30,
  22799. 34,
  22800. 35,
  22801. 36,
  22802. 38,
  22803. 48,
  22804. 49,
  22805. 60,
  22806. 61,
  22807. 62,
  22808. 63,
  22809. 64,
  22810. 71,
  22811. 72,
  22812. 73,
  22813. 74,
  22814. 75,
  22815. 85,
  22816. 86,
  22817. 87,
  22818. 88,
  22819. 89
  22820. ].forEach(function(n) {
  22821. if (!tma[n])
  22822. return;
  22823. var ref2 = parse_TSP_Reference(tma[n][0].data);
  22824. delete tma[n];
  22825. numbers_del_oref(tmaroot, ref2);
  22826. });
  22827. var store = parse_shallow(tma[4][0].data);
  22828. {
  22829. [2, 4, 5, 6, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22].forEach(function(n) {
  22830. var _a2;
  22831. if (!((_a2 = store[n]) == null ? void 0 : _a2[0]))
  22832. return;
  22833. var oldref = parse_TSP_Reference(store[n][0].data);
  22834. var newref = get_unique_msgid({ deps: [tmaref], location: deps[oldref].location, type: deps[oldref].type }, deps);
  22835. numbers_del_oref(tmaroot, oldref);
  22836. numbers_add_oref(tmaroot, newref);
  22837. remap[oldref] = newref;
  22838. var msg = numbers_iwa_find(cfb, deps, oldref);
  22839. msg.id = newref;
  22840. if (deps[oldref].location == deps[tmaref].location)
  22841. arch.push(msg);
  22842. else {
  22843. deps[newref].location = deps[oldref].location.replace(oldref.toString(), newref.toString());
  22844. if (deps[newref].location == deps[oldref].location)
  22845. deps[newref].location = deps[newref].location.replace(/\.iwa/, "-".concat(newref, ".iwa"));
  22846. CFB.utils.cfb_add(cfb, deps[newref].location, compress_iwa_file(write_iwa_file([msg])));
  22847. var newloc = deps[newref].location;
  22848. newloc = newloc.replace(/^Root Entry\//, "");
  22849. newloc = newloc.replace(/^Index\//, "").replace(/\.iwa$/, "");
  22850. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  22851. var mlist = parse_shallow(ai.messages[0].data);
  22852. mlist[3].push({ type: 2, data: write_shallow([
  22853. [],
  22854. [{ type: 0, data: write_varint49(newref) }],
  22855. [{ type: 2, data: stru8(newloc.replace(/-.*$/, "")) }],
  22856. [{ type: 2, data: stru8(newloc) }],
  22857. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  22858. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  22859. [],
  22860. [],
  22861. [],
  22862. [],
  22863. [{ type: 0, data: write_varint49(0) }],
  22864. [],
  22865. [{ type: 0, data: write_varint49(0) }]
  22866. ]) });
  22867. mlist[1] = [{ type: 0, data: write_varint49(Math.max(newref + 1, parse_varint49(mlist[1][0].data))) }];
  22868. var parentidx = mlist[3].findIndex(function(m) {
  22869. var _a3, _b2;
  22870. var mm = parse_shallow(m.data);
  22871. if ((_a3 = mm[3]) == null ? void 0 : _a3[0])
  22872. return u8str(mm[3][0].data) == loc;
  22873. if (((_b2 = mm[2]) == null ? void 0 : _b2[0]) && u8str(mm[2][0].data) == loc)
  22874. return true;
  22875. return false;
  22876. });
  22877. var parent = parse_shallow(mlist[3][parentidx].data);
  22878. if (!parent[6])
  22879. parent[6] = [];
  22880. parent[6].push({
  22881. type: 2,
  22882. data: write_shallow([
  22883. [],
  22884. [{ type: 0, data: write_varint49(newref) }]
  22885. ])
  22886. });
  22887. mlist[3][parentidx].data = write_shallow(parent);
  22888. ai.messages[0].data = write_shallow(mlist);
  22889. });
  22890. }
  22891. store[n][0].data = write_TSP_Reference(newref);
  22892. });
  22893. var row_headers = parse_shallow(store[1][0].data);
  22894. {
  22895. (_b = row_headers[2]) == null ? void 0 : _b.forEach(function(tspref) {
  22896. var oldref = parse_TSP_Reference(tspref.data);
  22897. var newref = get_unique_msgid({ deps: [tmaref], location: deps[oldref].location, type: deps[oldref].type }, deps);
  22898. numbers_del_oref(tmaroot, oldref);
  22899. numbers_add_oref(tmaroot, newref);
  22900. remap[oldref] = newref;
  22901. var msg = numbers_iwa_find(cfb, deps, oldref);
  22902. msg.id = newref;
  22903. if (deps[oldref].location == deps[tmaref].location) {
  22904. arch.push(msg);
  22905. } else {
  22906. deps[newref].location = deps[oldref].location.replace(oldref.toString(), newref.toString());
  22907. if (deps[newref].location == deps[oldref].location)
  22908. deps[newref].location = deps[newref].location.replace(/\.iwa/, "-".concat(newref, ".iwa"));
  22909. CFB.utils.cfb_add(cfb, deps[newref].location, compress_iwa_file(write_iwa_file([msg])));
  22910. var newloc = deps[newref].location;
  22911. newloc = newloc.replace(/^Root Entry\//, "");
  22912. newloc = newloc.replace(/^Index\//, "").replace(/\.iwa$/, "");
  22913. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  22914. var mlist = parse_shallow(ai.messages[0].data);
  22915. mlist[3].push({ type: 2, data: write_shallow([
  22916. [],
  22917. [{ type: 0, data: write_varint49(newref) }],
  22918. [{ type: 2, data: stru8(newloc.replace(/-.*$/, "")) }],
  22919. [{ type: 2, data: stru8(newloc) }],
  22920. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  22921. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  22922. [],
  22923. [],
  22924. [],
  22925. [],
  22926. [{ type: 0, data: write_varint49(0) }],
  22927. [],
  22928. [{ type: 0, data: write_varint49(0) }]
  22929. ]) });
  22930. mlist[1] = [{ type: 0, data: write_varint49(Math.max(newref + 1, parse_varint49(mlist[1][0].data))) }];
  22931. var parentidx = mlist[3].findIndex(function(m) {
  22932. var _a2, _b2;
  22933. var mm = parse_shallow(m.data);
  22934. if ((_a2 = mm[3]) == null ? void 0 : _a2[0])
  22935. return u8str(mm[3][0].data) == loc;
  22936. if (((_b2 = mm[2]) == null ? void 0 : _b2[0]) && u8str(mm[2][0].data) == loc)
  22937. return true;
  22938. return false;
  22939. });
  22940. var parent = parse_shallow(mlist[3][parentidx].data);
  22941. if (!parent[6])
  22942. parent[6] = [];
  22943. parent[6].push({
  22944. type: 2,
  22945. data: write_shallow([
  22946. [],
  22947. [{ type: 0, data: write_varint49(newref) }]
  22948. ])
  22949. });
  22950. mlist[3][parentidx].data = write_shallow(parent);
  22951. ai.messages[0].data = write_shallow(mlist);
  22952. });
  22953. }
  22954. tspref.data = write_TSP_Reference(newref);
  22955. });
  22956. }
  22957. store[1][0].data = write_shallow(row_headers);
  22958. var tiles = parse_shallow(store[3][0].data);
  22959. {
  22960. tiles[1].forEach(function(t) {
  22961. var tst = parse_shallow(t.data);
  22962. var oldtileref = parse_TSP_Reference(tst[2][0].data);
  22963. var newtileref = remap[oldtileref];
  22964. if (!remap[oldtileref]) {
  22965. newtileref = get_unique_msgid({ deps: [tmaref], location: "", type: deps[oldtileref].type }, deps);
  22966. deps[newtileref].location = "Root Entry/Index/Tables/Tile-".concat(newtileref, ".iwa");
  22967. remap[oldtileref] = newtileref;
  22968. var oldtile = numbers_iwa_find(cfb, deps, oldtileref);
  22969. oldtile.id = newtileref;
  22970. numbers_del_oref(tmaroot, oldtileref);
  22971. numbers_add_oref(tmaroot, newtileref);
  22972. CFB.utils.cfb_add(cfb, "/Index/Tables/Tile-".concat(newtileref, ".iwa"), compress_iwa_file(write_iwa_file([oldtile])));
  22973. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  22974. var mlist = parse_shallow(ai.messages[0].data);
  22975. mlist[3].push({ type: 2, data: write_shallow([
  22976. [],
  22977. [{ type: 0, data: write_varint49(newtileref) }],
  22978. [{ type: 2, data: stru8("Tables/Tile") }],
  22979. [{ type: 2, data: stru8("Tables/Tile-".concat(newtileref)) }],
  22980. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  22981. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  22982. [],
  22983. [],
  22984. [],
  22985. [],
  22986. [{ type: 0, data: write_varint49(0) }],
  22987. [],
  22988. [{ type: 0, data: write_varint49(0) }]
  22989. ]) });
  22990. mlist[1] = [{ type: 0, data: write_varint49(Math.max(newtileref + 1, parse_varint49(mlist[1][0].data))) }];
  22991. var parentidx = mlist[3].findIndex(function(m) {
  22992. var _a2, _b2;
  22993. var mm = parse_shallow(m.data);
  22994. if ((_a2 = mm[3]) == null ? void 0 : _a2[0])
  22995. return u8str(mm[3][0].data) == loc;
  22996. if (((_b2 = mm[2]) == null ? void 0 : _b2[0]) && u8str(mm[2][0].data) == loc)
  22997. return true;
  22998. return false;
  22999. });
  23000. var parent = parse_shallow(mlist[3][parentidx].data);
  23001. if (!parent[6])
  23002. parent[6] = [];
  23003. parent[6].push({
  23004. type: 2,
  23005. data: write_shallow([
  23006. [],
  23007. [{ type: 0, data: write_varint49(newtileref) }]
  23008. ])
  23009. });
  23010. mlist[3][parentidx].data = write_shallow(parent);
  23011. ai.messages[0].data = write_shallow(mlist);
  23012. });
  23013. }
  23014. tst[2][0].data = write_TSP_Reference(newtileref);
  23015. t.data = write_shallow(tst);
  23016. });
  23017. }
  23018. store[3][0].data = write_shallow(tiles);
  23019. }
  23020. tma[4][0].data = write_shallow(store);
  23021. tmaroot.messages[0].data = write_shallow(tma);
  23022. });
  23023. }
  23024. function write_numbers_ws(cfb, deps, ws, wsname, sheetidx, rootref) {
  23025. var drawables = [];
  23026. numbers_iwa_doit(cfb, deps, rootref, function(docroot) {
  23027. var sheetref = parse_shallow(docroot.messages[0].data);
  23028. {
  23029. sheetref[1] = [{ type: 2, data: stru8(wsname) }];
  23030. drawables = mappa(sheetref[2], parse_TSP_Reference);
  23031. }
  23032. docroot.messages[0].data = write_shallow(sheetref);
  23033. });
  23034. var tia = numbers_iwa_find(cfb, deps, drawables[0]);
  23035. var tmaref = parse_TSP_Reference(parse_shallow(tia.messages[0].data)[2][0].data);
  23036. numbers_iwa_doit(cfb, deps, tmaref, function(docroot, x) {
  23037. return write_numbers_tma(cfb, deps, ws, docroot, x, tmaref);
  23038. });
  23039. }
  23040. var USE_WIDE_ROWS = true;
  23041. function write_numbers_tma(cfb, deps, ws, tmaroot, tmafile, tmaref) {
  23042. var range = decode_range(ws["!ref"]);
  23043. range.s.r = range.s.c = 0;
  23044. var trunc = false;
  23045. if (range.e.c > 999) {
  23046. trunc = true;
  23047. range.e.c = 999;
  23048. }
  23049. if (range.e.r > 999999) {
  23050. trunc = true;
  23051. range.e.r = 999999;
  23052. }
  23053. if (trunc)
  23054. console.error("Truncating to ".concat(encode_range(range)));
  23055. var data = sheet_to_json(ws, { range: range, header: 1 });
  23056. var SST = ["~Sh33tJ5~"];
  23057. var loc = deps[tmaref].location;
  23058. loc = loc.replace(/^Root Entry\//, "");
  23059. loc = loc.replace(/^Index\//, "").replace(/\.iwa$/, "");
  23060. var pb = parse_shallow(tmaroot.messages[0].data);
  23061. {
  23062. pb[6][0].data = write_varint49(range.e.r + 1);
  23063. pb[7][0].data = write_varint49(range.e.c + 1);
  23064. delete pb[46];
  23065. var store = parse_shallow(pb[4][0].data);
  23066. {
  23067. var row_header_ref = parse_TSP_Reference(parse_shallow(store[1][0].data)[2][0].data);
  23068. numbers_iwa_doit(cfb, deps, row_header_ref, function(rowhead, _x) {
  23069. var _a;
  23070. var base_bucket = parse_shallow(rowhead.messages[0].data);
  23071. if ((_a = base_bucket == null ? void 0 : base_bucket[2]) == null ? void 0 : _a[0])
  23072. for (var R2 = 0; R2 < data.length; ++R2) {
  23073. var _bucket = parse_shallow(base_bucket[2][0].data);
  23074. _bucket[1][0].data = write_varint49(R2);
  23075. _bucket[4][0].data = write_varint49(data[R2].length);
  23076. base_bucket[2][R2] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) };
  23077. }
  23078. rowhead.messages[0].data = write_shallow(base_bucket);
  23079. });
  23080. var col_header_ref = parse_TSP_Reference(store[2][0].data);
  23081. numbers_iwa_doit(cfb, deps, col_header_ref, function(colhead, _x) {
  23082. var base_bucket = parse_shallow(colhead.messages[0].data);
  23083. for (var C = 0; C <= range.e.c; ++C) {
  23084. var _bucket = parse_shallow(base_bucket[2][0].data);
  23085. _bucket[1][0].data = write_varint49(C);
  23086. _bucket[4][0].data = write_varint49(range.e.r + 1);
  23087. base_bucket[2][C] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) };
  23088. }
  23089. colhead.messages[0].data = write_shallow(base_bucket);
  23090. });
  23091. var rbtree = parse_shallow(store[9][0].data);
  23092. rbtree[1] = [];
  23093. var tilestore = parse_shallow(store[3][0].data);
  23094. {
  23095. var tstride = 256;
  23096. tilestore[2] = [{ type: 0, data: write_varint49(tstride) }];
  23097. var tileref = parse_TSP_Reference(parse_shallow(tilestore[1][0].data)[2][0].data);
  23098. var save_token = function() {
  23099. var metadata = numbers_iwa_find(cfb, deps, 2);
  23100. var mlist = parse_shallow(metadata.messages[0].data);
  23101. var mlst = mlist[3].filter(function(m) {
  23102. return parse_varint49(parse_shallow(m.data)[1][0].data) == tileref;
  23103. });
  23104. return (mlst == null ? void 0 : mlst.length) ? parse_varint49(parse_shallow(mlst[0].data)[12][0].data) : 0;
  23105. }();
  23106. {
  23107. CFB.utils.cfb_del(cfb, deps[tileref].location);
  23108. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  23109. var mlist = parse_shallow(ai.messages[0].data);
  23110. mlist[3] = mlist[3].filter(function(m) {
  23111. return parse_varint49(parse_shallow(m.data)[1][0].data) != tileref;
  23112. });
  23113. var parentidx = mlist[3].findIndex(function(m) {
  23114. var _a, _b;
  23115. var mm = parse_shallow(m.data);
  23116. if ((_a = mm[3]) == null ? void 0 : _a[0])
  23117. return u8str(mm[3][0].data) == loc;
  23118. if (((_b = mm[2]) == null ? void 0 : _b[0]) && u8str(mm[2][0].data) == loc)
  23119. return true;
  23120. return false;
  23121. });
  23122. var parent = parse_shallow(mlist[3][parentidx].data);
  23123. if (!parent[6])
  23124. parent[6] = [];
  23125. parent[6] = parent[6].filter(function(m) {
  23126. return parse_varint49(parse_shallow(m.data)[1][0].data) != tileref;
  23127. });
  23128. mlist[3][parentidx].data = write_shallow(parent);
  23129. ai.messages[0].data = write_shallow(mlist);
  23130. });
  23131. numbers_del_oref(tmaroot, tileref);
  23132. }
  23133. tilestore[1] = [];
  23134. var ntiles = Math.ceil((range.e.r + 1) / tstride);
  23135. for (var tidx = 0; tidx < ntiles; ++tidx) {
  23136. var newtileid = get_unique_msgid({
  23137. deps: [],
  23138. location: "",
  23139. type: 6002
  23140. }, deps);
  23141. deps[newtileid].location = "Root Entry/Index/Tables/Tile-".concat(newtileid, ".iwa");
  23142. var tiledata = [
  23143. [],
  23144. [{ type: 0, data: write_varint49(0) }],
  23145. [{ type: 0, data: write_varint49(Math.min(range.e.r + 1, (tidx + 1) * tstride)) }],
  23146. [{ type: 0, data: write_varint49(0) }],
  23147. [{ type: 0, data: write_varint49(Math.min((tidx + 1) * tstride, range.e.r + 1) - tidx * tstride) }],
  23148. [],
  23149. [{ type: 0, data: write_varint49(5) }],
  23150. [{ type: 0, data: write_varint49(1) }],
  23151. [{ type: 0, data: write_varint49(USE_WIDE_ROWS ? 1 : 0) }]
  23152. ];
  23153. for (var R = tidx * tstride; R <= Math.min(range.e.r, (tidx + 1) * tstride - 1); ++R) {
  23154. var tilerow = write_TST_TileRowInfo(data[R], SST, USE_WIDE_ROWS);
  23155. tilerow[1][0].data = write_varint49(R - tidx * tstride);
  23156. tiledata[5].push({ data: write_shallow(tilerow), type: 2 });
  23157. }
  23158. tilestore[1].push({ type: 2, data: write_shallow([
  23159. [],
  23160. [{ type: 0, data: write_varint49(tidx) }],
  23161. [{ type: 2, data: write_TSP_Reference(newtileid) }]
  23162. ]) });
  23163. var newtile = {
  23164. id: newtileid,
  23165. messages: [write_iwam(6002, write_shallow(tiledata))]
  23166. };
  23167. var tilecontent = compress_iwa_file(write_iwa_file([newtile]));
  23168. CFB.utils.cfb_add(cfb, "/Index/Tables/Tile-".concat(newtileid, ".iwa"), tilecontent);
  23169. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  23170. var mlist = parse_shallow(ai.messages[0].data);
  23171. mlist[3].push({ type: 2, data: write_shallow([
  23172. [],
  23173. [{ type: 0, data: write_varint49(newtileid) }],
  23174. [{ type: 2, data: stru8("Tables/Tile") }],
  23175. [{ type: 2, data: stru8("Tables/Tile-".concat(newtileid)) }],
  23176. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  23177. [{ type: 2, data: new Uint8Array([2, 0, 0]) }],
  23178. [],
  23179. [],
  23180. [],
  23181. [],
  23182. [{ type: 0, data: write_varint49(0) }],
  23183. [],
  23184. [{ type: 0, data: write_varint49(save_token) }]
  23185. ]) });
  23186. mlist[1] = [{ type: 0, data: write_varint49(Math.max(newtileid + 1, parse_varint49(mlist[1][0].data))) }];
  23187. var parentidx = mlist[3].findIndex(function(m) {
  23188. var _a, _b;
  23189. var mm = parse_shallow(m.data);
  23190. if ((_a = mm[3]) == null ? void 0 : _a[0])
  23191. return u8str(mm[3][0].data) == loc;
  23192. if (((_b = mm[2]) == null ? void 0 : _b[0]) && u8str(mm[2][0].data) == loc)
  23193. return true;
  23194. return false;
  23195. });
  23196. var parent = parse_shallow(mlist[3][parentidx].data);
  23197. if (!parent[6])
  23198. parent[6] = [];
  23199. parent[6].push({
  23200. type: 2,
  23201. data: write_shallow([
  23202. [],
  23203. [{ type: 0, data: write_varint49(newtileid) }]
  23204. ])
  23205. });
  23206. mlist[3][parentidx].data = write_shallow(parent);
  23207. ai.messages[0].data = write_shallow(mlist);
  23208. });
  23209. numbers_add_oref(tmaroot, newtileid);
  23210. rbtree[1].push({ type: 2, data: write_shallow([
  23211. [],
  23212. [{ type: 0, data: write_varint49(tidx * tstride) }],
  23213. [{ type: 0, data: write_varint49(tidx) }]
  23214. ]) });
  23215. }
  23216. }
  23217. store[3][0].data = write_shallow(tilestore);
  23218. store[9][0].data = write_shallow(rbtree);
  23219. store[10] = [{ type: 2, data: new Uint8Array([]) }];
  23220. if (ws["!merges"]) {
  23221. var mergeid = get_unique_msgid({
  23222. type: 6144,
  23223. deps: [tmaref],
  23224. location: deps[tmaref].location
  23225. }, deps);
  23226. tmafile.push({
  23227. id: mergeid,
  23228. messages: [write_iwam(6144, write_shallow([
  23229. [],
  23230. ws["!merges"].map(function(m) {
  23231. return { type: 2, data: write_shallow([
  23232. [],
  23233. [{ type: 2, data: write_shallow([
  23234. [],
  23235. [{ type: 5, data: new Uint8Array(new Uint16Array([m.s.r, m.s.c]).buffer) }]
  23236. ]) }],
  23237. [{ type: 2, data: write_shallow([
  23238. [],
  23239. [{ type: 5, data: new Uint8Array(new Uint16Array([m.e.r - m.s.r + 1, m.e.c - m.s.c + 1]).buffer) }]
  23240. ]) }]
  23241. ]) };
  23242. })
  23243. ]))]
  23244. });
  23245. store[13] = [{ type: 2, data: write_TSP_Reference(mergeid) }];
  23246. numbers_iwa_doit(cfb, deps, 2, function(ai) {
  23247. var mlist = parse_shallow(ai.messages[0].data);
  23248. var parentidx = mlist[3].findIndex(function(m) {
  23249. var _a, _b;
  23250. var mm = parse_shallow(m.data);
  23251. if ((_a = mm[3]) == null ? void 0 : _a[0])
  23252. return u8str(mm[3][0].data) == loc;
  23253. if (((_b = mm[2]) == null ? void 0 : _b[0]) && u8str(mm[2][0].data) == loc)
  23254. return true;
  23255. return false;
  23256. });
  23257. var parent = parse_shallow(mlist[3][parentidx].data);
  23258. if (!parent[6])
  23259. parent[6] = [];
  23260. parent[6].push({
  23261. type: 2,
  23262. data: write_shallow([
  23263. [],
  23264. [{ type: 0, data: write_varint49(mergeid) }]
  23265. ])
  23266. });
  23267. mlist[3][parentidx].data = write_shallow(parent);
  23268. ai.messages[0].data = write_shallow(mlist);
  23269. });
  23270. numbers_add_oref(tmaroot, mergeid);
  23271. } else
  23272. delete store[13];
  23273. var sstref = parse_TSP_Reference(store[4][0].data);
  23274. numbers_iwa_doit(cfb, deps, sstref, function(sstroot) {
  23275. var sstdata = parse_shallow(sstroot.messages[0].data);
  23276. {
  23277. sstdata[3] = [];
  23278. SST.forEach(function(str, i) {
  23279. if (i == 0)
  23280. return;
  23281. sstdata[3].push({ type: 2, data: write_shallow([
  23282. [],
  23283. [{ type: 0, data: write_varint49(i) }],
  23284. [{ type: 0, data: write_varint49(1) }],
  23285. [{ type: 2, data: stru8(str) }]
  23286. ]) });
  23287. });
  23288. }
  23289. sstroot.messages[0].data = write_shallow(sstdata);
  23290. });
  23291. }
  23292. pb[4][0].data = write_shallow(store);
  23293. }
  23294. tmaroot.messages[0].data = write_shallow(pb);
  23295. }
  23296. function fix_opts_func(defaults) {
  23297. return function fix_opts(opts) {
  23298. for(var i = 0; i != defaults.length; ++i) {
  23299. var d = defaults[i];
  23300. if(opts[d[0]] === undefined) opts[d[0]] = d[1];
  23301. if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
  23302. }
  23303. };
  23304. }
  23305. function fix_read_opts(opts) {
  23306. fix_opts_func([
  23307. ['cellNF', false], /* emit cell number format string as .z */
  23308. ['cellHTML', true], /* emit html string as .h */
  23309. ['cellFormula', true], /* emit formulae as .f */
  23310. ['cellStyles', false], /* emits style/theme as .s */
  23311. ['cellText', true], /* emit formatted text as .w */
  23312. ['cellDates', false], /* emit date cells with type `d` */
  23313. ['sheetStubs', false], /* emit empty cells */
  23314. ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
  23315. ['bookDeps', false], /* parse calculation chains */
  23316. ['bookSheets', false], /* only try to get sheet names (no Sheets) */
  23317. ['bookProps', false], /* only try to get properties (no Sheets) */
  23318. ['bookFiles', false], /* include raw file structure (keys, files, cfb) */
  23319. ['bookVBA', false], /* include vba raw data (vbaraw) */
  23320. ['password',''], /* password */
  23321. ['WTF', false] /* WTF mode (throws errors) */
  23322. ])(opts);
  23323. }
  23324. function fix_write_opts(opts) {
  23325. fix_opts_func([
  23326. ['cellDates', false], /* write date cells with type `d` */
  23327. ['bookSST', false], /* Generate Shared String Table */
  23328. ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
  23329. ['compression', false], /* Use file compression */
  23330. ['WTF', false] /* WTF mode (throws errors) */
  23331. ])(opts);
  23332. }
  23333. function get_sheet_type(n) {
  23334. if(RELS.WS.indexOf(n) > -1) return "sheet";
  23335. if(RELS.CS && n == RELS.CS) return "chart";
  23336. if(RELS.DS && n == RELS.DS) return "dialog";
  23337. if(RELS.MS && n == RELS.MS) return "macro";
  23338. return (n && n.length) ? n : "sheet";
  23339. }
  23340. function safe_parse_wbrels(wbrels, sheets) {
  23341. if(!wbrels) return 0;
  23342. try {
  23343. 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)]; });
  23344. } catch(e) { return null; }
  23345. return !wbrels || wbrels.length === 0 ? null : wbrels;
  23346. }
  23347. function safe_parse_sheet(zip, path, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles) {
  23348. try {
  23349. sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
  23350. var data = getzipdata(zip, path);
  23351. var _ws;
  23352. switch(stype) {
  23353. case 'sheet': _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  23354. case 'chart': _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
  23355. if(!_ws || !_ws['!drawel']) break;
  23356. var dfile = resolve_path(_ws['!drawel'].Target, path);
  23357. var drelsp = get_rels_path(dfile);
  23358. var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
  23359. var chartp = resolve_path(draw, dfile);
  23360. var crelsp = get_rels_path(chartp);
  23361. _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
  23362. break;
  23363. case 'macro': _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  23364. case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  23365. default: throw new Error("Unrecognized sheet type " + stype);
  23366. }
  23367. sheets[sheet] = _ws;
  23368. /* scan rels for comments and threaded comments */
  23369. var comments = [], tcomments = [];
  23370. if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
  23371. var dfile = "";
  23372. if(sheetRels[sheet][n].Type == RELS.CMNT) {
  23373. dfile = resolve_path(sheetRels[sheet][n].Target, path);
  23374. comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
  23375. if(!comments || !comments.length) return;
  23376. sheet_insert_comments(_ws, comments, false);
  23377. }
  23378. if(sheetRels[sheet][n].Type == RELS.TCMNT) {
  23379. dfile = resolve_path(sheetRels[sheet][n].Target, path);
  23380. tcomments = tcomments.concat(parse_tcmnt_xml(getzipdata(zip, dfile, true), opts));
  23381. }
  23382. });
  23383. if(tcomments && tcomments.length) sheet_insert_comments(_ws, tcomments, true, opts.people || []);
  23384. } catch(e) { if(opts.WTF) throw e; }
  23385. }
  23386. function strip_front_slash(x) { return x.charAt(0) == '/' ? x.slice(1) : x; }
  23387. function parse_zip(zip, opts) {
  23388. make_ssf();
  23389. opts = opts || {};
  23390. fix_read_opts(opts);
  23391. /* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
  23392. if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
  23393. /* UOC */
  23394. if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
  23395. /* Numbers */
  23396. if(safegetzipfile(zip, 'Index/Document.iwa')) {
  23397. if(typeof Uint8Array == "undefined") throw new Error('NUMBERS file parsing requires Uint8Array support');
  23398. if(typeof parse_numbers_iwa != "undefined") {
  23399. if(zip.FileIndex) return parse_numbers_iwa(zip, opts);
  23400. var _zip = CFB.utils.cfb_new();
  23401. zipentries(zip).forEach(function(e) { zip_add_file(_zip, e, getzipbin(zip, e)); });
  23402. return parse_numbers_iwa(_zip, opts);
  23403. }
  23404. throw new Error('Unsupported NUMBERS file');
  23405. }
  23406. if(!safegetzipfile(zip, '[Content_Types].xml')) {
  23407. if(safegetzipfile(zip, 'index.xml.gz')) throw new Error('Unsupported NUMBERS 08 file');
  23408. if(safegetzipfile(zip, 'index.xml')) throw new Error('Unsupported NUMBERS 09 file');
  23409. var index_zip = CFB.find(zip, 'Index.zip');
  23410. if(index_zip) {
  23411. opts = dup(opts);
  23412. delete opts.type;
  23413. if(typeof index_zip.content == "string") opts.type = "binary";
  23414. // TODO: Bun buffer bug
  23415. if(typeof Bun !== "undefined" && Buffer.isBuffer(index_zip.content)) return readSync(new Uint8Array(index_zip.content), opts);
  23416. return readSync(index_zip.content, opts);
  23417. }
  23418. throw new Error('Unsupported ZIP file');
  23419. }
  23420. var entries = zipentries(zip);
  23421. var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')));
  23422. var xlsb = false;
  23423. var sheets, binname;
  23424. if(dir.workbooks.length === 0) {
  23425. binname = "xl/workbook.xml";
  23426. if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
  23427. }
  23428. if(dir.workbooks.length === 0) {
  23429. binname = "xl/workbook.bin";
  23430. if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
  23431. dir.workbooks.push(binname);
  23432. xlsb = true;
  23433. }
  23434. if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  23435. var themes = ({});
  23436. var styles = ({});
  23437. if(!opts.bookSheets && !opts.bookProps) {
  23438. strs = [];
  23439. if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }
  23440. if(opts.cellStyles && dir.themes.length) themes = parse_theme_xml(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"", opts);
  23441. if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  23442. }
  23443. /*var externbooks = */dir.links.map(function(link) {
  23444. try {
  23445. var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
  23446. return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
  23447. } catch(e) {}
  23448. });
  23449. var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  23450. var props = {}, propdata = "";
  23451. if(dir.coreprops.length) {
  23452. propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
  23453. if(propdata) props = parse_core_props(propdata);
  23454. if(dir.extprops.length !== 0) {
  23455. propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
  23456. if(propdata) parse_ext_props(propdata, props, opts);
  23457. }
  23458. }
  23459. var custprops = {};
  23460. if(!opts.bookSheets || opts.bookProps) {
  23461. if (dir.custprops.length !== 0) {
  23462. propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
  23463. if(propdata) custprops = parse_cust_props(propdata, opts);
  23464. }
  23465. }
  23466. var out = ({});
  23467. if(opts.bookSheets || opts.bookProps) {
  23468. if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
  23469. else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
  23470. if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
  23471. if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
  23472. if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  23473. }
  23474. sheets = {};
  23475. var deps = {};
  23476. if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);
  23477. var i=0;
  23478. var sheetRels = ({});
  23479. var path, relsPath;
  23480. {
  23481. var wbsheets = wb.Sheets;
  23482. props.Worksheets = wbsheets.length;
  23483. props.SheetNames = [];
  23484. for(var j = 0; j != wbsheets.length; ++j) {
  23485. props.SheetNames[j] = wbsheets[j].name;
  23486. }
  23487. }
  23488. var wbext = xlsb ? "bin" : "xml";
  23489. var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  23490. var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
  23491. if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
  23492. var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile.replace(/_rels.*/, "s5s"));
  23493. if((dir.metadata || []).length >= 1) {
  23494. /* TODO: MDX and other types of metadata */
  23495. opts.xlmeta = parse_xlmeta(getzipdata(zip, strip_front_slash(dir.metadata[0])),dir.metadata[0],opts);
  23496. }
  23497. if((dir.people || []).length >= 1) {
  23498. opts.people = parse_people_xml(getzipdata(zip, strip_front_slash(dir.people[0])),opts);
  23499. }
  23500. if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  23501. /* Numbers iOS hack */
  23502. var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
  23503. wsloop: for(i = 0; i != props.Worksheets; ++i) {
  23504. var stype = "sheet";
  23505. if(wbrels && wbrels[i]) {
  23506. path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
  23507. if(!safegetzipfile(zip, path)) path = wbrels[i][1];
  23508. if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
  23509. stype = wbrels[i][2];
  23510. } else {
  23511. path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
  23512. path = path.replace(/sheet0\./,"sheet.");
  23513. }
  23514. relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
  23515. if(opts && opts.sheets != null) switch(typeof opts.sheets) {
  23516. case "number": if(i != opts.sheets) continue wsloop; break;
  23517. case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
  23518. default: if(Array.isArray && Array.isArray(opts.sheets)) {
  23519. var snjseen = false;
  23520. for(var snj = 0; snj != opts.sheets.length; ++snj) {
  23521. if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
  23522. if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
  23523. }
  23524. if(!snjseen) continue wsloop;
  23525. }
  23526. }
  23527. safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
  23528. }
  23529. out = ({
  23530. Directory: dir,
  23531. Workbook: wb,
  23532. Props: props,
  23533. Custprops: custprops,
  23534. Deps: deps,
  23535. Sheets: sheets,
  23536. SheetNames: props.SheetNames,
  23537. Strings: strs,
  23538. Styles: styles,
  23539. Themes: themes,
  23540. SSF: dup(table_fmt)
  23541. });
  23542. if(opts && opts.bookFiles) {
  23543. if(zip.files) {
  23544. out.keys = entries;
  23545. out.files = zip.files;
  23546. } else {
  23547. out.keys = [];
  23548. out.files = {};
  23549. zip.FullPaths.forEach(function(p, idx) {
  23550. p = p.replace(/^Root Entry[\/]/, "");
  23551. out.keys.push(p);
  23552. out.files[p] = zip.FileIndex[idx];
  23553. });
  23554. }
  23555. }
  23556. if(opts && opts.bookVBA) {
  23557. if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
  23558. else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
  23559. }
  23560. // TODO: pass back content types metdata for xlsm/xlsx resolution
  23561. out.bookType = xlsb ? "xlsb" : "xlsx";
  23562. return out;
  23563. }
  23564. /* [MS-OFFCRYPTO] 2.1.1 */
  23565. function parse_xlsxcfb(cfb, _opts) {
  23566. var opts = _opts || {};
  23567. var f = 'Workbook', data = CFB.find(cfb, f);
  23568. try {
  23569. f = '/!DataSpaces/Version';
  23570. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  23571. /*var version = */parse_DataSpaceVersionInfo(data.content);
  23572. /* 2.3.4.1 */
  23573. f = '/!DataSpaces/DataSpaceMap';
  23574. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  23575. var dsm = parse_DataSpaceMap(data.content);
  23576. 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")
  23577. throw new Error("ECMA-376 Encrypted file bad " + f);
  23578. /* 2.3.4.2 */
  23579. f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
  23580. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  23581. var seds = parse_DataSpaceDefinition(data.content);
  23582. if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
  23583. throw new Error("ECMA-376 Encrypted file bad " + f);
  23584. /* 2.3.4.3 */
  23585. f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
  23586. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  23587. /*var hdr = */parse_Primary(data.content);
  23588. } catch(e) {}
  23589. f = '/EncryptionInfo';
  23590. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  23591. var einfo = parse_EncryptionInfo(data.content);
  23592. /* 2.3.4.4 */
  23593. f = '/EncryptedPackage';
  23594. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  23595. /*global decrypt_agile */
  23596. if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  23597. /*global decrypt_std76 */
  23598. if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  23599. throw new Error("File is password-protected");
  23600. }
  23601. function write_zip_xlsb(wb, opts) {
  23602. if(wb && !wb.SSF) {
  23603. wb.SSF = dup(table_fmt);
  23604. }
  23605. if(wb && wb.SSF) {
  23606. make_ssf(); SSF_load_table(wb.SSF);
  23607. // $FlowIgnore
  23608. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  23609. opts.ssf = wb.SSF;
  23610. }
  23611. opts.rels = {}; opts.wbrels = {};
  23612. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  23613. if(browser_has_Map) opts.revStrings = new Map();
  23614. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  23615. var wbext = "bin";
  23616. var vbafmt = true;
  23617. var ct = new_ct();
  23618. fix_write_opts(opts = opts || {});
  23619. var zip = zip_new();
  23620. var f = "", rId = 0;
  23621. opts.cellXfs = [];
  23622. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  23623. if(!wb.Props) wb.Props = {};
  23624. f = "docProps/core.xml";
  23625. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  23626. ct.coreprops.push(f);
  23627. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  23628. f = "docProps/app.xml";
  23629. if(wb.Props && wb.Props.SheetNames){/* empty */}
  23630. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  23631. else {
  23632. var _sn = [];
  23633. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  23634. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  23635. wb.Props.SheetNames = _sn;
  23636. }
  23637. wb.Props.Worksheets = wb.Props.SheetNames.length;
  23638. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  23639. ct.extprops.push(f);
  23640. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  23641. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  23642. f = "docProps/custom.xml";
  23643. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  23644. ct.custprops.push(f);
  23645. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  23646. }
  23647. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  23648. var wsrels = {'!id':{}};
  23649. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  23650. var _type = (ws || {})["!type"] || "sheet";
  23651. switch(_type) {
  23652. case "chart":
  23653. /* falls through */
  23654. default:
  23655. f = "xl/worksheets/sheet" + rId + "." + wbext;
  23656. zip_add_file(zip, f, write_ws_bin(rId-1, opts, wb, wsrels));
  23657. ct.sheets.push(f);
  23658. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  23659. }
  23660. if(ws) {
  23661. var comments = ws['!comments'];
  23662. var need_vml = false;
  23663. var cf = "";
  23664. if(comments && comments.length > 0) {
  23665. cf = "xl/comments" + rId + "." + wbext;
  23666. zip_add_file(zip, cf, write_comments_bin(comments, opts));
  23667. ct.comments.push(cf);
  23668. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  23669. need_vml = true;
  23670. }
  23671. if(ws['!legacy']) {
  23672. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_vml(rId, ws['!comments']));
  23673. }
  23674. delete ws['!comments'];
  23675. delete ws['!legacy'];
  23676. }
  23677. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  23678. }
  23679. if(opts.Strings != null && opts.Strings.length > 0) {
  23680. f = "xl/sharedStrings." + wbext;
  23681. zip_add_file(zip, f, write_sst_bin(opts.Strings, opts));
  23682. ct.strs.push(f);
  23683. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  23684. }
  23685. f = "xl/workbook." + wbext;
  23686. zip_add_file(zip, f, write_wb_bin(wb, opts));
  23687. ct.workbooks.push(f);
  23688. add_rels(opts.rels, 1, f, RELS.WB);
  23689. /* TODO: something more intelligent with themes */
  23690. f = "xl/theme/theme1.xml";
  23691. var ww = write_theme(wb.Themes, opts);
  23692. zip_add_file(zip, f, ww);
  23693. ct.themes.push(f);
  23694. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  23695. /* TODO: something more intelligent with styles */
  23696. f = "xl/styles." + wbext;
  23697. zip_add_file(zip, f, write_sty_bin(wb, opts));
  23698. ct.styles.push(f);
  23699. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  23700. if(wb.vbaraw && vbafmt) {
  23701. f = "xl/vbaProject.bin";
  23702. zip_add_file(zip, f, wb.vbaraw);
  23703. ct.vba.push(f);
  23704. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  23705. }
  23706. f = "xl/metadata." + wbext;
  23707. zip_add_file(zip, f, write_xlmeta_bin());
  23708. ct.metadata.push(f);
  23709. add_rels(opts.wbrels, -1, "metadata." + wbext, RELS.XLMETA);
  23710. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  23711. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  23712. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  23713. delete opts.revssf; delete opts.ssf;
  23714. return zip;
  23715. }
  23716. function write_zip_xlsx(wb, opts) {
  23717. if(wb && !wb.SSF) {
  23718. wb.SSF = dup(table_fmt);
  23719. }
  23720. if(wb && wb.SSF) {
  23721. make_ssf(); SSF_load_table(wb.SSF);
  23722. // $FlowIgnore
  23723. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  23724. opts.ssf = wb.SSF;
  23725. }
  23726. opts.rels = {}; opts.wbrels = {};
  23727. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  23728. if(browser_has_Map) opts.revStrings = new Map();
  23729. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  23730. var wbext = "xml";
  23731. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  23732. var ct = new_ct();
  23733. fix_write_opts(opts = opts || {});
  23734. var zip = zip_new();
  23735. var f = "", rId = 0;
  23736. opts.cellXfs = [];
  23737. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  23738. if(!wb.Props) wb.Props = {};
  23739. f = "docProps/core.xml";
  23740. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  23741. ct.coreprops.push(f);
  23742. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  23743. f = "docProps/app.xml";
  23744. if(wb.Props && wb.Props.SheetNames){/* empty */}
  23745. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  23746. else {
  23747. var _sn = [];
  23748. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  23749. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  23750. wb.Props.SheetNames = _sn;
  23751. }
  23752. wb.Props.Worksheets = wb.Props.SheetNames.length;
  23753. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  23754. ct.extprops.push(f);
  23755. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  23756. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  23757. f = "docProps/custom.xml";
  23758. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  23759. ct.custprops.push(f);
  23760. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  23761. }
  23762. var people = ["SheetJ5"];
  23763. opts.tcid = 0;
  23764. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  23765. var wsrels = {'!id':{}};
  23766. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  23767. var _type = (ws || {})["!type"] || "sheet";
  23768. switch(_type) {
  23769. case "chart":
  23770. /* falls through */
  23771. default:
  23772. f = "xl/worksheets/sheet" + rId + "." + wbext;
  23773. zip_add_file(zip, f, write_ws_xml(rId-1, opts, wb, wsrels));
  23774. ct.sheets.push(f);
  23775. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  23776. }
  23777. if(ws) {
  23778. var comments = ws['!comments'];
  23779. var need_vml = false;
  23780. var cf = "";
  23781. if(comments && comments.length > 0) {
  23782. var needtc = false;
  23783. comments.forEach(function(carr) {
  23784. carr[1].forEach(function(c) { if(c.T == true) needtc = true; });
  23785. });
  23786. if(needtc) {
  23787. cf = "xl/threadedComments/threadedComment" + rId + ".xml";
  23788. zip_add_file(zip, cf, write_tcmnt_xml(comments, people, opts));
  23789. ct.threadedcomments.push(cf);
  23790. add_rels(wsrels, -1, "../threadedComments/threadedComment" + rId + ".xml", RELS.TCMNT);
  23791. }
  23792. cf = "xl/comments" + rId + "." + wbext;
  23793. zip_add_file(zip, cf, write_comments_xml(comments, opts));
  23794. ct.comments.push(cf);
  23795. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  23796. need_vml = true;
  23797. }
  23798. if(ws['!legacy']) {
  23799. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_vml(rId, ws['!comments']));
  23800. }
  23801. delete ws['!comments'];
  23802. delete ws['!legacy'];
  23803. }
  23804. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  23805. }
  23806. if(opts.Strings != null && opts.Strings.length > 0) {
  23807. f = "xl/sharedStrings." + wbext;
  23808. zip_add_file(zip, f, write_sst_xml(opts.Strings, opts));
  23809. ct.strs.push(f);
  23810. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  23811. }
  23812. f = "xl/workbook." + wbext;
  23813. zip_add_file(zip, f, write_wb_xml(wb, opts));
  23814. ct.workbooks.push(f);
  23815. add_rels(opts.rels, 1, f, RELS.WB);
  23816. /* TODO: something more intelligent with themes */
  23817. f = "xl/theme/theme1.xml";
  23818. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  23819. ct.themes.push(f);
  23820. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  23821. /* TODO: something more intelligent with styles */
  23822. f = "xl/styles." + wbext;
  23823. zip_add_file(zip, f, write_sty_xml(wb, opts));
  23824. ct.styles.push(f);
  23825. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  23826. if(wb.vbaraw && vbafmt) {
  23827. f = "xl/vbaProject.bin";
  23828. zip_add_file(zip, f, wb.vbaraw);
  23829. ct.vba.push(f);
  23830. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  23831. }
  23832. f = "xl/metadata." + wbext;
  23833. zip_add_file(zip, f, write_xlmeta_xml());
  23834. ct.metadata.push(f);
  23835. add_rels(opts.wbrels, -1, "metadata." + wbext, RELS.XLMETA);
  23836. if(people.length > 1) {
  23837. f = "xl/persons/person.xml";
  23838. zip_add_file(zip, f, write_people_xml(people, opts));
  23839. ct.people.push(f);
  23840. add_rels(opts.wbrels, -1, "persons/person.xml", RELS.PEOPLE);
  23841. }
  23842. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  23843. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  23844. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  23845. delete opts.revssf; delete opts.ssf;
  23846. return zip;
  23847. }
  23848. function firstbyte(f,o) {
  23849. var x = "";
  23850. switch((o||{}).type || "base64") {
  23851. case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  23852. case 'base64': x = Base64_decode(f.slice(0,12)); break;
  23853. case 'binary': x = f; break;
  23854. case 'array': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  23855. default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
  23856. }
  23857. 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)];
  23858. }
  23859. function read_cfb(cfb, opts) {
  23860. if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  23861. return parse_xlscfb(cfb, opts);
  23862. }
  23863. function read_zip(data, opts) {
  23864. var zip, d = data;
  23865. var o = opts||{};
  23866. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  23867. zip = zip_read(d, o);
  23868. return parse_zip(zip, o);
  23869. }
  23870. function read_plaintext(data, o) {
  23871. var i = 0;
  23872. main: while(i < data.length) switch(data.charCodeAt(i)) {
  23873. case 0x0A: case 0x0D: case 0x20: ++i; break;
  23874. case 0x3C: return parse_xlml(data.slice(i),o);
  23875. default: break main;
  23876. }
  23877. return PRN.to_workbook(data, o);
  23878. }
  23879. function read_plaintext_raw(data, o) {
  23880. var str = "", bytes = firstbyte(data, o);
  23881. switch(o.type) {
  23882. case 'base64': str = Base64_decode(data); break;
  23883. case 'binary': str = data; break;
  23884. case 'buffer': str = data.toString('binary'); break;
  23885. case 'array': str = cc2str(data); break;
  23886. default: throw new Error("Unrecognized type " + o.type);
  23887. }
  23888. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
  23889. o.type = "binary";
  23890. return read_plaintext(str, o);
  23891. }
  23892. function read_utf16(data, o) {
  23893. var d = data;
  23894. if(o.type == 'base64') d = Base64_decode(d);
  23895. d = typeof $cptable !== "undefined" ? $cptable.utils.decode(1200, d.slice(2), 'str') : utf16leread(d.slice(2));
  23896. o.type = "binary";
  23897. return read_plaintext(d, o);
  23898. }
  23899. function bstrify(data) {
  23900. return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
  23901. }
  23902. function read_prn(data, d, o, str) {
  23903. if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
  23904. return PRN.to_workbook(d, o);
  23905. }
  23906. function readSync(data, opts) {
  23907. reset_cp();
  23908. var o = opts||{};
  23909. if(o.codepage && typeof $cptable === "undefined") console.error("Codepage tables are not loaded. Non-ASCII characters may not give expected results");
  23910. if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o = dup(o), o.type = "array", o));
  23911. if(typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && !o.type) o.type = typeof Deno !== "undefined" ? "buffer" : "array";
  23912. var d = data, n = [0,0,0,0], str = false;
  23913. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  23914. _ssfopts = {};
  23915. if(o.dateNF) _ssfopts.dateNF = o.dateNF;
  23916. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  23917. if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); if(typeof Uint8Array !== 'undefined' && !has_buf) o.type = "array"; }
  23918. if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
  23919. if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
  23920. // $FlowIgnore
  23921. var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
  23922. // $FlowIgnore
  23923. if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
  23924. }
  23925. switch((n = firstbyte(d, o))[0]) {
  23926. 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;
  23927. case 0x09: if(n[1] <= 0x08) return parse_xlscfb(d, o); break;
  23928. case 0x3C: return parse_xlml(d, o);
  23929. case 0x49:
  23930. if(n[1] === 0x49 && n[2] === 0x2a && n[3] === 0x00) throw new Error("TIFF Image File is not a spreadsheet");
  23931. if(n[1] === 0x44) return read_wb_ID(d, o);
  23932. break;
  23933. case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
  23934. case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
  23935. case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
  23936. case 0xFF:
  23937. if(n[1] === 0xFE) { return read_utf16(d, o); }
  23938. else if(n[1] === 0x00 && n[2] === 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
  23939. break;
  23940. case 0x00:
  23941. if(n[1] === 0x00) {
  23942. if(n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
  23943. if(n[2] === 0x00 && (n[3] === 0x08 || n[3] === 0x09)) return WK_.to_workbook(d, o);
  23944. }
  23945. break;
  23946. case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
  23947. case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return rtf_to_workbook(d, o); break;
  23948. case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
  23949. case 0x89: if(n[1] === 0x50 && n[2] === 0x4E && n[3] === 0x47) throw new Error("PNG Image File is not a spreadsheet"); break;
  23950. case 0x08: if(n[1] === 0xE7) throw new Error("Unsupported Multiplan 1.x file!"); break;
  23951. case 0x0C:
  23952. if(n[1] === 0xEC) throw new Error("Unsupported Multiplan 2.x file!");
  23953. if(n[1] === 0xED) throw new Error("Unsupported Multiplan 3.x file!");
  23954. break;
  23955. }
  23956. if(DBF_SUPPORTED_VERSIONS.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
  23957. return read_prn(data, d, o, str);
  23958. }
  23959. function readFileSync(filename, opts) {
  23960. var o = opts||{}; o.type = 'file';
  23961. return readSync(filename, o);
  23962. }
  23963. function write_cfb_ctr(cfb, o) {
  23964. switch(o.type) {
  23965. case "base64": case "binary": break;
  23966. case "buffer": case "array": o.type = ""; break;
  23967. case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
  23968. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  23969. default: throw new Error("Unrecognized type " + o.type);
  23970. }
  23971. return CFB.write(cfb, o);
  23972. }
  23973. function write_zip(wb, opts) {
  23974. switch(opts.bookType) {
  23975. case "ods": return write_ods(wb, opts);
  23976. case "numbers": return write_numbers_iwa(wb, opts);
  23977. case "xlsb": return write_zip_xlsb(wb, opts);
  23978. default: return write_zip_xlsx(wb, opts);
  23979. }
  23980. }
  23981. function write_zip_type(wb, opts) {
  23982. var o = dup(opts||{});
  23983. var z = write_zip(wb, o);
  23984. return write_zip_denouement(z, o);
  23985. }
  23986. function write_zip_typeXLSX(wb, opts) {
  23987. var o = dup(opts||{});
  23988. var z = write_zip_xlsx(wb, o);
  23989. return write_zip_denouement(z, o);
  23990. }
  23991. function write_zip_denouement(z, o) {
  23992. var oopts = {};
  23993. var ftype = has_buf ? "nodebuffer" : (typeof Uint8Array !== "undefined" ? "array" : "string");
  23994. if(o.compression) oopts.compression = 'DEFLATE';
  23995. if(o.password) oopts.type = ftype;
  23996. else switch(o.type) {
  23997. case "base64": oopts.type = "base64"; break;
  23998. case "binary": oopts.type = "string"; break;
  23999. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  24000. case "buffer":
  24001. case "file": oopts.type = ftype; break;
  24002. default: throw new Error("Unrecognized type " + o.type);
  24003. }
  24004. var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: {"nodebuffer": "buffer", "string": "binary"}[oopts.type] || oopts.type, compression: !!o.compression}) : z.generate(oopts);
  24005. if(typeof Deno !== "undefined") {
  24006. if(typeof out == "string") {
  24007. if(o.type == "binary" || o.type == "base64") return out;
  24008. out = new Uint8Array(s2ab(out));
  24009. }
  24010. }
  24011. /*jshint -W083 */
  24012. if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
  24013. /*jshint +W083 */
  24014. if(o.type === "file") return write_dl(o.file, out);
  24015. return o.type == "string" ? utf8read(out) : out;
  24016. }
  24017. function write_cfb_type(wb, opts) {
  24018. var o = opts||{};
  24019. var cfb = write_xlscfb(wb, o);
  24020. return write_cfb_ctr(cfb, o);
  24021. }
  24022. function write_string_type(out, opts, bom) {
  24023. if(!bom) bom = "";
  24024. var o = bom + out;
  24025. switch(opts.type) {
  24026. case "base64": return Base64_encode(utf8write(o));
  24027. case "binary": return utf8write(o);
  24028. case "string": return out;
  24029. case "file": return write_dl(opts.file, o, 'utf8');
  24030. case "buffer": {
  24031. if(has_buf) return Buffer_from(o, 'utf8');
  24032. else if(typeof TextEncoder !== "undefined") return new TextEncoder().encode(o);
  24033. else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
  24034. }
  24035. }
  24036. throw new Error("Unrecognized type " + opts.type);
  24037. }
  24038. function write_stxt_type(out, opts) {
  24039. switch(opts.type) {
  24040. case "base64": return Base64_encode_pass(out);
  24041. case "binary": return out;
  24042. case "string": return out; /* override in sheet_to_txt */
  24043. case "file": return write_dl(opts.file, out, 'binary');
  24044. case "buffer": {
  24045. if(has_buf) return Buffer_from(out, 'binary');
  24046. else return out.split("").map(function(c) { return c.charCodeAt(0); });
  24047. }
  24048. }
  24049. throw new Error("Unrecognized type " + opts.type);
  24050. }
  24051. /* TODO: test consistency */
  24052. function write_binary_type(out, opts) {
  24053. switch(opts.type) {
  24054. case "string":
  24055. case "base64":
  24056. case "binary":
  24057. var bstr = "";
  24058. // $FlowIgnore
  24059. for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
  24060. return opts.type == 'base64' ? Base64_encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
  24061. case "file": return write_dl(opts.file, out);
  24062. case "buffer": return out;
  24063. default: throw new Error("Unrecognized type " + opts.type);
  24064. }
  24065. }
  24066. function writeSyncXLSX(wb, opts) {
  24067. reset_cp();
  24068. check_wb(wb);
  24069. var o = dup(opts||{});
  24070. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  24071. if(o.type == "array") { o.type = "binary"; var out = (writeSyncXLSX(wb, o)); o.type = "array"; return s2ab(out); }
  24072. return write_zip_typeXLSX(wb, o);
  24073. }
  24074. function writeSync(wb, opts) {
  24075. reset_cp();
  24076. check_wb(wb);
  24077. var o = dup(opts||{});
  24078. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  24079. if(o.type == "array") { o.type = "binary"; var out = (writeSync(wb, o)); o.type = "array"; return s2ab(out); }
  24080. var idx = 0;
  24081. if(o.sheet) {
  24082. if(typeof o.sheet == "number") idx = o.sheet;
  24083. else idx = wb.SheetNames.indexOf(o.sheet);
  24084. if(!wb.SheetNames[idx]) throw new Error("Sheet not found: " + o.sheet + " : " + (typeof o.sheet));
  24085. }
  24086. switch(o.bookType || 'xlsb') {
  24087. case 'xml':
  24088. case 'xlml': return write_string_type(write_xlml(wb, o), o);
  24089. case 'slk':
  24090. case 'sylk': return write_string_type(SYLK.from_sheet(wb.Sheets[wb.SheetNames[idx]], o, wb), o);
  24091. case 'htm':
  24092. case 'html': return write_string_type(sheet_to_html(wb.Sheets[wb.SheetNames[idx]], o), o);
  24093. case 'txt': return write_stxt_type(sheet_to_txt(wb.Sheets[wb.SheetNames[idx]], o), o);
  24094. case 'csv': return write_string_type(sheet_to_csv(wb.Sheets[wb.SheetNames[idx]], o), o, "\ufeff");
  24095. case 'dif': return write_string_type(DIF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  24096. case 'dbf': return write_binary_type(DBF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  24097. case 'prn': return write_string_type(PRN.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  24098. case 'rtf': return write_string_type(sheet_to_rtf(wb.Sheets[wb.SheetNames[idx]], o), o);
  24099. case 'eth': return write_string_type(ETH.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  24100. case 'fods': return write_string_type(write_ods(wb, o), o);
  24101. case 'wk1': return write_binary_type(WK_.sheet_to_wk1(wb.Sheets[wb.SheetNames[idx]], o), o);
  24102. case 'wk3': return write_binary_type(WK_.book_to_wk3(wb, o), o);
  24103. case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
  24104. case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
  24105. case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
  24106. case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
  24107. case 'biff8':
  24108. case 'xla':
  24109. case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
  24110. case 'xlsx':
  24111. case 'xlsm':
  24112. case 'xlam':
  24113. case 'xlsb':
  24114. case 'numbers':
  24115. case 'ods': return write_zip_type(wb, o);
  24116. default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
  24117. }
  24118. }
  24119. function resolve_book_type(o) {
  24120. if(o.bookType) return;
  24121. var _BT = {
  24122. "xls": "biff8",
  24123. "htm": "html",
  24124. "slk": "sylk",
  24125. "socialcalc": "eth",
  24126. "Sh33tJS": "WTF"
  24127. };
  24128. var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
  24129. if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
  24130. o.bookType = _BT[o.bookType] || o.bookType;
  24131. }
  24132. function writeFileSync(wb, filename, opts) {
  24133. var o = opts||{}; o.type = 'file';
  24134. o.file = filename;
  24135. resolve_book_type(o);
  24136. return writeSync(wb, o);
  24137. }
  24138. function writeFileSyncXLSX(wb, filename, opts) {
  24139. var o = opts||{}; o.type = 'file';
  24140. o.file = filename;
  24141. resolve_book_type(o);
  24142. return writeSyncXLSX(wb, o);
  24143. }
  24144. function writeFileAsync(filename, wb, opts, cb) {
  24145. var o = opts||{}; o.type = 'file';
  24146. o.file = filename;
  24147. resolve_book_type(o);
  24148. o.type = 'buffer';
  24149. var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts);
  24150. return _fs.writeFile(filename, writeSync(wb, o), _cb);
  24151. }
  24152. function make_json_row(sheet, r, R, cols, header, hdr, dense, o) {
  24153. var rr = encode_row(R);
  24154. var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
  24155. var isempty = true;
  24156. var row = (header === 1) ? [] : {};
  24157. if(header !== 1) {
  24158. if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
  24159. else row.__rowNum__ = R;
  24160. }
  24161. if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
  24162. var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  24163. if(val === undefined || val.t === undefined) {
  24164. if(defval === undefined) continue;
  24165. if(hdr[C] != null) { row[hdr[C]] = defval; }
  24166. continue;
  24167. }
  24168. var v = val.v;
  24169. switch(val.t){
  24170. case 'z': if(v == null) break; continue;
  24171. case 'e': v = (v == 0 ? null : void 0); break;
  24172. case 's': case 'd': case 'b': case 'n': break;
  24173. default: throw new Error('unrecognized type ' + val.t);
  24174. }
  24175. if(hdr[C] != null) {
  24176. if(v == null) {
  24177. if(val.t == "e" && v === null) row[hdr[C]] = null;
  24178. else if(defval !== undefined) row[hdr[C]] = defval;
  24179. else if(raw && v === null) row[hdr[C]] = null;
  24180. else continue;
  24181. } else {
  24182. row[hdr[C]] = raw && (val.t !== "n" || (val.t === "n" && o.rawNumbers !== false)) ? v : format_cell(val,v,o);
  24183. }
  24184. if(v != null) isempty = false;
  24185. }
  24186. }
  24187. return { row: row, isempty: isempty };
  24188. }
  24189. function sheet_to_json(sheet, opts) {
  24190. if(sheet == null || sheet["!ref"] == null) return [];
  24191. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  24192. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  24193. var o = opts || {};
  24194. var range = o.range != null ? o.range : sheet["!ref"];
  24195. if(o.header === 1) header = 1;
  24196. else if(o.header === "A") header = 2;
  24197. else if(Array.isArray(o.header)) header = 3;
  24198. else if(o.header == null) header = 0;
  24199. switch(typeof range) {
  24200. case 'string': r = safe_decode_range(range); break;
  24201. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  24202. default: r = range;
  24203. }
  24204. if(header > 0) offset = 0;
  24205. var rr = encode_row(r.s.r);
  24206. var cols = [];
  24207. var out = [];
  24208. var outi = 0, counter = 0;
  24209. var dense = Array.isArray(sheet);
  24210. var R = r.s.r, C = 0;
  24211. var header_cnt = {};
  24212. if(dense && !sheet[R]) sheet[R] = [];
  24213. var colinfo = o.skipHidden && sheet["!cols"] || [];
  24214. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  24215. for(C = r.s.c; C <= r.e.c; ++C) {
  24216. if(((colinfo[C]||{}).hidden)) continue;
  24217. cols[C] = encode_col(C);
  24218. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  24219. switch(header) {
  24220. case 1: hdr[C] = C - r.s.c; break;
  24221. case 2: hdr[C] = cols[C]; break;
  24222. case 3: hdr[C] = o.header[C - r.s.c]; break;
  24223. default:
  24224. if(val == null) val = {w: "__EMPTY", t: "s"};
  24225. vv = v = format_cell(val, null, o);
  24226. counter = header_cnt[v] || 0;
  24227. if(!counter) header_cnt[v] = 1;
  24228. else {
  24229. do { vv = v + "_" + (counter++); } while(header_cnt[vv]); header_cnt[v] = counter;
  24230. header_cnt[vv] = 1;
  24231. }
  24232. hdr[C] = vv;
  24233. }
  24234. }
  24235. for (R = r.s.r + offset; R <= r.e.r; ++R) {
  24236. if ((rowinfo[R]||{}).hidden) continue;
  24237. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  24238. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
  24239. }
  24240. out.length = outi;
  24241. return out;
  24242. }
  24243. var qreg = /"/g;
  24244. function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
  24245. var isempty = true;
  24246. var row = [], txt = "", rr = encode_row(R);
  24247. for(var C = r.s.c; C <= r.e.c; ++C) {
  24248. if (!cols[C]) continue;
  24249. var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
  24250. if(val == null) txt = "";
  24251. else if(val.v != null) {
  24252. isempty = false;
  24253. txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
  24254. 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; }
  24255. if(txt == "ID") txt = '"ID"';
  24256. } else if(val.f != null && !val.F) {
  24257. isempty = false;
  24258. txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
  24259. } else txt = "";
  24260. /* NOTE: Excel CSV does not support array formulae */
  24261. row.push(txt);
  24262. }
  24263. if(o.blankrows === false && isempty) return null;
  24264. return row.join(FS);
  24265. }
  24266. function sheet_to_csv(sheet, opts) {
  24267. var out = [];
  24268. var o = opts == null ? {} : opts;
  24269. if(sheet == null || sheet["!ref"] == null) return "";
  24270. var r = safe_decode_range(sheet["!ref"]);
  24271. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  24272. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  24273. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  24274. var row = "", cols = [];
  24275. o.dense = Array.isArray(sheet);
  24276. var colinfo = o.skipHidden && sheet["!cols"] || [];
  24277. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  24278. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  24279. var w = 0;
  24280. for(var R = r.s.r; R <= r.e.r; ++R) {
  24281. if ((rowinfo[R]||{}).hidden) continue;
  24282. row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
  24283. if(row == null) { continue; }
  24284. if(o.strip) row = row.replace(endregex,"");
  24285. if(row || (o.blankrows !== false)) out.push((w++ ? RS : "") + row);
  24286. }
  24287. delete o.dense;
  24288. return out.join("");
  24289. }
  24290. function sheet_to_txt(sheet, opts) {
  24291. if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
  24292. var s = sheet_to_csv(sheet, opts);
  24293. if(typeof $cptable == 'undefined' || opts.type == 'string') return s;
  24294. var o = $cptable.utils.encode(1200, s, 'str');
  24295. return String.fromCharCode(255) + String.fromCharCode(254) + o;
  24296. }
  24297. function sheet_to_formulae(sheet) {
  24298. var y = "", x, val="";
  24299. if(sheet == null || sheet["!ref"] == null) return [];
  24300. var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
  24301. var cmds = [];
  24302. var dense = Array.isArray(sheet);
  24303. for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
  24304. for(var R = r.s.r; R <= r.e.r; ++R) {
  24305. rr = encode_row(R);
  24306. for(C = r.s.c; C <= r.e.c; ++C) {
  24307. y = cols[C] + rr;
  24308. x = dense ? (sheet[R]||[])[C] : sheet[y];
  24309. val = "";
  24310. if(x === undefined) continue;
  24311. else if(x.F != null) {
  24312. y = x.F;
  24313. if(!x.f) continue;
  24314. val = x.f;
  24315. if(y.indexOf(":") == -1) y = y + ":" + y;
  24316. }
  24317. if(x.f != null) val = x.f;
  24318. else if(x.t == 'z') continue;
  24319. else if(x.t == 'n' && x.v != null) val = "" + x.v;
  24320. else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
  24321. else if(x.w !== undefined) val = "'" + x.w;
  24322. else if(x.v === undefined) continue;
  24323. else if(x.t == 's') val = "'" + x.v;
  24324. else val = ""+x.v;
  24325. cmds[cmds.length] = y + "=" + val;
  24326. }
  24327. }
  24328. return cmds;
  24329. }
  24330. function sheet_add_json(_ws, js, opts) {
  24331. var o = opts || {};
  24332. var dense = _ws ? Array.isArray(_ws) : o.dense;
  24333. if(DENSE != null && dense == null) dense = DENSE;
  24334. var offset = +!o.skipHeader;
  24335. var ws = _ws || (dense ? ([]) : ({}));
  24336. var _R = 0, _C = 0;
  24337. if(ws && o.origin != null) {
  24338. if(typeof o.origin == 'number') _R = o.origin;
  24339. else {
  24340. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  24341. _R = _origin.r; _C = _origin.c;
  24342. }
  24343. }
  24344. var range = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}});
  24345. if(ws['!ref']) {
  24346. var _range = safe_decode_range(ws['!ref']);
  24347. range.e.c = Math.max(range.e.c, _range.e.c);
  24348. range.e.r = Math.max(range.e.r, _range.e.r);
  24349. if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
  24350. } else {
  24351. if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
  24352. }
  24353. var hdr = o.header || [], C = 0;
  24354. var ROW = [];
  24355. js.forEach(function (JS, R) {
  24356. if(dense && !ws[_R + R + offset]) ws[_R + R + offset] = [];
  24357. if(dense) ROW = ws[_R + R + offset];
  24358. keys(JS).forEach(function(k) {
  24359. if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
  24360. var v = JS[k];
  24361. var t = 'z';
  24362. var z = "";
  24363. var ref = dense ? "" : encode_cell({c:_C + C,r:_R + R + offset});
  24364. var cell = dense ? ROW[_C + C] : ws[ref];
  24365. if(v && typeof v === 'object' && !(v instanceof Date)){
  24366. ws[ref] = v;
  24367. } else {
  24368. if(typeof v == 'number') t = 'n';
  24369. else if(typeof v == 'boolean') t = 'b';
  24370. else if(typeof v == 'string') t = 's';
  24371. else if(v instanceof Date) {
  24372. t = 'd';
  24373. if(!o.cellDates) { t = 'n'; v = datenum(v); }
  24374. z = (cell != null && cell.z && fmt_is_date(cell.z)) ? cell.z : (o.dateNF || table_fmt[14]);
  24375. }
  24376. else if(v === null && o.nullError) { t = 'e'; v = 0; }
  24377. if(!cell) {
  24378. if(!dense) ws[ref] = cell = ({t:t, v:v});
  24379. else ROW[_C + C] = cell = ({t:t, v:v});
  24380. } else {
  24381. cell.t = t; cell.v = v;
  24382. delete cell.w; delete cell.R;
  24383. if(z) cell.z = z;
  24384. }
  24385. if(z) cell.z = z;
  24386. }
  24387. });
  24388. });
  24389. range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
  24390. var __R = encode_row(_R);
  24391. if(dense && !ws[_R]) ws[_R] = [];
  24392. if(offset) for(C = 0; C < hdr.length; ++C) {
  24393. if(dense) ws[_R][C + _C] = {t:'s', v:hdr[C]};
  24394. else ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
  24395. }
  24396. ws['!ref'] = encode_range(range);
  24397. return ws;
  24398. }
  24399. function json_to_sheet(js, opts) { return sheet_add_json(null, js, opts); }
  24400. /* get cell, creating a stub if necessary */
  24401. function ws_get_cell_stub(ws, R, C) {
  24402. /* A1 cell address */
  24403. if(typeof R == "string") {
  24404. /* dense */
  24405. if(Array.isArray(ws)) {
  24406. var RC = decode_cell(R);
  24407. if(!ws[RC.r]) ws[RC.r] = [];
  24408. return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
  24409. }
  24410. return ws[R] || (ws[R] = {t:'z'});
  24411. }
  24412. /* cell address object */
  24413. if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
  24414. /* R and C are 0-based indices */
  24415. return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
  24416. }
  24417. /* find sheet index for given name / validate index */
  24418. function wb_sheet_idx(wb, sh) {
  24419. if(typeof sh == "number") {
  24420. if(sh >= 0 && wb.SheetNames.length > sh) return sh;
  24421. throw new Error("Cannot find sheet # " + sh);
  24422. } else if(typeof sh == "string") {
  24423. var idx = wb.SheetNames.indexOf(sh);
  24424. if(idx > -1) return idx;
  24425. throw new Error("Cannot find sheet name |" + sh + "|");
  24426. } else throw new Error("Cannot find sheet |" + sh + "|");
  24427. }
  24428. /* simple blank workbook object */
  24429. function book_new() {
  24430. return { SheetNames: [], Sheets: {} };
  24431. }
  24432. /* add a worksheet to the end of a given workbook */
  24433. function book_append_sheet(wb, ws, name, roll) {
  24434. var i = 1;
  24435. if(!name) for(; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
  24436. if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
  24437. if(roll && wb.SheetNames.indexOf(name) >= 0) {
  24438. var m = name.match(/(^.*?)(\d+)$/);
  24439. i = m && +m[2] || 0;
  24440. var root = m && m[1] || name;
  24441. for(++i; i <= 0xFFFF; ++i) if(wb.SheetNames.indexOf(name = root + i) == -1) break;
  24442. }
  24443. check_ws_name(name);
  24444. if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  24445. wb.SheetNames.push(name);
  24446. wb.Sheets[name] = ws;
  24447. return name;
  24448. }
  24449. /* set sheet visibility (visible/hidden/very hidden) */
  24450. function book_set_sheet_visibility(wb, sh, vis) {
  24451. if(!wb.Workbook) wb.Workbook = {};
  24452. if(!wb.Workbook.Sheets) wb.Workbook.Sheets = [];
  24453. var idx = wb_sheet_idx(wb, sh);
  24454. // $FlowIgnore
  24455. if(!wb.Workbook.Sheets[idx]) wb.Workbook.Sheets[idx] = {};
  24456. switch(vis) {
  24457. case 0: case 1: case 2: break;
  24458. default: throw new Error("Bad sheet visibility setting " + vis);
  24459. }
  24460. // $FlowIgnore
  24461. wb.Workbook.Sheets[idx].Hidden = vis;
  24462. }
  24463. /* set number format */
  24464. function cell_set_number_format(cell, fmt) {
  24465. cell.z = fmt;
  24466. return cell;
  24467. }
  24468. /* set cell hyperlink */
  24469. function cell_set_hyperlink(cell, target, tooltip) {
  24470. if(!target) {
  24471. delete cell.l;
  24472. } else {
  24473. cell.l = ({ Target: target });
  24474. if(tooltip) cell.l.Tooltip = tooltip;
  24475. }
  24476. return cell;
  24477. }
  24478. function cell_set_internal_link(cell, range, tooltip) { return cell_set_hyperlink(cell, "#" + range, tooltip); }
  24479. /* add to cell comments */
  24480. function cell_add_comment(cell, text, author) {
  24481. if(!cell.c) cell.c = [];
  24482. cell.c.push({t:text, a:author||"SheetJS"});
  24483. }
  24484. /* set array formula and flush related cells */
  24485. function sheet_set_array_formula(ws, range, formula, dynamic) {
  24486. var rng = typeof range != "string" ? range : safe_decode_range(range);
  24487. var rngstr = typeof range == "string" ? range : encode_range(range);
  24488. for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
  24489. var cell = ws_get_cell_stub(ws, R, C);
  24490. cell.t = 'n';
  24491. cell.F = rngstr;
  24492. delete cell.v;
  24493. if(R == rng.s.r && C == rng.s.c) {
  24494. cell.f = formula;
  24495. if(dynamic) cell.D = true;
  24496. }
  24497. }
  24498. var wsr = decode_range(ws["!ref"]);
  24499. if(wsr.s.r > rng.s.r) wsr.s.r = rng.s.r;
  24500. if(wsr.s.c > rng.s.c) wsr.s.c = rng.s.c;
  24501. if(wsr.e.r < rng.e.r) wsr.e.r = rng.e.r;
  24502. if(wsr.e.c < rng.e.c) wsr.e.c = rng.e.c;
  24503. ws["!ref"] = encode_range(wsr);
  24504. return ws;
  24505. }
  24506. var utils = {
  24507. encode_col: encode_col,
  24508. encode_row: encode_row,
  24509. encode_cell: encode_cell,
  24510. encode_range: encode_range,
  24511. decode_col: decode_col,
  24512. decode_row: decode_row,
  24513. split_cell: split_cell,
  24514. decode_cell: decode_cell,
  24515. decode_range: decode_range,
  24516. format_cell: format_cell,
  24517. sheet_add_aoa: sheet_add_aoa,
  24518. sheet_add_json: sheet_add_json,
  24519. sheet_add_dom: sheet_add_dom,
  24520. aoa_to_sheet: aoa_to_sheet,
  24521. json_to_sheet: json_to_sheet,
  24522. table_to_sheet: parse_dom_table,
  24523. table_to_book: table_to_book,
  24524. sheet_to_csv: sheet_to_csv,
  24525. sheet_to_txt: sheet_to_txt,
  24526. sheet_to_json: sheet_to_json,
  24527. sheet_to_html: sheet_to_html,
  24528. sheet_to_formulae: sheet_to_formulae,
  24529. sheet_to_row_object_array: sheet_to_json,
  24530. sheet_get_cell: ws_get_cell_stub,
  24531. book_new: book_new,
  24532. book_append_sheet: book_append_sheet,
  24533. book_set_sheet_visibility: book_set_sheet_visibility,
  24534. cell_set_number_format: cell_set_number_format,
  24535. cell_set_hyperlink: cell_set_hyperlink,
  24536. cell_set_internal_link: cell_set_internal_link,
  24537. cell_add_comment: cell_add_comment,
  24538. sheet_set_array_formula: sheet_set_array_formula,
  24539. consts: {
  24540. SHEET_VISIBLE: 0,
  24541. SHEET_HIDDEN: 1,
  24542. SHEET_VERY_HIDDEN: 2
  24543. }
  24544. };
  24545. var _Readable;
  24546. function set_readable(R) { _Readable = R; }
  24547. function write_csv_stream(sheet, opts) {
  24548. var stream = _Readable();
  24549. var o = opts == null ? {} : opts;
  24550. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  24551. var r = safe_decode_range(sheet["!ref"]);
  24552. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  24553. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  24554. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  24555. var row = "", cols = [];
  24556. o.dense = Array.isArray(sheet);
  24557. var colinfo = o.skipHidden && sheet["!cols"] || [];
  24558. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  24559. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  24560. var R = r.s.r;
  24561. var BOM = false, w = 0;
  24562. stream._read = function() {
  24563. if(!BOM) { BOM = true; return stream.push("\uFEFF"); }
  24564. while(R <= r.e.r) {
  24565. ++R;
  24566. if ((rowinfo[R-1]||{}).hidden) continue;
  24567. row = make_csv_row(sheet, r, R-1, cols, fs, rs, FS, o);
  24568. if(row != null) {
  24569. if(o.strip) row = row.replace(endregex,"");
  24570. if(row || (o.blankrows !== false)) return stream.push((w++ ? RS : "") + row);
  24571. }
  24572. }
  24573. return stream.push(null);
  24574. };
  24575. return stream;
  24576. }
  24577. function write_html_stream(ws, opts) {
  24578. var stream = _Readable();
  24579. var o = opts || {};
  24580. var header = o.header != null ? o.header : HTML_BEGIN;
  24581. var footer = o.footer != null ? o.footer : HTML_END;
  24582. stream.push(header);
  24583. var r = decode_range(ws['!ref']);
  24584. o.dense = Array.isArray(ws);
  24585. stream.push(make_html_preamble(ws, r, o));
  24586. var R = r.s.r;
  24587. var end = false;
  24588. stream._read = function() {
  24589. if(R > r.e.r) {
  24590. if(!end) { end = true; stream.push("</table>" + footer); }
  24591. return stream.push(null);
  24592. }
  24593. while(R <= r.e.r) {
  24594. stream.push(make_html_row(ws, r, R, o));
  24595. ++R;
  24596. break;
  24597. }
  24598. };
  24599. return stream;
  24600. }
  24601. function write_json_stream(sheet, opts) {
  24602. var stream = _Readable({objectMode:true});
  24603. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  24604. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  24605. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  24606. var o = opts || {};
  24607. var range = o.range != null ? o.range : sheet["!ref"];
  24608. if(o.header === 1) header = 1;
  24609. else if(o.header === "A") header = 2;
  24610. else if(Array.isArray(o.header)) header = 3;
  24611. switch(typeof range) {
  24612. case 'string': r = safe_decode_range(range); break;
  24613. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  24614. default: r = range;
  24615. }
  24616. if(header > 0) offset = 0;
  24617. var rr = encode_row(r.s.r);
  24618. var cols = [];
  24619. var counter = 0;
  24620. var dense = Array.isArray(sheet);
  24621. var R = r.s.r, C = 0;
  24622. var header_cnt = {};
  24623. if(dense && !sheet[R]) sheet[R] = [];
  24624. var colinfo = o.skipHidden && sheet["!cols"] || [];
  24625. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  24626. for(C = r.s.c; C <= r.e.c; ++C) {
  24627. if(((colinfo[C]||{}).hidden)) continue;
  24628. cols[C] = encode_col(C);
  24629. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  24630. switch(header) {
  24631. case 1: hdr[C] = C - r.s.c; break;
  24632. case 2: hdr[C] = cols[C]; break;
  24633. case 3: hdr[C] = o.header[C - r.s.c]; break;
  24634. default:
  24635. if(val == null) val = {w: "__EMPTY", t: "s"};
  24636. vv = v = format_cell(val, null, o);
  24637. counter = header_cnt[v] || 0;
  24638. if(!counter) header_cnt[v] = 1;
  24639. else {
  24640. do { vv = v + "_" + (counter++); } while(header_cnt[vv]); header_cnt[v] = counter;
  24641. header_cnt[vv] = 1;
  24642. }
  24643. hdr[C] = vv;
  24644. }
  24645. }
  24646. R = r.s.r + offset;
  24647. stream._read = function() {
  24648. while(R <= r.e.r) {
  24649. if ((rowinfo[R-1]||{}).hidden) continue;
  24650. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  24651. ++R;
  24652. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) {
  24653. stream.push(row.row);
  24654. return;
  24655. }
  24656. }
  24657. return stream.push(null);
  24658. };
  24659. return stream;
  24660. }
  24661. var __stream = {
  24662. to_json: write_json_stream,
  24663. to_html: write_html_stream,
  24664. to_csv: write_csv_stream,
  24665. set_readable: set_readable
  24666. };
  24667. if(typeof parse_xlscfb !== "undefined") XLSX.parse_xlscfb = parse_xlscfb;
  24668. XLSX.parse_zip = parse_zip;
  24669. XLSX.read = readSync; //xlsread
  24670. XLSX.readFile = readFileSync; //readFile
  24671. XLSX.readFileSync = readFileSync;
  24672. XLSX.write = writeSync;
  24673. XLSX.writeFile = writeFileSync;
  24674. XLSX.writeFileSync = writeFileSync;
  24675. XLSX.writeFileAsync = writeFileAsync;
  24676. XLSX.utils = utils;
  24677. XLSX.writeXLSX = writeSyncXLSX;
  24678. XLSX.writeFileXLSX = writeFileSyncXLSX;
  24679. XLSX.SSF = SSF;
  24680. if(typeof __stream !== "undefined") XLSX.stream = __stream;
  24681. if(typeof CFB !== "undefined") XLSX.CFB = CFB;
  24682. if(typeof require !== "undefined") {
  24683. var strmod = require('stream');
  24684. if((strmod||{}).Readable) set_readable(strmod.Readable);
  24685. try { _fs = require('fs'); } catch(e) {}
  24686. }
  24687. }
  24688. /*global define */
  24689. if(typeof exports !== 'undefined') make_xlsx_lib(exports);
  24690. else if(typeof module !== 'undefined' && module.exports) make_xlsx_lib(module.exports);
  24691. else if(typeof define === 'function' && define.amd) define('xlsx', function() { if(!XLSX.version) make_xlsx_lib(XLSX); return XLSX; });
  24692. else make_xlsx_lib(XLSX);
  24693. /* NOTE: the following extra line is needed for "Lightning Locker Service" */
  24694. if(typeof window !== 'undefined' && !window.XLSX) try { window.XLSX = XLSX; } catch(e) {}