xlsx.extendscript.js 823 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643
  1. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  2. /*! shim.js (C) 2013-present SheetJS -- http://sheetjs.com */
  3. /* ES3/5 Compatibility shims and other utilities for older browsers. */
  4. // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
  5. if(!Object.keys) Object.keys = (function() {
  6. var hasOwnProperty = Object.prototype.hasOwnProperty,
  7. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  8. dontEnums = [
  9. 'toString',
  10. 'toLocaleString',
  11. 'valueOf',
  12. 'hasOwnProperty',
  13. 'isPrototypeOf',
  14. 'propertyIsEnumerable',
  15. 'constructor'
  16. ],
  17. dontEnumsLength = dontEnums.length;
  18. return function(obj) {
  19. if(typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
  20. var result = [];
  21. for(var prop in obj) if(hasOwnProperty.call(obj, prop)) result.push(prop);
  22. if(hasDontEnumBug)
  23. for(var i=0; i < dontEnumsLength; ++i)
  24. if(hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  25. return result;
  26. };
  27. })();
  28. if(!String.prototype.trim) String.prototype.trim = function() {
  29. var s = this.replace(/^\s+/, '');
  30. for(var i = s.length - 1; i >=0 ; --i) if(!s.charAt(i).match(/^\s/)) return s.slice(0,i+1);
  31. return "";
  32. };
  33. if(!Array.prototype.forEach) Array.prototype.forEach = function(cb) {
  34. var len = (this.length>>>0), self = (arguments[1]||void 0);
  35. for(var i=0; i<len; ++i) if(i in this) self ? cb.call(self, this[i], i, this) : cb(this[i], i, this);
  36. };
  37. if(!Array.prototype.map) Array.prototype.map = function(cb) {
  38. var len = (this.length>>>0), self = (arguments[1]||void 0), A = new Array(len);
  39. for(var i=0; i<len; ++i) if(i in this) A[i] = self ? cb.call(self, this[i], i, this) : cb(this[i], i, this);
  40. return A;
  41. };
  42. if(!Array.prototype.indexOf) Array.prototype.indexOf = function(needle) {
  43. var len = (this.length>>>0), i = ((arguments[1]|0)||0);
  44. for(i<0 && (i+=len)<0 && (i=0); i<len; ++i) if(this[i] === needle) return i;
  45. return -1;
  46. };
  47. if(!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(needle) {
  48. var len = (this.length>>>0), i = len - 1;
  49. for(; i>=0; --i) if(this[i] === needle) return i;
  50. return -1;
  51. };
  52. if(!Array.isArray) Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; };
  53. if(!Date.prototype.toISOString) Date.prototype.toISOString = (function() {
  54. function p(n,i) { return ('0000000' + n).slice(-(i||2)); }
  55. return function _toISOString() {
  56. var y = this.getUTCFullYear(), yr = "";
  57. if(y>9999) yr = '+' + p( y, 6);
  58. else if(y<0) yr = '-' + p(-y, 6);
  59. else yr = p( y, 4);
  60. return [
  61. yr, p(this.getUTCMonth()+1), p(this.getUTCDate())
  62. ].join('-') + 'T' + [
  63. p(this.getUTCHours()), p(this.getUTCMinutes()), p(this.getUTCSeconds())
  64. ].join(':') + '.' + p(this.getUTCMilliseconds(),3) + 'Z';
  65. };
  66. }());
  67. if(typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) ArrayBuffer.prototype.slice = function(start, end) {
  68. if(start == null) start = 0;
  69. if(start < 0) { start += this.byteLength; if(start < 0) start = 0; }
  70. if(start >= this.byteLength) return new Uint8Array(0);
  71. if(end == null) end = this.byteLength;
  72. if(end < 0) { end += this.byteLength; if(end < 0) end = 0; }
  73. if(end > this.byteLength) end = this.byteLength;
  74. if(start > end) return new Uint8Array(0);
  75. var out = new ArrayBuffer(end - start);
  76. var view = new Uint8Array(out);
  77. var data = new Uint8Array(this, start, end - start)
  78. /* IE10 should have Uint8Array#set */
  79. if(view.set) view.set(data); else while(start <= --end) view[end - start] = data[end];
  80. return out;
  81. };
  82. if(typeof Uint8Array !== 'undefined' && !Uint8Array.prototype.slice) Uint8Array.prototype.slice = function(start, end) {
  83. if(start == null) start = 0;
  84. if(start < 0) { start += this.length; if(start < 0) start = 0; }
  85. if(start >= this.length) return new Uint8Array(0);
  86. if(end == null) end = this.length;
  87. if(end < 0) { end += this.length; if(end < 0) end = 0; }
  88. if(end > this.length) end = this.length;
  89. if(start > end) return new Uint8Array(0);
  90. var out = new Uint8Array(end - start);
  91. while(start <= --end) out[end - start] = this[end];
  92. return out;
  93. };
  94. // VBScript + ActiveX fallback for IE5+
  95. var IE_SaveFile = (function() { try {
  96. if(typeof IE_SaveFile_Impl == "undefined") document.write([
  97. '<script type="text/vbscript" language="vbscript">',
  98. 'IE_GetProfileAndPath_Key = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\"',
  99. 'Function IE_GetProfileAndPath(key): Set wshell = CreateObject("WScript.Shell"): IE_GetProfileAndPath = wshell.RegRead(IE_GetProfileAndPath_Key & key): IE_GetProfileAndPath = wshell.ExpandEnvironmentStrings("%USERPROFILE%") & "!" & IE_GetProfileAndPath: End Function',
  100. 'Function IE_SaveFile_Impl(FileName, payload): Dim data, plen, i, bit: data = CStr(payload): plen = Len(data): Set fso = CreateObject("Scripting.FileSystemObject"): fso.CreateTextFile FileName, True: Set f = fso.GetFile(FileName): Set stream = f.OpenAsTextStream(2, 0): For i = 1 To plen Step 3: bit = Mid(data, i, 2): stream.write Chr(CLng("&h" & bit)): Next: stream.Close: IE_SaveFile_Impl = True: End Function',
  101. '|/script>'.replace("|","<")
  102. ].join("\r\n"));
  103. if(typeof IE_SaveFile_Impl == "undefined") return void 0;
  104. var IE_GetPath = (function() {
  105. var DDP1 = "";
  106. try { DDP1 = IE_GetProfileAndPath("{374DE290-123F-4565-9164-39C4925E467B}"); } catch(e) { try { DDP1 = IE_GetProfileAndPath("Personal"); } catch(e) { try { DDP1 = IE_GetProfileAndPath("Desktop"); } catch(e) { throw e; }}}
  107. var o = DDP1.split("!");
  108. DDP = o[1].replace("%USERPROFILE%", o[0]);
  109. return function(path) { return DDP + "\\" + path; };
  110. })();
  111. function fix_data(data) {
  112. var out = [];
  113. var T = typeof data == "string";
  114. for(var i = 0; i < data.length; ++i) out.push(("00"+(T ? data.charCodeAt(i) : data[i]).toString(16)).slice(-2));
  115. var o = out.join("|");
  116. return o;
  117. }
  118. return function(data, filename) { return IE_SaveFile_Impl(IE_GetPath(filename), fix_data(data)); };
  119. } catch(e) { return void 0; }})();
  120. var IE_LoadFile = (function() { try {
  121. if(typeof IE_LoadFile_Impl == "undefined") document.write([
  122. '<script type="text/vbscript" language="vbscript">',
  123. 'Function IE_LoadFile_Impl(FileName): Dim out(), plen, i, cc: Set fso = CreateObject("Scripting.FileSystemObject"): Set f = fso.GetFile(FileName): Set stream = f.OpenAsTextStream(1, 0): plen = f.Size: ReDim out(plen): For i = 1 To plen Step 1: cc = Hex(Asc(stream.read(1))): If Len(cc) < 2 Then: cc = "0" & cc: End If: out(i) = cc: Next: IE_LoadFile_Impl = Join(out,""): End Function',
  124. '|/script>'.replace("|","<")
  125. ].join("\r\n"));
  126. if(typeof IE_LoadFile_Impl == "undefined") return void 0;
  127. function fix_data(data) {
  128. var out = [];
  129. for(var i = 0; i < data.length; i+=2) out.push(String.fromCharCode(parseInt(data.slice(i, i+2), 16)));
  130. var o = out.join("");
  131. return o;
  132. }
  133. return function(filename) { return fix_data(IE_LoadFile_Impl(filename)); };
  134. } catch(e) { return void 0; }})();
  135. // getComputedStyle polyfill from https://gist.github.com/8HNHoFtE/5891086
  136. if(typeof window !== 'undefined' && typeof window.getComputedStyle !== 'function') {
  137. window.getComputedStyle = function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}
  138. }
  139. var DO_NOT_EXPORT_CODEPAGE = true;
  140. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  141. /* vim: set ts=2: */
  142. /*exported XLSX */
  143. /*global exports, module, require:false, process:false, Buffer:false, ArrayBuffer:false, DataView:false, Deno:false */
  144. var XLSX = {};
  145. function make_xlsx_lib(XLSX){
  146. XLSX.version = '0.18.5';
  147. var current_codepage = 1200, current_ansi = 1252;
  148. /*global cptable:true, window */
  149. var $cptable;
  150. if(typeof cptable !== 'undefined') $cptable = cptable;
  151. else if(typeof module !== "undefined" && typeof require !== 'undefined') {
  152. $cptable = undefined;
  153. }
  154. var VALID_ANSI = [ 874, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 10000 ];
  155. /* ECMA-376 Part I 18.4.1 charset to codepage mapping */
  156. var CS2CP = ({
  157. 0: 1252, /* ANSI */
  158. 1: 65001, /* DEFAULT */
  159. 2: 65001, /* SYMBOL */
  160. 77: 10000, /* MAC */
  161. 128: 932, /* SHIFTJIS */
  162. 129: 949, /* HANGUL */
  163. 130: 1361, /* JOHAB */
  164. 134: 936, /* GB2312 */
  165. 136: 950, /* CHINESEBIG5 */
  166. 161: 1253, /* GREEK */
  167. 162: 1254, /* TURKISH */
  168. 163: 1258, /* VIETNAMESE */
  169. 177: 1255, /* HEBREW */
  170. 178: 1256, /* ARABIC */
  171. 186: 1257, /* BALTIC */
  172. 204: 1251, /* RUSSIAN */
  173. 222: 874, /* THAI */
  174. 238: 1250, /* EASTEUROPE */
  175. 255: 1252, /* OEM */
  176. 69: 6969 /* MISC */
  177. });
  178. var set_ansi = function(cp) { if(VALID_ANSI.indexOf(cp) == -1) return; current_ansi = CS2CP[0] = cp; };
  179. function reset_ansi() { set_ansi(1252); }
  180. var set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  181. function reset_cp() { set_cp(1200); reset_ansi(); }
  182. function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
  183. function utf16leread(data) {
  184. var o = [];
  185. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
  186. return o.join("");
  187. }
  188. function utf16beread(data) {
  189. var o = [];
  190. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
  191. return o.join("");
  192. }
  193. var debom = function(data) {
  194. var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
  195. if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.slice(2));
  196. if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.slice(2));
  197. if(c1 == 0xFEFF) return data.slice(1);
  198. return data;
  199. };
  200. var _getchar = function _gc1(x) { return String.fromCharCode(x); };
  201. var _getansi = function _ga1(x) { return String.fromCharCode(x); };
  202. if(typeof $cptable !== 'undefined') {
  203. set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  204. debom = function(data) {
  205. if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return $cptable.utils.decode(1200, char_codes(data.slice(2))); }
  206. return data;
  207. };
  208. _getchar = function _gc2(x) {
  209. if(current_codepage === 1200) return String.fromCharCode(x);
  210. return $cptable.utils.decode(current_codepage, [x&255,x>>8])[0];
  211. };
  212. _getansi = function _ga2(x) {
  213. return $cptable.utils.decode(current_ansi, [x])[0];
  214. };
  215. }
  216. var DENSE = null;
  217. var DIF_XL = true;
  218. var Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  219. function Base64_encode(input) {
  220. var o = "";
  221. var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  222. for (var i = 0; i < input.length; ) {
  223. c1 = input.charCodeAt(i++);
  224. e1 = c1 >> 2;
  225. c2 = input.charCodeAt(i++);
  226. e2 = (c1 & 3) << 4 | c2 >> 4;
  227. c3 = input.charCodeAt(i++);
  228. e3 = (c2 & 15) << 2 | c3 >> 6;
  229. e4 = c3 & 63;
  230. if (isNaN(c2)) {
  231. e3 = e4 = 64;
  232. } else if (isNaN(c3)) {
  233. e4 = 64;
  234. }
  235. o += Base64_map.charAt(e1) + Base64_map.charAt(e2) + Base64_map.charAt(e3) + Base64_map.charAt(e4);
  236. }
  237. return o;
  238. }
  239. function Base64_decode(input) {
  240. var o = "";
  241. var c1 = 0, c2 = 0, c3 = 0, e1 = 0, e2 = 0, e3 = 0, e4 = 0;
  242. input = input.replace(/[^\w\+\/\=]/g, "");
  243. for (var i = 0; i < input.length; ) {
  244. e1 = Base64_map.indexOf(input.charAt(i++));
  245. e2 = Base64_map.indexOf(input.charAt(i++));
  246. c1 = e1 << 2 | e2 >> 4;
  247. o += String.fromCharCode(c1);
  248. e3 = Base64_map.indexOf(input.charAt(i++));
  249. c2 = (e2 & 15) << 4 | e3 >> 2;
  250. if (e3 !== 64) {
  251. o += String.fromCharCode(c2);
  252. }
  253. e4 = Base64_map.indexOf(input.charAt(i++));
  254. c3 = (e3 & 3) << 6 | e4;
  255. if (e4 !== 64) {
  256. o += String.fromCharCode(c3);
  257. }
  258. }
  259. return o;
  260. }
  261. var has_buf = (function() { return typeof Buffer !== 'undefined' && typeof undefined !== 'undefined' && typeof ({}) !== 'undefined' && !!({}).node; })();
  262. var Buffer_from = (function() {
  263. if(typeof Buffer !== 'undefined') {
  264. var nbfs = !Buffer.from;
  265. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  266. return nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  267. }
  268. return function() {};
  269. })();
  270. function new_raw_buf(len) {
  271. /* jshint -W056 */
  272. if(has_buf) return Buffer.alloc ? Buffer.alloc(len) : new Buffer(len);
  273. return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
  274. /* jshint +W056 */
  275. }
  276. function new_unsafe_buf(len) {
  277. /* jshint -W056 */
  278. if(has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len);
  279. return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len);
  280. /* jshint +W056 */
  281. }
  282. var s2a = function s2a(s) {
  283. if(has_buf) return Buffer_from(s, "binary");
  284. return s.split("").map(function(x){ return x.charCodeAt(0) & 0xff; });
  285. };
  286. function s2ab(s) {
  287. if(typeof ArrayBuffer === 'undefined') return s2a(s);
  288. var buf = new ArrayBuffer(s.length), view = new Uint8Array(buf);
  289. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  290. return buf;
  291. }
  292. function a2s(data) {
  293. if(Array.isArray(data)) return data.map(function(c) { return String.fromCharCode(c); }).join("");
  294. var o = []; for(var i = 0; i < data.length; ++i) o[i] = String.fromCharCode(data[i]); return o.join("");
  295. }
  296. function a2u(data) {
  297. if(typeof Uint8Array === 'undefined') throw new Error("Unsupported");
  298. return new Uint8Array(data);
  299. }
  300. function ab2a(data) {
  301. if(typeof ArrayBuffer == 'undefined') throw new Error("Unsupported");
  302. if(data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
  303. var o = new Array(data.length);
  304. for(var i = 0; i < data.length; ++i) o[i] = data[i];
  305. return o;
  306. }
  307. var bconcat = has_buf ? function(bufs) { return Buffer.concat(bufs.map(function(buf) { return Buffer.isBuffer(buf) ? buf : Buffer_from(buf); })); } : function(bufs) {
  308. if(typeof Uint8Array !== "undefined") {
  309. var i = 0, maxlen = 0;
  310. for(i = 0; i < bufs.length; ++i) maxlen += bufs[i].length;
  311. var o = new Uint8Array(maxlen);
  312. var len = 0;
  313. for(i = 0, maxlen = 0; i < bufs.length; maxlen += len, ++i) {
  314. len = bufs[i].length;
  315. if(bufs[i] instanceof Uint8Array) o.set(bufs[i], maxlen);
  316. else if(typeof bufs[i] == "string") { throw "wtf"; }
  317. else o.set(new Uint8Array(bufs[i]), maxlen);
  318. }
  319. return o;
  320. }
  321. return [].concat.apply([], bufs.map(function(buf) { return Array.isArray(buf) ? buf : [].slice.call(buf); }));
  322. };
  323. function utf8decode(content) {
  324. var out = [], widx = 0, L = content.length + 250;
  325. var o = new_raw_buf(content.length + 255);
  326. for(var ridx = 0; ridx < content.length; ++ridx) {
  327. var c = content.charCodeAt(ridx);
  328. if(c < 0x80) o[widx++] = c;
  329. else if(c < 0x800) {
  330. o[widx++] = (192|((c>>6)&31));
  331. o[widx++] = (128|(c&63));
  332. } else if(c >= 0xD800 && c < 0xE000) {
  333. c = (c&1023)+64;
  334. var d = content.charCodeAt(++ridx)&1023;
  335. o[widx++] = (240|((c>>8)&7));
  336. o[widx++] = (128|((c>>2)&63));
  337. o[widx++] = (128|((d>>6)&15)|((c&3)<<4));
  338. o[widx++] = (128|(d&63));
  339. } else {
  340. o[widx++] = (224|((c>>12)&15));
  341. o[widx++] = (128|((c>>6)&63));
  342. o[widx++] = (128|(c&63));
  343. }
  344. if(widx > L) {
  345. out.push(o.slice(0, widx));
  346. widx = 0;
  347. o = new_raw_buf(65535);
  348. L = 65530;
  349. }
  350. }
  351. out.push(o.slice(0, widx));
  352. return bconcat(out);
  353. }
  354. var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/g;
  355. /* ssf.js (C) 2013-present SheetJS -- http://sheetjs.com */
  356. /*jshint -W041 */
  357. function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
  358. function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  359. function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;}
  360. function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);}
  361. function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;}
  362. function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  363. var p2_32 = Math.pow(2,32);
  364. function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
  365. /* yes, in 2022 this is still faster than string compare */
  366. 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; }
  367. var days = [
  368. ['Sun', 'Sunday'],
  369. ['Mon', 'Monday'],
  370. ['Tue', 'Tuesday'],
  371. ['Wed', 'Wednesday'],
  372. ['Thu', 'Thursday'],
  373. ['Fri', 'Friday'],
  374. ['Sat', 'Saturday']
  375. ];
  376. var months = [
  377. ['J', 'Jan', 'January'],
  378. ['F', 'Feb', 'February'],
  379. ['M', 'Mar', 'March'],
  380. ['A', 'Apr', 'April'],
  381. ['M', 'May', 'May'],
  382. ['J', 'Jun', 'June'],
  383. ['J', 'Jul', 'July'],
  384. ['A', 'Aug', 'August'],
  385. ['S', 'Sep', 'September'],
  386. ['O', 'Oct', 'October'],
  387. ['N', 'Nov', 'November'],
  388. ['D', 'Dec', 'December']
  389. ];
  390. function SSF_init_table(t) {
  391. if(!t) t = {};
  392. t[0]= 'General';
  393. t[1]= '0';
  394. t[2]= '0.00';
  395. t[3]= '#,##0';
  396. t[4]= '#,##0.00';
  397. t[9]= '0%';
  398. t[10]= '0.00%';
  399. t[11]= '0.00E+00';
  400. t[12]= '# ?/?';
  401. t[13]= '# ??/??';
  402. t[14]= 'm/d/yy';
  403. t[15]= 'd-mmm-yy';
  404. t[16]= 'd-mmm';
  405. t[17]= 'mmm-yy';
  406. t[18]= 'h:mm AM/PM';
  407. t[19]= 'h:mm:ss AM/PM';
  408. t[20]= 'h:mm';
  409. t[21]= 'h:mm:ss';
  410. t[22]= 'm/d/yy h:mm';
  411. t[37]= '#,##0 ;(#,##0)';
  412. t[38]= '#,##0 ;[Red](#,##0)';
  413. t[39]= '#,##0.00;(#,##0.00)';
  414. t[40]= '#,##0.00;[Red](#,##0.00)';
  415. t[45]= 'mm:ss';
  416. t[46]= '[h]:mm:ss';
  417. t[47]= 'mmss.0';
  418. t[48]= '##0.0E+0';
  419. t[49]= '@';
  420. t[56]= '"上午/下午 "hh"時"mm"分"ss"秒 "';
  421. return t;
  422. }
  423. /* repeated to satiate webpack */
  424. var table_fmt = {
  425. 0: 'General',
  426. 1: '0',
  427. 2: '0.00',
  428. 3: '#,##0',
  429. 4: '#,##0.00',
  430. 9: '0%',
  431. 10: '0.00%',
  432. 11: '0.00E+00',
  433. 12: '# ?/?',
  434. 13: '# ??/??',
  435. 14: 'm/d/yy',
  436. 15: 'd-mmm-yy',
  437. 16: 'd-mmm',
  438. 17: 'mmm-yy',
  439. 18: 'h:mm AM/PM',
  440. 19: 'h:mm:ss AM/PM',
  441. 20: 'h:mm',
  442. 21: 'h:mm:ss',
  443. 22: 'm/d/yy h:mm',
  444. 37: '#,##0 ;(#,##0)',
  445. 38: '#,##0 ;[Red](#,##0)',
  446. 39: '#,##0.00;(#,##0.00)',
  447. 40: '#,##0.00;[Red](#,##0.00)',
  448. 45: 'mm:ss',
  449. 46: '[h]:mm:ss',
  450. 47: 'mmss.0',
  451. 48: '##0.0E+0',
  452. 49: '@',
  453. 56: '"上午/下午 "hh"時"mm"分"ss"秒 "'
  454. };
  455. /* Defaults determined by systematically testing in Excel 2019 */
  456. /* These formats appear to default to other formats in the table */
  457. var SSF_default_map = {
  458. 5: 37, 6: 38, 7: 39, 8: 40, // 5 -> 37 ... 8 -> 40
  459. 23: 0, 24: 0, 25: 0, 26: 0, // 23 -> 0 ... 26 -> 0
  460. 27: 14, 28: 14, 29: 14, 30: 14, 31: 14, // 27 -> 14 ... 31 -> 14
  461. 50: 14, 51: 14, 52: 14, 53: 14, 54: 14, // 50 -> 14 ... 58 -> 14
  462. 55: 14, 56: 14, 57: 14, 58: 14,
  463. 59: 1, 60: 2, 61: 3, 62: 4, // 59 -> 1 ... 62 -> 4
  464. 67: 9, 68: 10, // 67 -> 9 ... 68 -> 10
  465. 69: 12, 70: 13, 71: 14, // 69 -> 12 ... 71 -> 14
  466. 72: 14, 73: 15, 74: 16, 75: 17, // 72 -> 14 ... 75 -> 17
  467. 76: 20, 77: 21, 78: 22, // 76 -> 20 ... 78 -> 22
  468. 79: 45, 80: 46, 81: 47, // 79 -> 45 ... 81 -> 47
  469. 82: 0 // 82 -> 0 ... 65536 -> 0 (omitted)
  470. };
  471. /* These formats technically refer to Accounting formats with no equivalent */
  472. var SSF_default_str = {
  473. // 5 -- Currency, 0 decimal, black negative
  474. 5: '"$"#,##0_);\\("$"#,##0\\)',
  475. 63: '"$"#,##0_);\\("$"#,##0\\)',
  476. // 6 -- Currency, 0 decimal, red negative
  477. 6: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  478. 64: '"$"#,##0_);[Red]\\("$"#,##0\\)',
  479. // 7 -- Currency, 2 decimal, black negative
  480. 7: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  481. 65: '"$"#,##0.00_);\\("$"#,##0.00\\)',
  482. // 8 -- Currency, 2 decimal, red negative
  483. 8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  484. 66: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  485. // 41 -- Accounting, 0 decimal, No Symbol
  486. 41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',
  487. // 42 -- Accounting, 0 decimal, $ Symbol
  488. 42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',
  489. // 43 -- Accounting, 2 decimal, No Symbol
  490. 43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',
  491. // 44 -- Accounting, 2 decimal, $ Symbol
  492. 44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)'
  493. };
  494. function SSF_frac(x, D, mixed) {
  495. var sgn = x < 0 ? -1 : 1;
  496. var B = x * sgn;
  497. var P_2 = 0, P_1 = 1, P = 0;
  498. var Q_2 = 1, Q_1 = 0, Q = 0;
  499. var A = Math.floor(B);
  500. while(Q_1 < D) {
  501. A = Math.floor(B);
  502. P = A * P_1 + P_2;
  503. Q = A * Q_1 + Q_2;
  504. if((B - A) < 0.00000005) break;
  505. B = 1 / (B - A);
  506. P_2 = P_1; P_1 = P;
  507. Q_2 = Q_1; Q_1 = Q;
  508. }
  509. if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
  510. if(!mixed) return [0, sgn * P, Q];
  511. var q = Math.floor(sgn * P/Q);
  512. return [q, sgn*P - q*Q, Q];
  513. }
  514. function SSF_parse_date_code(v,opts,b2) {
  515. if(v > 2958465 || v < 0) return null;
  516. var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
  517. var dout=[];
  518. 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};
  519. if(Math.abs(out.u) < 1e-6) out.u = 0;
  520. if(opts && opts.date1904) date += 1462;
  521. if(out.u > 0.9999) {
  522. out.u = 0;
  523. if(++time == 86400) { out.T = time = 0; ++date; ++out.D; }
  524. }
  525. if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
  526. else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
  527. else {
  528. if(date > 60) --date;
  529. /* 1 = Jan 1 1900 in Gregorian */
  530. var d = new Date(1900, 0, 1);
  531. d.setDate(d.getDate() + date - 1);
  532. dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
  533. dow = d.getDay();
  534. if(date < 60) dow = (dow + 6) % 7;
  535. if(b2) dow = SSF_fix_hijri(d, dout);
  536. }
  537. out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
  538. out.S = time % 60; time = Math.floor(time / 60);
  539. out.M = time % 60; time = Math.floor(time / 60);
  540. out.H = time;
  541. out.q = dow;
  542. return out;
  543. }
  544. var SSFbasedate = new Date(1899, 11, 31, 0, 0, 0);
  545. var SSFdnthresh = SSFbasedate.getTime();
  546. var SSFbase1904 = new Date(1900, 2, 1, 0, 0, 0);
  547. function datenum_local(v, date1904) {
  548. var epoch = v.getTime();
  549. if(date1904) epoch -= 1461*24*60*60*1000;
  550. else if(v >= SSFbase1904) epoch += 24*60*60*1000;
  551. return (epoch - (SSFdnthresh + (v.getTimezoneOffset() - SSFbasedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
  552. }
  553. /* ECMA-376 18.8.30 numFmt*/
  554. /* Note: `toPrecision` uses standard form when prec > E and E >= -6 */
  555. /* exponent >= -9 and <= 9 */
  556. function SSF_strip_decimal(o) {
  557. return (o.indexOf(".") == -1) ? o : o.replace(/(?:\.0*|(\.\d*[1-9])0+)$/, "$1");
  558. }
  559. /* General Exponential always shows 2 digits exp and trims the mantissa */
  560. function SSF_normalize_exp(o) {
  561. if(o.indexOf("E") == -1) return o;
  562. return o.replace(/(?:\.0*|(\.\d*[1-9])0+)[Ee]/,"$1E").replace(/(E[+-])(\d)$/,"$10$2");
  563. }
  564. /* exponent >= -9 and <= 9 */
  565. function SSF_small_exp(v) {
  566. var w = (v<0?12:11);
  567. var o = SSF_strip_decimal(v.toFixed(12)); if(o.length <= w) return o;
  568. o = v.toPrecision(10); if(o.length <= w) return o;
  569. return v.toExponential(5);
  570. }
  571. /* exponent >= 11 or <= -10 likely exponential */
  572. function SSF_large_exp(v) {
  573. var o = SSF_strip_decimal(v.toFixed(11));
  574. return (o.length > (v<0?12:11) || o === "0" || o === "-0") ? v.toPrecision(6) : o;
  575. }
  576. function SSF_general_num(v) {
  577. var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;
  578. if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
  579. else if(Math.abs(V) <= 9) o = SSF_small_exp(v);
  580. else if(V === 10) o = v.toFixed(10).substr(0,12);
  581. else o = SSF_large_exp(v);
  582. return SSF_strip_decimal(SSF_normalize_exp(o.toUpperCase()));
  583. }
  584. /*
  585. "General" rules:
  586. - text is passed through ("@")
  587. - booleans are rendered as TRUE/FALSE
  588. - "up to 11 characters" displayed for numbers
  589. - Default date format (code 14) used for Dates
  590. The longest 32-bit integer text is "-2147483648", exactly 11 chars
  591. TODO: technically the display depends on the width of the cell
  592. */
  593. function SSF_general(v, opts) {
  594. switch(typeof v) {
  595. case 'string': return v;
  596. case 'boolean': return v ? "TRUE" : "FALSE";
  597. case 'number': return (v|0) === v ? v.toString(10) : SSF_general_num(v);
  598. case 'undefined': return "";
  599. case 'object':
  600. if(v == null) return "";
  601. if(v instanceof Date) return SSF_format(14, datenum_local(v, opts && opts.date1904), opts);
  602. }
  603. throw new Error("unsupported value in General format: " + v);
  604. }
  605. function SSF_fix_hijri(date, o) {
  606. /* TODO: properly adjust y/m/d and */
  607. o[0] -= 581;
  608. var dow = date.getDay();
  609. if(date < 60) dow = (dow + 6) % 7;
  610. return dow;
  611. }
  612. //var THAI_DIGITS = "\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59".split("");
  613. function SSF_write_date(type, fmt, val, ss0) {
  614. var o="", ss=0, tt=0, y = val.y, out, outl = 0;
  615. switch(type) {
  616. case 98: /* 'b' buddhist year */
  617. y = val.y + 543;
  618. /* falls through */
  619. case 121: /* 'y' year */
  620. switch(fmt.length) {
  621. case 1: case 2: out = y % 100; outl = 2; break;
  622. default: out = y % 10000; outl = 4; break;
  623. } break;
  624. case 109: /* 'm' month */
  625. switch(fmt.length) {
  626. case 1: case 2: out = val.m; outl = fmt.length; break;
  627. case 3: return months[val.m-1][1];
  628. case 5: return months[val.m-1][0];
  629. default: return months[val.m-1][2];
  630. } break;
  631. case 100: /* 'd' day */
  632. switch(fmt.length) {
  633. case 1: case 2: out = val.d; outl = fmt.length; break;
  634. case 3: return days[val.q][0];
  635. default: return days[val.q][1];
  636. } break;
  637. case 104: /* 'h' 12-hour */
  638. switch(fmt.length) {
  639. case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
  640. default: throw 'bad hour format: ' + fmt;
  641. } break;
  642. case 72: /* 'H' 24-hour */
  643. switch(fmt.length) {
  644. case 1: case 2: out = val.H; outl = fmt.length; break;
  645. default: throw 'bad hour format: ' + fmt;
  646. } break;
  647. case 77: /* 'M' minutes */
  648. switch(fmt.length) {
  649. case 1: case 2: out = val.M; outl = fmt.length; break;
  650. default: throw 'bad minute format: ' + fmt;
  651. } break;
  652. case 115: /* 's' seconds */
  653. if(fmt != 's' && fmt != 'ss' && fmt != '.0' && fmt != '.00' && fmt != '.000') throw 'bad second format: ' + fmt;
  654. if(val.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val.S, fmt.length);
  655. if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
  656. else tt = ss0 === 1 ? 10 : 1;
  657. ss = Math.round((tt)*(val.S + val.u));
  658. if(ss >= 60*tt) ss = 0;
  659. if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
  660. o = pad0(ss,2 + ss0);
  661. if(fmt === 'ss') return o.substr(0,2);
  662. return "." + o.substr(2,fmt.length-1);
  663. case 90: /* 'Z' absolute time */
  664. switch(fmt) {
  665. case '[h]': case '[hh]': out = val.D*24+val.H; break;
  666. case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
  667. case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
  668. default: throw 'bad abstime format: ' + fmt;
  669. } outl = fmt.length === 3 ? 1 : 2; break;
  670. case 101: /* 'e' era */
  671. out = y; outl = 1; break;
  672. }
  673. var outstr = outl > 0 ? pad0(out, outl) : "";
  674. return outstr;
  675. }
  676. /*jshint -W086 */
  677. /*jshint +W086 */
  678. function commaify(s) {
  679. var w = 3;
  680. if(s.length <= w) return s;
  681. var j = (s.length % w), o = s.substr(0,j);
  682. for(; j!=s.length; j+=w) o+=(o.length > 0 ? "," : "") + s.substr(j,w);
  683. return o;
  684. }
  685. var pct1 = /%/g;
  686. function write_num_pct(type, fmt, val){
  687. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  688. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  689. }
  690. function write_num_cm(type, fmt, val){
  691. var idx = fmt.length - 1;
  692. while(fmt.charCodeAt(idx-1) === 44) --idx;
  693. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  694. }
  695. function write_num_exp(fmt, val){
  696. var o;
  697. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  698. if(fmt.match(/^#+0.0E\+0$/)) {
  699. if(val == 0) return "0.0E+0";
  700. else if(val < 0) return "-" + write_num_exp(fmt, -val);
  701. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  702. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  703. if(ee < 0) ee += period;
  704. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  705. if(o.indexOf("e") === -1) {
  706. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  707. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  708. else o += "E+" + (fakee - ee);
  709. while(o.substr(0,2) === "0.") {
  710. o = o.charAt(0) + o.substr(2,period) + "." + o.substr(2+period);
  711. o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
  712. }
  713. o = o.replace(/\+-/,"-");
  714. }
  715. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  716. } else o = val.toExponential(idx);
  717. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  718. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  719. return o.replace("e","E");
  720. }
  721. var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
  722. function write_num_f1(r, aval, sign) {
  723. var den = parseInt(r[4],10), rr = Math.round(aval * den), base = Math.floor(rr/den);
  724. var myn = (rr - base*den), myd = den;
  725. 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));
  726. }
  727. function write_num_f2(r, aval, sign) {
  728. return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length);
  729. }
  730. var dec1 = /^#*0*\.([0#]+)/;
  731. var closeparen = /\).*[0#]/;
  732. var phone = /\(###\) ###\\?-####/;
  733. function hashq(str) {
  734. var o = "", cc;
  735. for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
  736. case 35: break;
  737. case 63: o+= " "; break;
  738. case 48: o+= "0"; break;
  739. default: o+= String.fromCharCode(cc);
  740. }
  741. return o;
  742. }
  743. function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
  744. function dec(val, d) {
  745. var _frac = val - Math.floor(val), dd = Math.pow(10,d);
  746. if (d < ('' + Math.round(_frac * dd)).length) return 0;
  747. return Math.round(_frac * dd);
  748. }
  749. function carry(val, d) {
  750. if (d < ('' + Math.round((val-Math.floor(val))*Math.pow(10,d))).length) {
  751. return 1;
  752. }
  753. return 0;
  754. }
  755. function flr(val) {
  756. if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0));
  757. return ""+Math.floor(val);
  758. }
  759. function write_num_flt(type, fmt, val) {
  760. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  761. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  762. if(val >= 0) return write_num_flt('n', ffmt, val);
  763. return '(' + write_num_flt('n', ffmt, -val) + ')';
  764. }
  765. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
  766. if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
  767. if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
  768. if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  769. var o;
  770. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  771. if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
  772. if(fmt.match(/^[#?]+$/)) {
  773. o = pad0r(val,0); if(o === "0") o = "";
  774. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  775. }
  776. if((r = fmt.match(frac1))) return write_num_f1(r, aval, sign);
  777. if(fmt.match(/^#+0+$/)) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
  778. if((r = fmt.match(dec1))) {
  779. 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); });
  780. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  781. }
  782. fmt = fmt.replace(/^#+([0.])/, "$1");
  783. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  784. return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  785. }
  786. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify(pad0r(aval,0));
  787. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  788. 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);
  789. }
  790. if((r = fmt.match(/^#,#*,#0/))) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
  791. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  792. o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
  793. ri = 0;
  794. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  795. }
  796. if(fmt.match(phone)) {
  797. o = write_num_flt(type, "##########", val);
  798. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  799. }
  800. var oa = "";
  801. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  802. ri = Math.min(r[4].length,7);
  803. ff = SSF_frac(aval, Math.pow(10,ri)-1, false);
  804. o = "" + sign;
  805. oa = write_num("n", r[1], ff[1]);
  806. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  807. o += oa + r[2] + "/" + r[3];
  808. oa = rpad_(ff[2],ri);
  809. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  810. o += oa;
  811. return o;
  812. }
  813. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  814. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  815. ff = SSF_frac(aval, Math.pow(10,ri)-1, true);
  816. 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));
  817. }
  818. if((r = fmt.match(/^[#0?]+$/))) {
  819. o = pad0r(val, 0);
  820. if(fmt.length <= o.length) return o;
  821. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  822. }
  823. if((r = fmt.match(/^([#0?]+)\.([#0]+)$/))) {
  824. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  825. ri = o.indexOf(".");
  826. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  827. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  828. }
  829. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  830. ri = dec(val, r[1].length);
  831. 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);
  832. }
  833. switch(fmt) {
  834. case "###,##0.00": return write_num_flt(type, "#,##0.00", val);
  835. case "###,###":
  836. case "##,###":
  837. case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
  838. case "###,###.00": return write_num_flt(type, "###,##0.00",val).replace(/^0\./,".");
  839. case "#,###.00": return write_num_flt(type, "#,##0.00",val).replace(/^0\./,".");
  840. default:
  841. }
  842. throw new Error("unsupported format |" + fmt + "|");
  843. }
  844. function write_num_cm2(type, fmt, val){
  845. var idx = fmt.length - 1;
  846. while(fmt.charCodeAt(idx-1) === 44) --idx;
  847. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  848. }
  849. function write_num_pct2(type, fmt, val){
  850. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  851. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  852. }
  853. function write_num_exp2(fmt, val){
  854. var o;
  855. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  856. if(fmt.match(/^#+0.0E\+0$/)) {
  857. if(val == 0) return "0.0E+0";
  858. else if(val < 0) return "-" + write_num_exp2(fmt, -val);
  859. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  860. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  861. if(ee < 0) ee += period;
  862. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  863. if(!o.match(/[Ee]/)) {
  864. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  865. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  866. else o += "E+" + (fakee - ee);
  867. o = o.replace(/\+-/,"-");
  868. }
  869. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  870. } else o = val.toExponential(idx);
  871. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  872. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  873. return o.replace("e","E");
  874. }
  875. function write_num_int(type, fmt, val) {
  876. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  877. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  878. if(val >= 0) return write_num_int('n', ffmt, val);
  879. return '(' + write_num_int('n', ffmt, -val) + ')';
  880. }
  881. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
  882. if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
  883. if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
  884. if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  885. var o;
  886. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  887. if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
  888. if(fmt.match(/^[#?]+$/)) {
  889. o = (""+val); if(val === 0) o = "";
  890. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  891. }
  892. if((r = fmt.match(frac1))) return write_num_f2(r, aval, sign);
  893. if(fmt.match(/^#+0+$/)) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
  894. if((r = fmt.match(dec1))) {
  895. o = (""+val).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1]));
  896. o = o.replace(/\.(\d*)$/,function($$, $1) {
  897. return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  898. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  899. }
  900. fmt = fmt.replace(/^#+([0.])/, "$1");
  901. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  902. return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  903. }
  904. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify((""+aval));
  905. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  906. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length);
  907. }
  908. if((r = fmt.match(/^#,#*,#0/))) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
  909. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  910. o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
  911. ri = 0;
  912. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  913. }
  914. if(fmt.match(phone)) {
  915. o = write_num_int(type, "##########", val);
  916. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  917. }
  918. var oa = "";
  919. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  920. ri = Math.min(r[4].length,7);
  921. ff = SSF_frac(aval, Math.pow(10,ri)-1, false);
  922. o = "" + sign;
  923. oa = write_num("n", r[1], ff[1]);
  924. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  925. o += oa + r[2] + "/" + r[3];
  926. oa = rpad_(ff[2],ri);
  927. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  928. o += oa;
  929. return o;
  930. }
  931. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  932. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  933. ff = SSF_frac(aval, Math.pow(10,ri)-1, true);
  934. 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));
  935. }
  936. if((r = fmt.match(/^[#0?]+$/))) {
  937. o = "" + val;
  938. if(fmt.length <= o.length) return o;
  939. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  940. }
  941. if((r = fmt.match(/^([#0]+)\.([#0]+)$/))) {
  942. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  943. ri = o.indexOf(".");
  944. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  945. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  946. }
  947. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  948. 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);
  949. }
  950. switch(fmt) {
  951. case "###,###":
  952. case "##,###":
  953. case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
  954. default:
  955. if(fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0,fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
  956. }
  957. throw new Error("unsupported format |" + fmt + "|");
  958. }
  959. function write_num(type, fmt, val) {
  960. return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
  961. }
  962. function SSF_split_fmt(fmt) {
  963. var out = [];
  964. var in_str = false/*, cc*/;
  965. for(var i = 0, j = 0; i < fmt.length; ++i) switch((/*cc=*/fmt.charCodeAt(i))) {
  966. case 34: /* '"' */
  967. in_str = !in_str; break;
  968. case 95: case 42: case 92: /* '_' '*' '\\' */
  969. ++i; break;
  970. case 59: /* ';' */
  971. out[out.length] = fmt.substr(j,i-j);
  972. j = i+1;
  973. }
  974. out[out.length] = fmt.substr(j);
  975. if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
  976. return out;
  977. }
  978. var SSF_abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
  979. function fmt_is_date(fmt) {
  980. var i = 0, /*cc = 0,*/ c = "", o = "";
  981. while(i < fmt.length) {
  982. switch((c = fmt.charAt(i))) {
  983. case 'G': if(SSF_isgeneral(fmt, i)) i+= 6; i++; break;
  984. case '"': for(;(/*cc=*/fmt.charCodeAt(++i)) !== 34 && i < fmt.length;){/*empty*/} ++i; break;
  985. case '\\': i+=2; break;
  986. case '_': i+=2; break;
  987. case '@': ++i; break;
  988. case 'B': case 'b':
  989. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") return true;
  990. /* falls through */
  991. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  992. /* falls through */
  993. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': return true;
  994. case 'A': case 'a': case '上':
  995. if(fmt.substr(i, 3).toUpperCase() === "A/P") return true;
  996. if(fmt.substr(i, 5).toUpperCase() === "AM/PM") return true;
  997. if(fmt.substr(i, 5).toUpperCase() === "上午/下午") return true;
  998. ++i; break;
  999. case '[':
  1000. o = c;
  1001. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  1002. if(o.match(SSF_abstime)) return true;
  1003. break;
  1004. case '.':
  1005. /* falls through */
  1006. case '0': case '#':
  1007. 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 */}
  1008. break;
  1009. case '?': while(fmt.charAt(++i) === c){/* empty */} break;
  1010. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break;
  1011. case '(': case ')': ++i; break;
  1012. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  1013. while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1){/* empty */} break;
  1014. case ' ': ++i; break;
  1015. default: ++i; break;
  1016. }
  1017. }
  1018. return false;
  1019. }
  1020. function eval_fmt(fmt, v, opts, flen) {
  1021. var out = [], o = "", i = 0, c = "", lst='t', dt, j, cc;
  1022. var hr='H';
  1023. /* Tokenize */
  1024. while(i < fmt.length) {
  1025. switch((c = fmt.charAt(i))) {
  1026. case 'G': /* General */
  1027. if(!SSF_isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
  1028. out[out.length] = {t:'G', v:'General'}; i+=7; break;
  1029. case '"': /* Literal text */
  1030. for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
  1031. out[out.length] = {t:'t', v:o}; ++i; break;
  1032. case '\\': var w = fmt.charAt(++i), t = (w === "(" || w === ")") ? w : 't';
  1033. out[out.length] = {t:t, v:w}; ++i; break;
  1034. case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
  1035. case '@': /* Text Placeholder */
  1036. out[out.length] = {t:'T', v:v}; ++i; break;
  1037. case 'B': case 'b':
  1038. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") {
  1039. if(dt==null) { dt=SSF_parse_date_code(v, opts, fmt.charAt(i+1) === "2"); if(dt==null) return ""; }
  1040. out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
  1041. }
  1042. /* falls through */
  1043. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  1044. c = c.toLowerCase();
  1045. /* falls through */
  1046. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
  1047. if(v < 0) return "";
  1048. if(dt==null) { dt=SSF_parse_date_code(v, opts); if(dt==null) return ""; }
  1049. o = c; while(++i < fmt.length && fmt.charAt(i).toLowerCase() === c) o+=c;
  1050. if(c === 'm' && lst.toLowerCase() === 'h') c = 'M';
  1051. if(c === 'h') c = hr;
  1052. out[out.length] = {t:c, v:o}; lst = c; break;
  1053. case 'A': case 'a': case '上':
  1054. var q={t:c, v:c};
  1055. if(dt==null) dt=SSF_parse_date_code(v, opts);
  1056. if(fmt.substr(i, 3).toUpperCase() === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
  1057. 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'; }
  1058. else if(fmt.substr(i,5).toUpperCase() === "上午/下午") { if(dt!=null) q.v = dt.H >= 12 ? "下午" : "上午"; q.t = 'T'; i+=5; hr='h'; }
  1059. else { q.t = "t"; ++i; }
  1060. if(dt==null && q.t === 'T') return "";
  1061. out[out.length] = q; lst = c; break;
  1062. case '[':
  1063. o = c;
  1064. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  1065. if(o.slice(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
  1066. if(o.match(SSF_abstime)) {
  1067. if(dt==null) { dt=SSF_parse_date_code(v, opts); if(dt==null) return ""; }
  1068. out[out.length] = {t:'Z', v:o.toLowerCase()};
  1069. lst = o.charAt(1);
  1070. } else if(o.indexOf("$") > -1) {
  1071. o = (o.match(/\$([^-\[\]]*)/)||[])[1]||"$";
  1072. if(!fmt_is_date(fmt)) out[out.length] = {t:'t',v:o};
  1073. }
  1074. break;
  1075. /* Numbers */
  1076. case '.':
  1077. if(dt != null) {
  1078. o = c; while(++i < fmt.length && (c=fmt.charAt(i)) === "0") o += c;
  1079. out[out.length] = {t:'s', v:o}; break;
  1080. }
  1081. /* falls through */
  1082. case '0': case '#':
  1083. o = c; while(++i < fmt.length && "0#?.,E+-%".indexOf(c=fmt.charAt(i)) > -1) o += c;
  1084. out[out.length] = {t:'n', v:o}; break;
  1085. case '?':
  1086. o = c; while(fmt.charAt(++i) === c) o+=c;
  1087. out[out.length] = {t:c, v:o}; lst = c; break;
  1088. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break; // **
  1089. case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
  1090. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  1091. o = c; while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) o+=fmt.charAt(i);
  1092. out[out.length] = {t:'D', v:o}; break;
  1093. case ' ': out[out.length] = {t:c, v:c}; ++i; break;
  1094. case '$': out[out.length] = {t:'t', v:'$'}; ++i; break;
  1095. default:
  1096. if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
  1097. out[out.length] = {t:'t', v:c}; ++i; break;
  1098. }
  1099. }
  1100. /* Scan for date/time parts */
  1101. var bt = 0, ss0 = 0, ssm;
  1102. for(i=out.length-1, lst='t'; i >= 0; --i) {
  1103. switch(out[i].t) {
  1104. case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
  1105. case 's':
  1106. if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
  1107. if(bt < 3) bt = 3;
  1108. /* falls through */
  1109. case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
  1110. case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
  1111. case 'X': /*if(out[i].v === "B2");*/
  1112. break;
  1113. case 'Z':
  1114. if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
  1115. if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
  1116. if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
  1117. }
  1118. }
  1119. /* time rounding depends on presence of minute / second / usec fields */
  1120. switch(bt) {
  1121. case 0: break;
  1122. case 1:
  1123. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  1124. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  1125. if(dt.M >= 60) { dt.M = 0; ++dt.H; }
  1126. break;
  1127. case 2:
  1128. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  1129. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  1130. break;
  1131. }
  1132. /* replace fields */
  1133. var nstr = "", jj;
  1134. for(i=0; i < out.length; ++i) {
  1135. switch(out[i].t) {
  1136. case 't': case 'T': case ' ': case 'D': break;
  1137. case 'X': out[i].v = ""; out[i].t = ";"; break;
  1138. case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
  1139. out[i].v = SSF_write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
  1140. out[i].t = 't'; break;
  1141. case 'n': case '?':
  1142. jj = i+1;
  1143. while(out[jj] != null && (
  1144. (c=out[jj].t) === "?" || c === "D" ||
  1145. ((c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/')) ||
  1146. (out[i].t === '(' && (c === ' ' || c === 'n' || c === ')')) ||
  1147. (c === 't' && (out[jj].v === '/' || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?'))
  1148. )) {
  1149. out[i].v += out[jj].v;
  1150. out[jj] = {v:"", t:";"}; ++jj;
  1151. }
  1152. nstr += out[i].v;
  1153. i = jj-1; break;
  1154. case 'G': out[i].t = 't'; out[i].v = SSF_general(v,opts); break;
  1155. }
  1156. }
  1157. var vv = "", myv, ostr;
  1158. if(nstr.length > 0) {
  1159. if(nstr.charCodeAt(0) == 40) /* '(' */ {
  1160. myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v);
  1161. ostr = write_num('n', nstr, myv);
  1162. } else {
  1163. myv = (v<0 && flen > 1 ? -v : v);
  1164. ostr = write_num('n', nstr, myv);
  1165. if(myv < 0 && out[0] && out[0].t == 't') {
  1166. ostr = ostr.substr(1);
  1167. out[0].v = "-" + out[0].v;
  1168. }
  1169. }
  1170. jj=ostr.length-1;
  1171. var decpt = out.length;
  1172. for(i=0; i < out.length; ++i) if(out[i] != null && out[i].t != 't' && out[i].v.indexOf(".") > -1) { decpt = i; break; }
  1173. var lasti=out.length;
  1174. if(decpt === out.length && ostr.indexOf("E") === -1) {
  1175. for(i=out.length-1; i>= 0;--i) {
  1176. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  1177. if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
  1178. else if(jj < 0) out[i].v = "";
  1179. else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
  1180. out[i].t = 't';
  1181. lasti = i;
  1182. }
  1183. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  1184. }
  1185. else if(decpt !== out.length && ostr.indexOf("E") === -1) {
  1186. jj = ostr.indexOf(".")-1;
  1187. for(i=decpt; i>= 0; --i) {
  1188. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  1189. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
  1190. vv = out[i].v.substr(j+1);
  1191. for(; j>=0; --j) {
  1192. if(jj>=0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#")) vv = ostr.charAt(jj--) + vv;
  1193. }
  1194. out[i].v = vv;
  1195. out[i].t = 't';
  1196. lasti = i;
  1197. }
  1198. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  1199. jj = ostr.indexOf(".")+1;
  1200. for(i=decpt; i<out.length; ++i) {
  1201. if(out[i] == null || ('n?('.indexOf(out[i].t) === -1 && i !== decpt)) continue;
  1202. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
  1203. vv = out[i].v.substr(0,j);
  1204. for(; j<out[i].v.length; ++j) {
  1205. if(jj<ostr.length) vv += ostr.charAt(jj++);
  1206. }
  1207. out[i].v = vv;
  1208. out[i].t = 't';
  1209. lasti = i;
  1210. }
  1211. }
  1212. }
  1213. for(i=0; i<out.length; ++i) if(out[i] != null && 'n?'.indexOf(out[i].t)>-1) {
  1214. myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
  1215. out[i].v = write_num(out[i].t, out[i].v, myv);
  1216. out[i].t = 't';
  1217. }
  1218. var retval = "";
  1219. for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
  1220. return retval;
  1221. }
  1222. var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
  1223. function chkcond(v, rr) {
  1224. if(rr == null) return false;
  1225. var thresh = parseFloat(rr[2]);
  1226. switch(rr[1]) {
  1227. case "=": if(v == thresh) return true; break;
  1228. case ">": if(v > thresh) return true; break;
  1229. case "<": if(v < thresh) return true; break;
  1230. case "<>": if(v != thresh) return true; break;
  1231. case ">=": if(v >= thresh) return true; break;
  1232. case "<=": if(v <= thresh) return true; break;
  1233. }
  1234. return false;
  1235. }
  1236. function choose_fmt(f, v) {
  1237. var fmt = SSF_split_fmt(f);
  1238. var l = fmt.length, lat = fmt[l-1].indexOf("@");
  1239. if(l<4 && lat>-1) --l;
  1240. if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
  1241. if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
  1242. switch(fmt.length) {
  1243. case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
  1244. case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
  1245. case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
  1246. case 4: break;
  1247. }
  1248. var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
  1249. if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
  1250. if(fmt[0].match(/\[[=<>]/) != null || fmt[1].match(/\[[=<>]/) != null) {
  1251. var m1 = fmt[0].match(cfregex2);
  1252. var m2 = fmt[1].match(cfregex2);
  1253. return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
  1254. }
  1255. return [l, ff];
  1256. }
  1257. function SSF_format(fmt,v,o) {
  1258. if(o == null) o = {};
  1259. var sfmt = "";
  1260. switch(typeof fmt) {
  1261. case "string":
  1262. if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
  1263. else sfmt = fmt;
  1264. break;
  1265. case "number":
  1266. if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
  1267. else sfmt = (o.table != null ? (o.table) : table_fmt)[fmt];
  1268. if(sfmt == null) sfmt = (o.table && o.table[SSF_default_map[fmt]]) || table_fmt[SSF_default_map[fmt]];
  1269. if(sfmt == null) sfmt = SSF_default_str[fmt] || "General";
  1270. break;
  1271. }
  1272. if(SSF_isgeneral(sfmt,0)) return SSF_general(v, o);
  1273. if(v instanceof Date) v = datenum_local(v, o.date1904);
  1274. var f = choose_fmt(sfmt, v);
  1275. if(SSF_isgeneral(f[1])) return SSF_general(v, o);
  1276. if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
  1277. else if(v === "" || v == null) return "";
  1278. return eval_fmt(f[1], v, o, f[0]);
  1279. }
  1280. function SSF_load(fmt, idx) {
  1281. if(typeof idx != 'number') {
  1282. idx = +idx || -1;
  1283. for(var i = 0; i < 0x0188; ++i) {
  1284. if(table_fmt[i] == undefined) { if(idx < 0) idx = i; continue; }
  1285. if(table_fmt[i] == fmt) { idx = i; break; }
  1286. }
  1287. if(idx < 0) idx = 0x187;
  1288. }
  1289. table_fmt[idx] = fmt;
  1290. return idx;
  1291. }
  1292. function SSF_load_table(tbl) {
  1293. for(var i=0; i!=0x0188; ++i)
  1294. if(tbl[i] !== undefined) SSF_load(tbl[i], i);
  1295. }
  1296. function make_ssf() {
  1297. table_fmt = SSF_init_table();
  1298. }
  1299. var SSF = {
  1300. format: SSF_format,
  1301. load: SSF_load,
  1302. _table: table_fmt,
  1303. load_table: SSF_load_table,
  1304. parse_date_code: SSF_parse_date_code,
  1305. is_date: fmt_is_date,
  1306. get_table: function get_table() { return SSF._table = table_fmt; }
  1307. };
  1308. var SSFImplicit/*{[number]:string}*/ = ({
  1309. "5": '"$"#,##0_);\\("$"#,##0\\)',
  1310. "6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  1311. "7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  1312. "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1313. "23": 'General', "24": 'General', "25": 'General', "26": 'General',
  1314. "27": 'm/d/yy', "28": 'm/d/yy', "29": 'm/d/yy', "30": 'm/d/yy', "31": 'm/d/yy',
  1315. "32": 'h:mm:ss', "33": 'h:mm:ss', "34": 'h:mm:ss', "35": 'h:mm:ss',
  1316. "36": 'm/d/yy',
  1317. "41": '_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
  1318. "42": '_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
  1319. "43": '_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
  1320. "44": '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
  1321. "50": 'm/d/yy', "51": 'm/d/yy', "52": 'm/d/yy', "53": 'm/d/yy', "54": 'm/d/yy',
  1322. "55": 'm/d/yy', "56": 'm/d/yy', "57": 'm/d/yy', "58": 'm/d/yy',
  1323. "59": '0',
  1324. "60": '0.00',
  1325. "61": '#,##0',
  1326. "62": '#,##0.00',
  1327. "63": '"$"#,##0_);\\("$"#,##0\\)',
  1328. "64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  1329. "65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  1330. "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  1331. "67": '0%',
  1332. "68": '0.00%',
  1333. "69": '# ?/?',
  1334. "70": '# ??/??',
  1335. "71": 'm/d/yy',
  1336. "72": 'm/d/yy',
  1337. "73": 'd-mmm-yy',
  1338. "74": 'd-mmm',
  1339. "75": 'mmm-yy',
  1340. "76": 'h:mm',
  1341. "77": 'h:mm:ss',
  1342. "78": 'm/d/yy h:mm',
  1343. "79": 'mm:ss',
  1344. "80": '[h]:mm:ss',
  1345. "81": 'mmss.0'
  1346. });
  1347. /* dateNF parse TODO: move to SSF */
  1348. var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
  1349. function dateNF_regex(dateNF) {
  1350. var fmt = typeof dateNF == "number" ? table_fmt[dateNF] : dateNF;
  1351. fmt = fmt.replace(dateNFregex, "(\\d+)");
  1352. return new RegExp("^" + fmt + "$");
  1353. }
  1354. function dateNF_fix(str, dateNF, match) {
  1355. var Y = -1, m = -1, d = -1, H = -1, M = -1, S = -1;
  1356. (dateNF.match(dateNFregex)||[]).forEach(function(n, i) {
  1357. var v = parseInt(match[i+1], 10);
  1358. switch(n.toLowerCase().charAt(0)) {
  1359. case 'y': Y = v; break; case 'd': d = v; break;
  1360. case 'h': H = v; break; case 's': S = v; break;
  1361. case 'm': if(H >= 0) M = v; else m = v; break;
  1362. }
  1363. });
  1364. if(S >= 0 && M == -1 && m >= 0) { M = m; m = -1; }
  1365. var datestr = (("" + (Y>=0?Y: new Date().getFullYear())).slice(-4) + "-" + ("00" + (m>=1?m:1)).slice(-2) + "-" + ("00" + (d>=1?d:1)).slice(-2));
  1366. if(datestr.length == 7) datestr = "0" + datestr;
  1367. if(datestr.length == 8) datestr = "20" + datestr;
  1368. var timestr = (("00" + (H>=0?H:0)).slice(-2) + ":" + ("00" + (M>=0?M:0)).slice(-2) + ":" + ("00" + (S>=0?S:0)).slice(-2));
  1369. if(H == -1 && M == -1 && S == -1) return datestr;
  1370. if(Y == -1 && m == -1 && d == -1) return timestr;
  1371. return datestr + "T" + timestr;
  1372. }
  1373. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  1374. /* vim: set ts=2: */
  1375. /*jshint eqnull:true */
  1376. /*exported CFB */
  1377. /*global Uint8Array:false, Uint16Array:false */
  1378. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  1379. /* vim: set ts=2: */
  1380. /*exported CRC32 */
  1381. var CRC32 = (function() {
  1382. var CRC32 = {};
  1383. CRC32.version = '1.2.0';
  1384. /* see perf/crc32table.js */
  1385. /*global Int32Array */
  1386. function signed_crc_table() {
  1387. var c = 0, table = new Array(256);
  1388. for(var n =0; n != 256; ++n){
  1389. c = n;
  1390. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1391. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1392. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1393. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1394. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1395. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1396. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1397. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  1398. table[n] = c;
  1399. }
  1400. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  1401. }
  1402. var T0 = signed_crc_table();
  1403. function slice_by_16_tables(T) {
  1404. var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ;
  1405. for(n = 0; n != 256; ++n) table[n] = T[n];
  1406. for(n = 0; n != 256; ++n) {
  1407. v = T[n];
  1408. for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF];
  1409. }
  1410. var out = [];
  1411. 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);
  1412. return out;
  1413. }
  1414. var TT = slice_by_16_tables(T0);
  1415. var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4];
  1416. var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9];
  1417. var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];
  1418. function crc32_bstr(bstr, seed) {
  1419. var C = seed ^ -1;
  1420. for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF];
  1421. return ~C;
  1422. }
  1423. function crc32_buf(B, seed) {
  1424. var C = seed ^ -1, L = B.length - 15, i = 0;
  1425. for(; i < L;) C =
  1426. Tf[B[i++] ^ (C & 255)] ^
  1427. Te[B[i++] ^ ((C >> 8) & 255)] ^
  1428. Td[B[i++] ^ ((C >> 16) & 255)] ^
  1429. Tc[B[i++] ^ (C >>> 24)] ^
  1430. Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^
  1431. T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^
  1432. T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];
  1433. L += 15;
  1434. while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF];
  1435. return ~C;
  1436. }
  1437. function crc32_str(str, seed) {
  1438. var C = seed ^ -1;
  1439. for(var i = 0, L = str.length, c = 0, d = 0; i < L;) {
  1440. c = str.charCodeAt(i++);
  1441. if(c < 0x80) {
  1442. C = (C>>>8) ^ T0[(C^c)&0xFF];
  1443. } else if(c < 0x800) {
  1444. C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF];
  1445. C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];
  1446. } else if(c >= 0xD800 && c < 0xE000) {
  1447. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  1448. C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF];
  1449. C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF];
  1450. C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  1451. C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF];
  1452. } else {
  1453. C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF];
  1454. C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF];
  1455. C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];
  1456. }
  1457. }
  1458. return ~C;
  1459. }
  1460. CRC32.table = T0;
  1461. CRC32.bstr = crc32_bstr;
  1462. CRC32.buf = crc32_buf;
  1463. CRC32.str = crc32_str;
  1464. return CRC32;
  1465. })();
  1466. /* [MS-CFB] v20171201 */
  1467. var CFB = (function _CFB(){
  1468. var exports = {};
  1469. exports.version = '1.2.1';
  1470. /* [MS-CFB] 2.6.4 */
  1471. function namecmp(l, r) {
  1472. var L = l.split("/"), R = r.split("/");
  1473. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  1474. if((c = L[i].length - R[i].length)) return c;
  1475. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  1476. }
  1477. return L.length - R.length;
  1478. }
  1479. function dirname(p) {
  1480. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  1481. var c = p.lastIndexOf("/");
  1482. return (c === -1) ? p : p.slice(0, c+1);
  1483. }
  1484. function filename(p) {
  1485. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  1486. var c = p.lastIndexOf("/");
  1487. return (c === -1) ? p : p.slice(c+1);
  1488. }
  1489. /* -------------------------------------------------------------------------- */
  1490. /* DOS Date format:
  1491. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  1492. add 1980 to stored year
  1493. stored second should be doubled
  1494. */
  1495. /* write JS date to buf as a DOS date */
  1496. function write_dos_date(buf, date) {
  1497. if(typeof date === "string") date = new Date(date);
  1498. var hms = date.getHours();
  1499. hms = hms << 6 | date.getMinutes();
  1500. hms = hms << 5 | (date.getSeconds()>>>1);
  1501. buf.write_shift(2, hms);
  1502. var ymd = (date.getFullYear() - 1980);
  1503. ymd = ymd << 4 | (date.getMonth()+1);
  1504. ymd = ymd << 5 | date.getDate();
  1505. buf.write_shift(2, ymd);
  1506. }
  1507. /* read four bytes from buf and interpret as a DOS date */
  1508. function parse_dos_date(buf) {
  1509. var hms = buf.read_shift(2) & 0xFFFF;
  1510. var ymd = buf.read_shift(2) & 0xFFFF;
  1511. var val = new Date();
  1512. var d = ymd & 0x1F; ymd >>>= 5;
  1513. var m = ymd & 0x0F; ymd >>>= 4;
  1514. val.setMilliseconds(0);
  1515. val.setFullYear(ymd + 1980);
  1516. val.setMonth(m-1);
  1517. val.setDate(d);
  1518. var S = hms & 0x1F; hms >>>= 5;
  1519. var M = hms & 0x3F; hms >>>= 6;
  1520. val.setHours(hms);
  1521. val.setMinutes(M);
  1522. val.setSeconds(S<<1);
  1523. return val;
  1524. }
  1525. function parse_extra_field(blob) {
  1526. prep_blob(blob, 0);
  1527. var o = {};
  1528. var flags = 0;
  1529. while(blob.l <= blob.length - 4) {
  1530. var type = blob.read_shift(2);
  1531. var sz = blob.read_shift(2), tgt = blob.l + sz;
  1532. var p = {};
  1533. switch(type) {
  1534. /* UNIX-style Timestamps */
  1535. case 0x5455: {
  1536. flags = blob.read_shift(1);
  1537. if(flags & 1) p.mtime = blob.read_shift(4);
  1538. /* for some reason, CD flag corresponds to LFH */
  1539. if(sz > 5) {
  1540. if(flags & 2) p.atime = blob.read_shift(4);
  1541. if(flags & 4) p.ctime = blob.read_shift(4);
  1542. }
  1543. if(p.mtime) p.mt = new Date(p.mtime*1000);
  1544. }
  1545. break;
  1546. }
  1547. blob.l = tgt;
  1548. o[type] = p;
  1549. }
  1550. return o;
  1551. }
  1552. var fs;
  1553. function get_fs() { return fs || (fs = undefined); }
  1554. function parse(file, options) {
  1555. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  1556. if((file[0] | 0x20) == 0x6d && (file[1]|0x20) == 0x69) return parse_mad(file, options);
  1557. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  1558. var mver = 3;
  1559. var ssz = 512;
  1560. var nmfs = 0; // number of mini FAT sectors
  1561. var difat_sec_cnt = 0;
  1562. var dir_start = 0;
  1563. var minifat_start = 0;
  1564. var difat_start = 0;
  1565. var fat_addrs = []; // locations of FAT sectors
  1566. /* [MS-CFB] 2.2 Compound File Header */
  1567. var blob = file.slice(0,512);
  1568. prep_blob(blob, 0);
  1569. /* major version */
  1570. var mv = check_get_mver(blob);
  1571. mver = mv[0];
  1572. switch(mver) {
  1573. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  1574. case 0: if(mv[1] == 0) return parse_zip(file, options);
  1575. /* falls through */
  1576. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  1577. }
  1578. /* reprocess header */
  1579. if(ssz !== 512) { blob = file.slice(0,ssz); prep_blob(blob, 28 /* blob.l */); }
  1580. /* Save header for final object */
  1581. var header = file.slice(0,ssz);
  1582. check_shifts(blob, mver);
  1583. // Number of Directory Sectors
  1584. var dir_cnt = blob.read_shift(4, 'i');
  1585. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  1586. // Number of FAT Sectors
  1587. blob.l += 4;
  1588. // First Directory Sector Location
  1589. dir_start = blob.read_shift(4, 'i');
  1590. // Transaction Signature
  1591. blob.l += 4;
  1592. // Mini Stream Cutoff Size
  1593. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  1594. // First Mini FAT Sector Location
  1595. minifat_start = blob.read_shift(4, 'i');
  1596. // Number of Mini FAT Sectors
  1597. nmfs = blob.read_shift(4, 'i');
  1598. // First DIFAT sector location
  1599. difat_start = blob.read_shift(4, 'i');
  1600. // Number of DIFAT Sectors
  1601. difat_sec_cnt = blob.read_shift(4, 'i');
  1602. // Grab FAT Sector Locations
  1603. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  1604. q = blob.read_shift(4, 'i');
  1605. if(q<0) break;
  1606. fat_addrs[j] = q;
  1607. }
  1608. /** Break the file up into sectors */
  1609. var sectors = sectorify(file, ssz);
  1610. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  1611. /** Chains */
  1612. var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  1613. sector_list[dir_start].name = "!Directory";
  1614. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  1615. sector_list[fat_addrs[0]].name = "!FAT";
  1616. sector_list.fat_addrs = fat_addrs;
  1617. sector_list.ssz = ssz;
  1618. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  1619. var files = {}, Paths = [], FileIndex = [], FullPaths = [];
  1620. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  1621. build_full_paths(FileIndex, FullPaths, Paths);
  1622. Paths.shift();
  1623. var o = {
  1624. FileIndex: FileIndex,
  1625. FullPaths: FullPaths
  1626. };
  1627. // $FlowIgnore
  1628. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  1629. return o;
  1630. } // parse
  1631. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  1632. function check_get_mver(blob) {
  1633. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  1634. // header signature 8
  1635. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  1636. // clsid 16
  1637. //blob.chk(HEADER_CLSID, 'CLSID: ');
  1638. blob.l += 16;
  1639. // minor version 2
  1640. var mver = blob.read_shift(2, 'u');
  1641. return [blob.read_shift(2,'u'), mver];
  1642. }
  1643. function check_shifts(blob, mver) {
  1644. var shift = 0x09;
  1645. // Byte Order
  1646. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  1647. blob.l += 2;
  1648. // Sector Shift
  1649. switch((shift = blob.read_shift(2))) {
  1650. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  1651. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  1652. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  1653. }
  1654. // Mini Sector Shift
  1655. blob.chk('0600', 'Mini Sector Shift: ');
  1656. // Reserved
  1657. blob.chk('000000000000', 'Reserved: ');
  1658. }
  1659. /** Break the file up into sectors */
  1660. function sectorify(file, ssz) {
  1661. var nsectors = Math.ceil(file.length/ssz)-1;
  1662. var sectors = [];
  1663. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  1664. sectors[nsectors-1] = file.slice(nsectors*ssz);
  1665. return sectors;
  1666. }
  1667. /* [MS-CFB] 2.6.4 Red-Black Tree */
  1668. function build_full_paths(FI, FP, Paths) {
  1669. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  1670. var dad = [], q = [];
  1671. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  1672. for(; j < q.length; ++j) {
  1673. i = q[j];
  1674. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  1675. if(dad[i] === i) {
  1676. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  1677. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  1678. }
  1679. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  1680. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  1681. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  1682. }
  1683. for(i=1; i < pl; ++i) if(dad[i] === i) {
  1684. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  1685. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  1686. }
  1687. for(i=1; i < pl; ++i) {
  1688. if(FI[i].type === 0 /* unknown */) continue;
  1689. j = i;
  1690. if(j != dad[j]) do {
  1691. j = dad[j];
  1692. FP[i] = FP[j] + "/" + FP[i];
  1693. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  1694. dad[i] = -1;
  1695. }
  1696. FP[0] += "/";
  1697. for(i=1; i < pl; ++i) {
  1698. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  1699. }
  1700. }
  1701. function get_mfat_entry(entry, payload, mini) {
  1702. var start = entry.start, size = entry.size;
  1703. //return (payload.slice(start*MSSZ, start*MSSZ + size));
  1704. var o = [];
  1705. var idx = start;
  1706. while(mini && size > 0 && idx >= 0) {
  1707. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  1708. size -= MSSZ;
  1709. idx = __readInt32LE(mini, idx * 4);
  1710. }
  1711. if(o.length === 0) return (new_buf(0));
  1712. return (bconcat(o).slice(0, entry.size));
  1713. }
  1714. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  1715. DIFAT chains by storing the next sector number as the last 32 bits */
  1716. function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
  1717. var q = ENDOFCHAIN;
  1718. if(idx === ENDOFCHAIN) {
  1719. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  1720. } else if(idx !== -1 /*FREESECT*/) {
  1721. var sector = sectors[idx], m = (ssz>>>2)-1;
  1722. if(!sector) return;
  1723. for(var i = 0; i < m; ++i) {
  1724. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  1725. fat_addrs.push(q);
  1726. }
  1727. sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  1728. }
  1729. }
  1730. /** Follow the linked list of sectors for a given starting point */
  1731. function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
  1732. var buf = [], buf_chain = [];
  1733. if(!chkd) chkd = [];
  1734. var modulus = ssz - 1, j = 0, jj = 0;
  1735. for(j=start; j>=0;) {
  1736. chkd[j] = true;
  1737. buf[buf.length] = j;
  1738. buf_chain.push(sectors[j]);
  1739. var addr = fat_addrs[Math.floor(j*4/ssz)];
  1740. jj = ((j*4) & modulus);
  1741. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  1742. if(!sectors[addr]) break;
  1743. j = __readInt32LE(sectors[addr], jj);
  1744. }
  1745. return {nodes: buf, data:__toBuffer([buf_chain])};
  1746. }
  1747. /** Chase down the sector linked lists */
  1748. function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
  1749. var sl = sectors.length, sector_list = ([]);
  1750. var chkd = [], buf = [], buf_chain = [];
  1751. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  1752. for(i=0; i < sl; ++i) {
  1753. buf = ([]);
  1754. k = (i + dir_start); if(k >= sl) k-=sl;
  1755. if(chkd[k]) continue;
  1756. buf_chain = [];
  1757. var seen = [];
  1758. for(j=k; j>=0;) {
  1759. seen[j] = true;
  1760. chkd[j] = true;
  1761. buf[buf.length] = j;
  1762. buf_chain.push(sectors[j]);
  1763. var addr = fat_addrs[Math.floor(j*4/ssz)];
  1764. jj = ((j*4) & modulus);
  1765. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  1766. if(!sectors[addr]) break;
  1767. j = __readInt32LE(sectors[addr], jj);
  1768. if(seen[j]) break;
  1769. }
  1770. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])});
  1771. }
  1772. return sector_list;
  1773. }
  1774. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  1775. function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
  1776. var minifat_store = 0, pl = (Paths.length?2:0);
  1777. var sector = sector_list[dir_start].data;
  1778. var i = 0, namelen = 0, name;
  1779. for(; i < sector.length; i+= 128) {
  1780. var blob = sector.slice(i, i+128);
  1781. prep_blob(blob, 64);
  1782. namelen = blob.read_shift(2);
  1783. name = __utf16le(blob,0,namelen-pl);
  1784. Paths.push(name);
  1785. var o = ({
  1786. name: name,
  1787. type: blob.read_shift(1),
  1788. color: blob.read_shift(1),
  1789. L: blob.read_shift(4, 'i'),
  1790. R: blob.read_shift(4, 'i'),
  1791. C: blob.read_shift(4, 'i'),
  1792. clsid: blob.read_shift(16),
  1793. state: blob.read_shift(4, 'i'),
  1794. start: 0,
  1795. size: 0
  1796. });
  1797. var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  1798. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  1799. var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  1800. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  1801. o.start = blob.read_shift(4, 'i');
  1802. o.size = blob.read_shift(4, 'i');
  1803. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  1804. if(o.type === 5) { /* root */
  1805. minifat_store = o.start;
  1806. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  1807. /*minifat_size = o.size;*/
  1808. } else if(o.size >= 4096 /* MSCSZ */) {
  1809. o.storage = 'fat';
  1810. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  1811. sector_list[o.start].name = o.name;
  1812. o.content = (sector_list[o.start].data.slice(0,o.size));
  1813. } else {
  1814. o.storage = 'minifat';
  1815. if(o.size < 0) o.size = 0;
  1816. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  1817. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  1818. }
  1819. }
  1820. if(o.content) prep_blob(o.content, 0);
  1821. files[name] = o;
  1822. FileIndex.push(o);
  1823. }
  1824. }
  1825. function read_date(blob, offset) {
  1826. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  1827. }
  1828. function read_file(filename, options) {
  1829. get_fs();
  1830. return parse(fs.readFileSync(filename), options);
  1831. }
  1832. function read(blob, options) {
  1833. var type = options && options.type;
  1834. if(!type) {
  1835. if(has_buf && Buffer.isBuffer(blob)) type = "buffer";
  1836. }
  1837. switch(type || "base64") {
  1838. case "file": return read_file(blob, options);
  1839. case "base64": return parse(s2a(Base64_decode(blob)), options);
  1840. case "binary": return parse(s2a(blob), options);
  1841. }
  1842. return parse(blob, options);
  1843. }
  1844. function init_cfb(cfb, opts) {
  1845. var o = opts || {}, root = o.root || "Root Entry";
  1846. if(!cfb.FullPaths) cfb.FullPaths = [];
  1847. if(!cfb.FileIndex) cfb.FileIndex = [];
  1848. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  1849. if(cfb.FullPaths.length === 0) {
  1850. cfb.FullPaths[0] = root + "/";
  1851. cfb.FileIndex[0] = ({ name: root, type: 5 });
  1852. }
  1853. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  1854. seed_cfb(cfb);
  1855. }
  1856. function seed_cfb(cfb) {
  1857. var nm = "\u0001Sh33tJ5";
  1858. if(CFB.find(cfb, "/" + nm)) return;
  1859. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  1860. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }));
  1861. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  1862. rebuild_cfb(cfb);
  1863. }
  1864. function rebuild_cfb(cfb, f) {
  1865. init_cfb(cfb);
  1866. var gc = false, s = false;
  1867. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  1868. var _file = cfb.FileIndex[i];
  1869. switch(_file.type) {
  1870. case 0:
  1871. if(s) gc = true;
  1872. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  1873. break;
  1874. case 1: case 2: case 5:
  1875. s = true;
  1876. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  1877. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  1878. break;
  1879. default: gc = true; break;
  1880. }
  1881. }
  1882. if(!gc && !f) return;
  1883. var now = new Date(1987, 1, 19), j = 0;
  1884. // Track which names exist
  1885. var fullPaths = Object.create ? Object.create(null) : {};
  1886. var data = [];
  1887. for(i = 0; i < cfb.FullPaths.length; ++i) {
  1888. fullPaths[cfb.FullPaths[i]] = true;
  1889. if(cfb.FileIndex[i].type === 0) continue;
  1890. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  1891. }
  1892. for(i = 0; i < data.length; ++i) {
  1893. var dad = dirname(data[i][0]);
  1894. s = fullPaths[dad];
  1895. if(!s) {
  1896. data.push([dad, ({
  1897. name: filename(dad).replace("/",""),
  1898. type: 1,
  1899. clsid: HEADER_CLSID,
  1900. ct: now, mt: now,
  1901. content: null
  1902. })]);
  1903. // Add name to set
  1904. fullPaths[dad] = true;
  1905. }
  1906. }
  1907. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  1908. cfb.FullPaths = []; cfb.FileIndex = [];
  1909. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  1910. for(i = 0; i < data.length; ++i) {
  1911. var elt = cfb.FileIndex[i];
  1912. var nm = cfb.FullPaths[i];
  1913. elt.name = filename(nm).replace("/","");
  1914. elt.L = elt.R = elt.C = -(elt.color = 1);
  1915. elt.size = elt.content ? elt.content.length : 0;
  1916. elt.start = 0;
  1917. elt.clsid = (elt.clsid || HEADER_CLSID);
  1918. if(i === 0) {
  1919. elt.C = data.length > 1 ? 1 : -1;
  1920. elt.size = 0;
  1921. elt.type = 5;
  1922. } else if(nm.slice(-1) == "/") {
  1923. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  1924. elt.C = j >= data.length ? -1 : j;
  1925. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  1926. elt.R = j >= data.length ? -1 : j;
  1927. elt.type = 1;
  1928. } else {
  1929. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  1930. elt.type = 2;
  1931. }
  1932. }
  1933. }
  1934. function _write(cfb, options) {
  1935. var _opts = options || {};
  1936. /* MAD is order-sensitive, skip rebuild and sort */
  1937. if(_opts.fileType == 'mad') return write_mad(cfb, _opts);
  1938. rebuild_cfb(cfb);
  1939. switch(_opts.fileType) {
  1940. case 'zip': return write_zip(cfb, _opts);
  1941. //case 'mad': return write_mad(cfb, _opts);
  1942. }
  1943. var L = (function(cfb){
  1944. var mini_size = 0, fat_size = 0;
  1945. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  1946. var file = cfb.FileIndex[i];
  1947. if(!file.content) continue;
  1948. var flen = file.content.length;
  1949. if(flen > 0){
  1950. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  1951. else fat_size += (flen + 0x01FF) >> 9;
  1952. }
  1953. }
  1954. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  1955. var mini_cnt = (mini_size + 7) >> 3;
  1956. var mfat_cnt = (mini_size + 0x7F) >> 7;
  1957. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  1958. var fat_cnt = (fat_base + 0x7F) >> 7;
  1959. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  1960. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  1961. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  1962. cfb.FileIndex[0].size = mini_size << 6;
  1963. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  1964. return L;
  1965. })(cfb);
  1966. var o = new_buf(L[7] << 9);
  1967. var i = 0, T = 0;
  1968. {
  1969. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  1970. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  1971. o.write_shift(2, 0x003E);
  1972. o.write_shift(2, 0x0003);
  1973. o.write_shift(2, 0xFFFE);
  1974. o.write_shift(2, 0x0009);
  1975. o.write_shift(2, 0x0006);
  1976. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  1977. o.write_shift(4, 0);
  1978. o.write_shift(4, L[2]);
  1979. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  1980. o.write_shift(4, 0);
  1981. o.write_shift(4, 1<<12);
  1982. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  1983. o.write_shift(4, L[3]);
  1984. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  1985. o.write_shift(4, L[1]);
  1986. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  1987. }
  1988. if(L[1]) {
  1989. for(T = 0; T < L[1]; ++T) {
  1990. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  1991. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  1992. }
  1993. }
  1994. var chainit = function(w) {
  1995. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  1996. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  1997. };
  1998. T = i = 0;
  1999. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  2000. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  2001. chainit(L[3]);
  2002. chainit(L[4]);
  2003. var j = 0, flen = 0;
  2004. var file = cfb.FileIndex[0];
  2005. for(; j < cfb.FileIndex.length; ++j) {
  2006. file = cfb.FileIndex[j];
  2007. if(!file.content) continue;
  2008. flen = file.content.length;
  2009. if(flen < 0x1000) continue;
  2010. file.start = T;
  2011. chainit((flen + 0x01FF) >> 9);
  2012. }
  2013. chainit((L[6] + 7) >> 3);
  2014. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  2015. T = i = 0;
  2016. for(j = 0; j < cfb.FileIndex.length; ++j) {
  2017. file = cfb.FileIndex[j];
  2018. if(!file.content) continue;
  2019. flen = file.content.length;
  2020. if(!flen || flen >= 0x1000) continue;
  2021. file.start = T;
  2022. chainit((flen + 0x3F) >> 6);
  2023. }
  2024. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  2025. for(i = 0; i < L[4]<<2; ++i) {
  2026. var nm = cfb.FullPaths[i];
  2027. if(!nm || nm.length === 0) {
  2028. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  2029. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  2030. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  2031. continue;
  2032. }
  2033. file = cfb.FileIndex[i];
  2034. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  2035. var _nm = (i === 0 && _opts.root) || file.name;
  2036. flen = 2*(_nm.length+1);
  2037. o.write_shift(64, _nm, "utf16le");
  2038. o.write_shift(2, flen);
  2039. o.write_shift(1, file.type);
  2040. o.write_shift(1, file.color);
  2041. o.write_shift(-4, file.L);
  2042. o.write_shift(-4, file.R);
  2043. o.write_shift(-4, file.C);
  2044. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  2045. else o.write_shift(16, file.clsid, "hex");
  2046. o.write_shift(4, file.state || 0);
  2047. o.write_shift(4, 0); o.write_shift(4, 0);
  2048. o.write_shift(4, 0); o.write_shift(4, 0);
  2049. o.write_shift(4, file.start);
  2050. o.write_shift(4, file.size); o.write_shift(4, 0);
  2051. }
  2052. for(i = 1; i < cfb.FileIndex.length; ++i) {
  2053. file = cfb.FileIndex[i];
  2054. if(file.size >= 0x1000) {
  2055. o.l = (file.start+1) << 9;
  2056. if (has_buf && Buffer.isBuffer(file.content)) {
  2057. file.content.copy(o, o.l, 0, file.size);
  2058. // o is a 0-filled Buffer so just set next offset
  2059. o.l += (file.size + 511) & -512;
  2060. } else {
  2061. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  2062. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  2063. }
  2064. }
  2065. }
  2066. for(i = 1; i < cfb.FileIndex.length; ++i) {
  2067. file = cfb.FileIndex[i];
  2068. if(file.size > 0 && file.size < 0x1000) {
  2069. if (has_buf && Buffer.isBuffer(file.content)) {
  2070. file.content.copy(o, o.l, 0, file.size);
  2071. // o is a 0-filled Buffer so just set next offset
  2072. o.l += (file.size + 63) & -64;
  2073. } else {
  2074. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  2075. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  2076. }
  2077. }
  2078. }
  2079. if (has_buf) {
  2080. o.l = o.length;
  2081. } else {
  2082. // When using Buffer, already 0-filled
  2083. while(o.l < o.length) o.write_shift(1, 0);
  2084. }
  2085. return o;
  2086. }
  2087. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  2088. function find(cfb, path) {
  2089. var UCFullPaths = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  2090. var UCPaths = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  2091. var k = false;
  2092. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  2093. else k = path.indexOf("/") !== -1;
  2094. var UCPath = path.toUpperCase();
  2095. var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  2096. if(w !== -1) return cfb.FileIndex[w];
  2097. var m = !UCPath.match(chr1);
  2098. UCPath = UCPath.replace(chr0,'');
  2099. if(m) UCPath = UCPath.replace(chr1,'!');
  2100. for(w = 0; w < UCFullPaths.length; ++w) {
  2101. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  2102. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  2103. }
  2104. return null;
  2105. }
  2106. /** CFB Constants */
  2107. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  2108. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  2109. /* 2.1 Compound File Sector Numbers and Types */
  2110. var ENDOFCHAIN = -2;
  2111. /* 2.2 Compound File Header */
  2112. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  2113. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  2114. var HEADER_CLSID = '00000000000000000000000000000000';
  2115. var consts = {
  2116. /* 2.1 Compund File Sector Numbers and Types */
  2117. MAXREGSECT: -6,
  2118. DIFSECT: -4,
  2119. FATSECT: -3,
  2120. ENDOFCHAIN: ENDOFCHAIN,
  2121. FREESECT: -1,
  2122. /* 2.2 Compound File Header */
  2123. HEADER_SIGNATURE: HEADER_SIGNATURE,
  2124. HEADER_MINOR_VERSION: '3e00',
  2125. MAXREGSID: -6,
  2126. NOSTREAM: -1,
  2127. HEADER_CLSID: HEADER_CLSID,
  2128. /* 2.6.1 Compound File Directory Entry */
  2129. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  2130. };
  2131. function write_file(cfb, filename, options) {
  2132. get_fs();
  2133. var o = _write(cfb, options);
  2134. fs.writeFileSync(filename, o);
  2135. }
  2136. function a2s(o) {
  2137. var out = new Array(o.length);
  2138. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  2139. return out.join("");
  2140. }
  2141. function write(cfb, options) {
  2142. var o = _write(cfb, options);
  2143. switch(options && options.type || "buffer") {
  2144. case "file": get_fs(); fs.writeFileSync(options.filename, (o)); return o;
  2145. case "binary": return typeof o == "string" ? o : a2s(o);
  2146. case "base64": return Base64_encode(typeof o == "string" ? o : a2s(o));
  2147. case "buffer": if(has_buf) return Buffer.isBuffer(o) ? o : Buffer_from(o);
  2148. /* falls through */
  2149. case "array": return typeof o == "string" ? s2a(o) : o;
  2150. }
  2151. return o;
  2152. }
  2153. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  2154. var _zlib;
  2155. function use_zlib(zlib) { try {
  2156. var InflateRaw = zlib.InflateRaw;
  2157. var InflRaw = new InflateRaw();
  2158. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  2159. if(InflRaw.bytesRead) _zlib = zlib;
  2160. else throw new Error("zlib does not expose bytesRead");
  2161. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  2162. function _inflateRawSync(payload, usz) {
  2163. if(!_zlib) return _inflate(payload, usz);
  2164. var InflateRaw = _zlib.InflateRaw;
  2165. var InflRaw = new InflateRaw();
  2166. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  2167. payload.l += InflRaw.bytesRead;
  2168. return out;
  2169. }
  2170. function _deflateRawSync(payload) {
  2171. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  2172. }
  2173. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  2174. /* 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 ]; */
  2175. 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 ];
  2176. /* 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 ]; */
  2177. 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 ];
  2178. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  2179. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  2180. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  2181. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  2182. function bit_swap_n(n, b) {
  2183. var rev = bitswap8[n & 0xFF];
  2184. if(b <= 8) return rev >>> (8-b);
  2185. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  2186. if(b <= 16) return rev >>> (16-b);
  2187. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  2188. return rev >>> (24-b);
  2189. }
  2190. /* helpers for unaligned bit reads */
  2191. 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; }
  2192. 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; }
  2193. 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; }
  2194. 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; }
  2195. 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; }
  2196. /* works up to n = 3 * 8 + 1 = 25 */
  2197. function read_bits_n(buf, bl, n) {
  2198. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  2199. var v = buf[h] >>> w;
  2200. if(n < 8 - w) return v & f;
  2201. v |= buf[h+1]<<(8-w);
  2202. if(n < 16 - w) return v & f;
  2203. v |= buf[h+2]<<(16-w);
  2204. if(n < 24 - w) return v & f;
  2205. v |= buf[h+3]<<(24-w);
  2206. return v & f;
  2207. }
  2208. /* helpers for unaligned bit writes */
  2209. function write_bits_3(buf, bl, v) { var w = bl & 7, h = bl >>> 3;
  2210. if(w <= 5) buf[h] |= (v & 7) << w;
  2211. else {
  2212. buf[h] |= (v << w) & 0xFF;
  2213. buf[h+1] = (v&7) >> (8-w);
  2214. }
  2215. return bl + 3;
  2216. }
  2217. function write_bits_1(buf, bl, v) {
  2218. var w = bl & 7, h = bl >>> 3;
  2219. v = (v&1) << w;
  2220. buf[h] |= v;
  2221. return bl + 1;
  2222. }
  2223. function write_bits_8(buf, bl, v) {
  2224. var w = bl & 7, h = bl >>> 3;
  2225. v <<= w;
  2226. buf[h] |= v & 0xFF; v >>>= 8;
  2227. buf[h+1] = v;
  2228. return bl + 8;
  2229. }
  2230. function write_bits_16(buf, bl, v) {
  2231. var w = bl & 7, h = bl >>> 3;
  2232. v <<= w;
  2233. buf[h] |= v & 0xFF; v >>>= 8;
  2234. buf[h+1] = v & 0xFF;
  2235. buf[h+2] = v >>> 8;
  2236. return bl + 16;
  2237. }
  2238. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  2239. function realloc(b, sz) {
  2240. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  2241. if(L >= sz) return b;
  2242. if(has_buf) {
  2243. var o = new_unsafe_buf(M);
  2244. // $FlowIgnore
  2245. if(b.copy) b.copy(o);
  2246. else for(; i < b.length; ++i) o[i] = b[i];
  2247. return o;
  2248. } else if(use_typed_arrays) {
  2249. var a = new Uint8Array(M);
  2250. if(a.set) a.set(b);
  2251. else for(; i < L; ++i) a[i] = b[i];
  2252. return a;
  2253. }
  2254. b.length = M;
  2255. return b;
  2256. }
  2257. /* zero-filled arrays for older browsers */
  2258. function zero_fill_array(n) {
  2259. var o = new Array(n);
  2260. for(var i = 0; i < n; ++i) o[i] = 0;
  2261. return o;
  2262. }
  2263. /* build tree (used for literals and lengths) */
  2264. function build_tree(clens, cmap, MAX) {
  2265. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  2266. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  2267. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  2268. for(i = L; i < MAX; ++i) clens[i] = 0;
  2269. L = clens.length;
  2270. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  2271. /* build code tree */
  2272. for(i = 0; i < L; ++i) {
  2273. bl_count[(w = clens[i])]++;
  2274. if(maxlen < w) maxlen = w;
  2275. ctree[i] = 0;
  2276. }
  2277. bl_count[0] = 0;
  2278. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  2279. for(i = 0; i < L; ++i) {
  2280. ccode = clens[i];
  2281. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  2282. }
  2283. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  2284. var cleni = 0;
  2285. for(i = 0; i < L; ++i) {
  2286. cleni = clens[i];
  2287. if(cleni != 0) {
  2288. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  2289. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  2290. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  2291. }
  2292. }
  2293. return maxlen;
  2294. }
  2295. /* Fixed Huffman */
  2296. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  2297. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  2298. if(!use_typed_arrays) {
  2299. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  2300. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  2301. }
  2302. (function() {
  2303. var dlens = [];
  2304. var i = 0;
  2305. for(;i<32; i++) dlens.push(5);
  2306. build_tree(dlens, fix_dmap, 32);
  2307. var clens = [];
  2308. i = 0;
  2309. for(; i<=143; i++) clens.push(8);
  2310. for(; i<=255; i++) clens.push(9);
  2311. for(; i<=279; i++) clens.push(7);
  2312. for(; i<=287; i++) clens.push(8);
  2313. build_tree(clens, fix_lmap, 288);
  2314. })();var _deflateRaw = (function _deflateRawIIFE() {
  2315. var DST_LN_RE = use_typed_arrays ? new Uint8Array(0x8000) : [];
  2316. var j = 0, k = 0;
  2317. for(; j < DST_LN.length - 1; ++j) {
  2318. for(; k < DST_LN[j+1]; ++k) DST_LN_RE[k] = j;
  2319. }
  2320. for(;k < 32768; ++k) DST_LN_RE[k] = 29;
  2321. var LEN_LN_RE = use_typed_arrays ? new Uint8Array(0x103) : [];
  2322. for(j = 0, k = 0; j < LEN_LN.length - 1; ++j) {
  2323. for(; k < LEN_LN[j+1]; ++k) LEN_LN_RE[k] = j;
  2324. }
  2325. function write_stored(data, out) {
  2326. var boff = 0;
  2327. while(boff < data.length) {
  2328. var L = Math.min(0xFFFF, data.length - boff);
  2329. var h = boff + L == data.length;
  2330. out.write_shift(1, +h);
  2331. out.write_shift(2, L);
  2332. out.write_shift(2, (~L) & 0xFFFF);
  2333. while(L-- > 0) out[out.l++] = data[boff++];
  2334. }
  2335. return out.l;
  2336. }
  2337. /* Fixed Huffman */
  2338. function write_huff_fixed(data, out) {
  2339. var bl = 0;
  2340. var boff = 0;
  2341. var addrs = use_typed_arrays ? new Uint16Array(0x8000) : [];
  2342. while(boff < data.length) {
  2343. var L = /* data.length - boff; */ Math.min(0xFFFF, data.length - boff);
  2344. /* write a stored block for short data */
  2345. if(L < 10) {
  2346. bl = write_bits_3(out, bl, +!!(boff + L == data.length)); // jshint ignore:line
  2347. if(bl & 7) bl += 8 - (bl & 7);
  2348. out.l = (bl / 8) | 0;
  2349. out.write_shift(2, L);
  2350. out.write_shift(2, (~L) & 0xFFFF);
  2351. while(L-- > 0) out[out.l++] = data[boff++];
  2352. bl = out.l * 8;
  2353. continue;
  2354. }
  2355. bl = write_bits_3(out, bl, +!!(boff + L == data.length) + 2); // jshint ignore:line
  2356. var hash = 0;
  2357. while(L-- > 0) {
  2358. var d = data[boff];
  2359. hash = ((hash << 5) ^ d) & 0x7FFF;
  2360. var match = -1, mlen = 0;
  2361. if((match = addrs[hash])) {
  2362. match |= boff & ~0x7FFF;
  2363. if(match > boff) match -= 0x8000;
  2364. if(match < boff) while(data[match + mlen] == data[boff + mlen] && mlen < 250) ++mlen;
  2365. }
  2366. if(mlen > 2) {
  2367. /* Copy Token */
  2368. d = LEN_LN_RE[mlen];
  2369. if(d <= 22) bl = write_bits_8(out, bl, bitswap8[d+1]>>1) - 1;
  2370. else {
  2371. write_bits_8(out, bl, 3);
  2372. bl += 5;
  2373. write_bits_8(out, bl, bitswap8[d-23]>>5);
  2374. bl += 3;
  2375. }
  2376. var len_eb = (d < 8) ? 0 : ((d - 4)>>2);
  2377. if(len_eb > 0) {
  2378. write_bits_16(out, bl, mlen - LEN_LN[d]);
  2379. bl += len_eb;
  2380. }
  2381. d = DST_LN_RE[boff - match];
  2382. bl = write_bits_8(out, bl, bitswap8[d]>>3);
  2383. bl -= 3;
  2384. var dst_eb = d < 4 ? 0 : (d-2)>>1;
  2385. if(dst_eb > 0) {
  2386. write_bits_16(out, bl, boff - match - DST_LN[d]);
  2387. bl += dst_eb;
  2388. }
  2389. for(var q = 0; q < mlen; ++q) {
  2390. addrs[hash] = boff & 0x7FFF;
  2391. hash = ((hash << 5) ^ data[boff]) & 0x7FFF;
  2392. ++boff;
  2393. }
  2394. L-= mlen - 1;
  2395. } else {
  2396. /* Literal Token */
  2397. if(d <= 143) d = d + 48;
  2398. else bl = write_bits_1(out, bl, 1);
  2399. bl = write_bits_8(out, bl, bitswap8[d]);
  2400. addrs[hash] = boff & 0x7FFF;
  2401. ++boff;
  2402. }
  2403. }
  2404. bl = write_bits_8(out, bl, 0) - 1;
  2405. }
  2406. out.l = ((bl + 7)/8)|0;
  2407. return out.l;
  2408. }
  2409. return function _deflateRaw(data, out) {
  2410. if(data.length < 8) return write_stored(data, out);
  2411. return write_huff_fixed(data, out);
  2412. };
  2413. })();
  2414. function _deflate(data) {
  2415. var buf = new_buf(50+Math.floor(data.length*1.1));
  2416. var off = _deflateRaw(data, buf);
  2417. return buf.slice(0, off);
  2418. }
  2419. /* modified inflate function also moves original read head */
  2420. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  2421. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  2422. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  2423. var dyn_len_1 = 1, dyn_len_2 = 1;
  2424. /* 5.5.3 Expanding Huffman Codes */
  2425. function dyn(data, boff) {
  2426. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  2427. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  2428. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  2429. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  2430. var w = 0;
  2431. /* grab and store code lengths */
  2432. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  2433. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  2434. var maxlen = 1;
  2435. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  2436. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  2437. var L = clens.length; /* 19 */
  2438. for(var i = 0; i < _HCLEN; ++i) {
  2439. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  2440. if(maxlen < w) maxlen = w;
  2441. bl_count[w]++;
  2442. boff += 3;
  2443. }
  2444. /* build code tree */
  2445. var ccode = 0;
  2446. bl_count[0] = 0;
  2447. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  2448. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  2449. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  2450. var cleni = 0;
  2451. for(i = 0; i < L; ++i) {
  2452. cleni = clens[i];
  2453. if(cleni != 0) {
  2454. ccode = bitswap8[ctree[i]]>>(8-cleni);
  2455. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  2456. }
  2457. }
  2458. /* read literal and dist codes at once */
  2459. var hcodes = [];
  2460. maxlen = 1;
  2461. for(; hcodes.length < _HLIT + _HDIST;) {
  2462. ccode = dyn_cmap[read_bits_7(data, boff)];
  2463. boff += ccode & 7;
  2464. switch((ccode >>>= 3)) {
  2465. case 16:
  2466. w = 3 + read_bits_2(data, boff); boff += 2;
  2467. ccode = hcodes[hcodes.length - 1];
  2468. while(w-- > 0) hcodes.push(ccode);
  2469. break;
  2470. case 17:
  2471. w = 3 + read_bits_3(data, boff); boff += 3;
  2472. while(w-- > 0) hcodes.push(0);
  2473. break;
  2474. case 18:
  2475. w = 11 + read_bits_7(data, boff); boff += 7;
  2476. while(w -- > 0) hcodes.push(0);
  2477. break;
  2478. default:
  2479. hcodes.push(ccode);
  2480. if(maxlen < ccode) maxlen = ccode;
  2481. break;
  2482. }
  2483. }
  2484. /* build literal / length trees */
  2485. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  2486. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  2487. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  2488. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  2489. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  2490. return boff;
  2491. }
  2492. /* return [ data, bytesRead ] */
  2493. function inflate(data, usz) {
  2494. /* shortcircuit for empty buffer [0x03, 0x00] */
  2495. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  2496. /* bit offset */
  2497. var boff = 0;
  2498. /* header includes final bit and type bits */
  2499. var header = 0;
  2500. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  2501. var woff = 0;
  2502. var OL = outbuf.length>>>0;
  2503. var max_len_1 = 0, max_len_2 = 0;
  2504. while((header&1) == 0) {
  2505. header = read_bits_3(data, boff); boff += 3;
  2506. if((header >>> 1) == 0) {
  2507. /* Stored block */
  2508. if(boff & 7) boff += 8 - (boff&7);
  2509. /* 2 bytes sz, 2 bytes bit inverse */
  2510. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  2511. boff += 32;
  2512. /* push sz bytes */
  2513. if(sz > 0) {
  2514. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  2515. while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  2516. }
  2517. continue;
  2518. } else if((header >> 1) == 1) {
  2519. /* Fixed Huffman */
  2520. max_len_1 = 9; max_len_2 = 5;
  2521. } else {
  2522. /* Dynamic Huffman */
  2523. boff = dyn(data, boff);
  2524. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  2525. }
  2526. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  2527. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  2528. /* ingest code and move read head */
  2529. var bits = read_bits_n(data, boff, max_len_1);
  2530. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  2531. boff += code & 15; code >>>= 4;
  2532. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  2533. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  2534. else if(code == 256) break;
  2535. else {
  2536. code -= 257;
  2537. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  2538. var tgt = woff + LEN_LN[code];
  2539. /* length extra bits */
  2540. if(len_eb > 0) {
  2541. tgt += read_bits_n(data, boff, len_eb);
  2542. boff += len_eb;
  2543. }
  2544. /* dist code */
  2545. bits = read_bits_n(data, boff, max_len_2);
  2546. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  2547. boff += code & 15; code >>>= 4;
  2548. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  2549. var dst = DST_LN[code];
  2550. /* dist extra bits */
  2551. if(dst_eb > 0) {
  2552. dst += read_bits_n(data, boff, dst_eb);
  2553. boff += dst_eb;
  2554. }
  2555. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  2556. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt + 100); OL = outbuf.length; }
  2557. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  2558. }
  2559. }
  2560. }
  2561. if(usz) return [outbuf, (boff+7)>>>3];
  2562. return [outbuf.slice(0, woff), (boff+7)>>>3];
  2563. }
  2564. function _inflate(payload, usz) {
  2565. var data = payload.slice(payload.l||0);
  2566. var out = inflate(data, usz);
  2567. payload.l += out[1];
  2568. return out[0];
  2569. }
  2570. function warn_or_throw(wrn, msg) {
  2571. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  2572. else throw new Error(msg);
  2573. }
  2574. function parse_zip(file, options) {
  2575. var blob = file;
  2576. prep_blob(blob, 0);
  2577. var FileIndex = [], FullPaths = [];
  2578. var o = {
  2579. FileIndex: FileIndex,
  2580. FullPaths: FullPaths
  2581. };
  2582. init_cfb(o, { root: options.root });
  2583. /* find end of central directory, start just after signature */
  2584. var i = blob.length - 4;
  2585. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  2586. blob.l = i + 4;
  2587. /* parse end of central directory */
  2588. blob.l += 4;
  2589. var fcnt = blob.read_shift(2);
  2590. blob.l += 6;
  2591. var start_cd = blob.read_shift(4);
  2592. /* parse central directory */
  2593. blob.l = start_cd;
  2594. for(i = 0; i < fcnt; ++i) {
  2595. /* trust local file header instead of CD entry */
  2596. blob.l += 20;
  2597. var csz = blob.read_shift(4);
  2598. var usz = blob.read_shift(4);
  2599. var namelen = blob.read_shift(2);
  2600. var efsz = blob.read_shift(2);
  2601. var fcsz = blob.read_shift(2);
  2602. blob.l += 8;
  2603. var offset = blob.read_shift(4);
  2604. var EF = parse_extra_field(blob.slice(blob.l+namelen, blob.l+namelen+efsz));
  2605. blob.l += namelen + efsz + fcsz;
  2606. var L = blob.l;
  2607. blob.l = offset + 4;
  2608. parse_local_file(blob, csz, usz, o, EF);
  2609. blob.l = L;
  2610. }
  2611. return o;
  2612. }
  2613. /* head starts just after local file header signature */
  2614. function parse_local_file(blob, csz, usz, o, EF) {
  2615. /* [local file header] */
  2616. blob.l += 2;
  2617. var flags = blob.read_shift(2);
  2618. var meth = blob.read_shift(2);
  2619. var date = parse_dos_date(blob);
  2620. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  2621. var crc32 = blob.read_shift(4);
  2622. var _csz = blob.read_shift(4);
  2623. var _usz = blob.read_shift(4);
  2624. var namelen = blob.read_shift(2);
  2625. var efsz = blob.read_shift(2);
  2626. // TODO: flags & (1<<11) // UTF8
  2627. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  2628. if(efsz) {
  2629. var ef = parse_extra_field(blob.slice(blob.l, blob.l + efsz));
  2630. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  2631. if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
  2632. }
  2633. blob.l += efsz;
  2634. /* [encryption header] */
  2635. /* [file data] */
  2636. var data = blob.slice(blob.l, blob.l + _csz);
  2637. switch(meth) {
  2638. case 8: data = _inflateRawSync(blob, _usz); break;
  2639. case 0: break; // TODO: scan for magic number
  2640. default: throw new Error("Unsupported ZIP Compression method " + meth);
  2641. }
  2642. /* [data descriptor] */
  2643. var wrn = false;
  2644. if(flags & 8) {
  2645. crc32 = blob.read_shift(4);
  2646. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  2647. _csz = blob.read_shift(4);
  2648. _usz = blob.read_shift(4);
  2649. }
  2650. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  2651. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  2652. //var _crc32 = CRC32.buf(data, 0);
  2653. //if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  2654. cfb_add(o, name, data, {unsafe: true, mt: date});
  2655. }
  2656. function write_zip(cfb, options) {
  2657. var _opts = options || {};
  2658. var out = [], cdirs = [];
  2659. var o = new_buf(1);
  2660. var method = (_opts.compression ? 8 : 0), flags = 0;
  2661. var desc = false;
  2662. if(desc) flags |= 8;
  2663. var i = 0, j = 0;
  2664. var start_cd = 0, fcnt = 0;
  2665. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  2666. var crcs = [];
  2667. var sz_cd = 0;
  2668. for(i = 1; i < cfb.FullPaths.length; ++i) {
  2669. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  2670. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  2671. var start = start_cd;
  2672. /* TODO: CP437 filename */
  2673. var namebuf = new_buf(fp.length);
  2674. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  2675. namebuf = namebuf.slice(0, namebuf.l);
  2676. crcs[fcnt] = CRC32.buf(fi.content, 0);
  2677. var outbuf = fi.content;
  2678. if(method == 8) outbuf = _deflateRawSync(outbuf);
  2679. /* local file header */
  2680. o = new_buf(30);
  2681. o.write_shift(4, 0x04034b50);
  2682. o.write_shift(2, 20);
  2683. o.write_shift(2, flags);
  2684. o.write_shift(2, method);
  2685. /* TODO: last mod file time/date */
  2686. if(fi.mt) write_dos_date(o, fi.mt);
  2687. else o.write_shift(4, 0);
  2688. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  2689. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  2690. o.write_shift(4, (flags & 8) ? 0 : fi.content.length);
  2691. o.write_shift(2, namebuf.length);
  2692. o.write_shift(2, 0);
  2693. start_cd += o.length;
  2694. out.push(o);
  2695. start_cd += namebuf.length;
  2696. out.push(namebuf);
  2697. /* TODO: extra fields? */
  2698. /* TODO: encryption header ? */
  2699. start_cd += outbuf.length;
  2700. out.push(outbuf);
  2701. /* data descriptor */
  2702. if(flags & 8) {
  2703. o = new_buf(12);
  2704. o.write_shift(-4, crcs[fcnt]);
  2705. o.write_shift(4, outbuf.length);
  2706. o.write_shift(4, fi.content.length);
  2707. start_cd += o.l;
  2708. out.push(o);
  2709. }
  2710. /* central directory */
  2711. o = new_buf(46);
  2712. o.write_shift(4, 0x02014b50);
  2713. o.write_shift(2, 0);
  2714. o.write_shift(2, 20);
  2715. o.write_shift(2, flags);
  2716. o.write_shift(2, method);
  2717. o.write_shift(4, 0); /* TODO: last mod file time/date */
  2718. o.write_shift(-4, crcs[fcnt]);
  2719. o.write_shift(4, outbuf.length);
  2720. o.write_shift(4, fi.content.length);
  2721. o.write_shift(2, namebuf.length);
  2722. o.write_shift(2, 0);
  2723. o.write_shift(2, 0);
  2724. o.write_shift(2, 0);
  2725. o.write_shift(2, 0);
  2726. o.write_shift(4, 0);
  2727. o.write_shift(4, start);
  2728. sz_cd += o.l;
  2729. cdirs.push(o);
  2730. sz_cd += namebuf.length;
  2731. cdirs.push(namebuf);
  2732. ++fcnt;
  2733. }
  2734. /* end of central directory */
  2735. o = new_buf(22);
  2736. o.write_shift(4, 0x06054b50);
  2737. o.write_shift(2, 0);
  2738. o.write_shift(2, 0);
  2739. o.write_shift(2, fcnt);
  2740. o.write_shift(2, fcnt);
  2741. o.write_shift(4, sz_cd);
  2742. o.write_shift(4, start_cd);
  2743. o.write_shift(2, 0);
  2744. return bconcat(([bconcat((out)), bconcat(cdirs), o]));
  2745. }
  2746. var ContentTypeMap = ({
  2747. "htm": "text/html",
  2748. "xml": "text/xml",
  2749. "gif": "image/gif",
  2750. "jpg": "image/jpeg",
  2751. "png": "image/png",
  2752. "mso": "application/x-mso",
  2753. "thmx": "application/vnd.ms-officetheme",
  2754. "sh33tj5": "application/octet-stream"
  2755. });
  2756. function get_content_type(fi, fp) {
  2757. if(fi.ctype) return fi.ctype;
  2758. var ext = fi.name || "", m = ext.match(/\.([^\.]+)$/);
  2759. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  2760. if(fp) {
  2761. m = (ext = fp).match(/[\.\\]([^\.\\])+$/);
  2762. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  2763. }
  2764. return "application/octet-stream";
  2765. }
  2766. /* 76 character chunks TODO: intertwine encoding */
  2767. function write_base64_76(bstr) {
  2768. var data = Base64_encode(bstr);
  2769. var o = [];
  2770. for(var i = 0; i < data.length; i+= 76) o.push(data.slice(i, i+76));
  2771. return o.join("\r\n") + "\r\n";
  2772. }
  2773. /*
  2774. Rules for QP:
  2775. - escape =## applies for all non-display characters and literal "="
  2776. - space or tab at end of line must be encoded
  2777. - \r\n newlines can be preserved, but bare \r and \n must be escaped
  2778. - lines must not exceed 76 characters, use soft breaks =\r\n
  2779. TODO: Some files from word appear to write line extensions with bare equals:
  2780. ```
  2781. <table class=3DMsoTableGrid border=3D1 cellspacing=3D0 cellpadding=3D0 width=
  2782. ="70%"
  2783. ```
  2784. */
  2785. function write_quoted_printable(text) {
  2786. var encoded = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c) {
  2787. var w = c.charCodeAt(0).toString(16).toUpperCase();
  2788. return "=" + (w.length == 1 ? "0" + w : w);
  2789. });
  2790. encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
  2791. if(encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
  2792. encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
  2793. var o = [], split = encoded.split("\r\n");
  2794. for(var si = 0; si < split.length; ++si) {
  2795. var str = split[si];
  2796. if(str.length == 0) { o.push(""); continue; }
  2797. for(var i = 0; i < str.length;) {
  2798. var end = 76;
  2799. var tmp = str.slice(i, i + end);
  2800. if(tmp.charAt(end - 1) == "=") end --;
  2801. else if(tmp.charAt(end - 2) == "=") end -= 2;
  2802. else if(tmp.charAt(end - 3) == "=") end -= 3;
  2803. tmp = str.slice(i, i + end);
  2804. i += end;
  2805. if(i < str.length) tmp += "=";
  2806. o.push(tmp);
  2807. }
  2808. }
  2809. return o.join("\r\n");
  2810. }
  2811. function parse_quoted_printable(data) {
  2812. var o = [];
  2813. /* unify long lines */
  2814. for(var di = 0; di < data.length; ++di) {
  2815. var line = data[di];
  2816. while(di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
  2817. o.push(line);
  2818. }
  2819. /* decode */
  2820. 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)); });
  2821. return s2a(o.join("\r\n"));
  2822. }
  2823. function parse_mime(cfb, data, root) {
  2824. var fname = "", cte = "", ctype = "", fdata;
  2825. var di = 0;
  2826. for(;di < 10; ++di) {
  2827. var line = data[di];
  2828. if(!line || line.match(/^\s*$/)) break;
  2829. var m = line.match(/^(.*?):\s*([^\s].*)$/);
  2830. if(m) switch(m[1].toLowerCase()) {
  2831. case "content-location": fname = m[2].trim(); break;
  2832. case "content-type": ctype = m[2].trim(); break;
  2833. case "content-transfer-encoding": cte = m[2].trim(); break;
  2834. }
  2835. }
  2836. ++di;
  2837. switch(cte.toLowerCase()) {
  2838. case 'base64': fdata = s2a(Base64_decode(data.slice(di).join(""))); break;
  2839. case 'quoted-printable': fdata = parse_quoted_printable(data.slice(di)); break;
  2840. default: throw new Error("Unsupported Content-Transfer-Encoding " + cte);
  2841. }
  2842. var file = cfb_add(cfb, fname.slice(root.length), fdata, {unsafe: true});
  2843. if(ctype) file.ctype = ctype;
  2844. }
  2845. function parse_mad(file, options) {
  2846. if(a2s(file.slice(0,13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
  2847. var root = (options && options.root || "");
  2848. // $FlowIgnore
  2849. var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s(file)).split("\r\n");
  2850. var di = 0, row = "";
  2851. /* if root is not specified, scan for the common prefix */
  2852. for(di = 0; di < data.length; ++di) {
  2853. row = data[di];
  2854. if(!/^Content-Location:/i.test(row)) continue;
  2855. row = row.slice(row.indexOf("file"));
  2856. if(!root) root = row.slice(0, row.lastIndexOf("/") + 1);
  2857. if(row.slice(0, root.length) == root) continue;
  2858. while(root.length > 0) {
  2859. root = root.slice(0, root.length - 1);
  2860. root = root.slice(0, root.lastIndexOf("/") + 1);
  2861. if(row.slice(0,root.length) == root) break;
  2862. }
  2863. }
  2864. var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
  2865. if(!mboundary) throw new Error("MAD cannot find boundary");
  2866. var boundary = "--" + (mboundary[1] || "");
  2867. var FileIndex = [], FullPaths = [];
  2868. var o = {
  2869. FileIndex: FileIndex,
  2870. FullPaths: FullPaths
  2871. };
  2872. init_cfb(o);
  2873. var start_di, fcnt = 0;
  2874. for(di = 0; di < data.length; ++di) {
  2875. var line = data[di];
  2876. if(line !== boundary && line !== boundary + "--") continue;
  2877. if(fcnt++) parse_mime(o, data.slice(start_di, di), root);
  2878. start_di = di;
  2879. }
  2880. return o;
  2881. }
  2882. function write_mad(cfb, options) {
  2883. var opts = options || {};
  2884. var boundary = opts.boundary || "SheetJS";
  2885. boundary = '------=' + boundary;
  2886. var out = [
  2887. 'MIME-Version: 1.0',
  2888. 'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
  2889. '',
  2890. '',
  2891. ''
  2892. ];
  2893. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  2894. for(var i = 1; i < cfb.FullPaths.length; ++i) {
  2895. fp = cfb.FullPaths[i].slice(root.length);
  2896. fi = cfb.FileIndex[i];
  2897. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  2898. /* Normalize filename */
  2899. fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c) {
  2900. return "_x" + c.charCodeAt(0).toString(16) + "_";
  2901. }).replace(/[\u0080-\uFFFF]/g, function(u) {
  2902. return "_u" + u.charCodeAt(0).toString(16) + "_";
  2903. });
  2904. /* Extract content as binary string */
  2905. var ca = fi.content;
  2906. // $FlowIgnore
  2907. var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s(ca);
  2908. /* 4/5 of first 1024 chars ascii -> quoted printable, else base64 */
  2909. var dispcnt = 0, L = Math.min(1024, cstr.length), cc = 0;
  2910. for(var csl = 0; csl <= L; ++csl) if((cc=cstr.charCodeAt(csl)) >= 0x20 && cc < 0x80) ++dispcnt;
  2911. var qp = dispcnt >= L * 4 / 5;
  2912. out.push(boundary);
  2913. out.push('Content-Location: ' + (opts.root || 'file:///C:/SheetJS/') + fp);
  2914. out.push('Content-Transfer-Encoding: ' + (qp ? 'quoted-printable' : 'base64'));
  2915. out.push('Content-Type: ' + get_content_type(fi, fp));
  2916. out.push('');
  2917. out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
  2918. }
  2919. out.push(boundary + '--\r\n');
  2920. return out.join("\r\n");
  2921. }
  2922. function cfb_new(opts) {
  2923. var o = ({});
  2924. init_cfb(o, opts);
  2925. return o;
  2926. }
  2927. function cfb_add(cfb, name, content, opts) {
  2928. var unsafe = opts && opts.unsafe;
  2929. if(!unsafe) init_cfb(cfb);
  2930. var file = !unsafe && CFB.find(cfb, name);
  2931. if(!file) {
  2932. var fpath = cfb.FullPaths[0];
  2933. if(name.slice(0, fpath.length) == fpath) fpath = name;
  2934. else {
  2935. if(fpath.slice(-1) != "/") fpath += "/";
  2936. fpath = (fpath + name).replace("//","/");
  2937. }
  2938. file = ({name: filename(name), type: 2});
  2939. cfb.FileIndex.push(file);
  2940. cfb.FullPaths.push(fpath);
  2941. if(!unsafe) CFB.utils.cfb_gc(cfb);
  2942. }
  2943. file.content = (content);
  2944. file.size = content ? content.length : 0;
  2945. if(opts) {
  2946. if(opts.CLSID) file.clsid = opts.CLSID;
  2947. if(opts.mt) file.mt = opts.mt;
  2948. if(opts.ct) file.ct = opts.ct;
  2949. }
  2950. return file;
  2951. }
  2952. function cfb_del(cfb, name) {
  2953. init_cfb(cfb);
  2954. var file = CFB.find(cfb, name);
  2955. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  2956. cfb.FileIndex.splice(j, 1);
  2957. cfb.FullPaths.splice(j, 1);
  2958. return true;
  2959. }
  2960. return false;
  2961. }
  2962. function cfb_mov(cfb, old_name, new_name) {
  2963. init_cfb(cfb);
  2964. var file = CFB.find(cfb, old_name);
  2965. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  2966. cfb.FileIndex[j].name = filename(new_name);
  2967. cfb.FullPaths[j] = new_name;
  2968. return true;
  2969. }
  2970. return false;
  2971. }
  2972. function cfb_gc(cfb) { rebuild_cfb(cfb, true); }
  2973. exports.find = find;
  2974. exports.read = read;
  2975. exports.parse = parse;
  2976. exports.write = write;
  2977. exports.writeFile = write_file;
  2978. exports.utils = {
  2979. cfb_new: cfb_new,
  2980. cfb_add: cfb_add,
  2981. cfb_del: cfb_del,
  2982. cfb_mov: cfb_mov,
  2983. cfb_gc: cfb_gc,
  2984. ReadShift: ReadShift,
  2985. CheckField: CheckField,
  2986. prep_blob: prep_blob,
  2987. bconcat: bconcat,
  2988. use_zlib: use_zlib,
  2989. _deflateRaw: _deflate,
  2990. _inflateRaw: _inflate,
  2991. consts: consts
  2992. };
  2993. return exports;
  2994. })();
  2995. var _fs;
  2996. if(typeof require !== 'undefined') try { _fs = undefined; } catch(e) {}
  2997. /* normalize data for blob ctor */
  2998. function blobify(data) {
  2999. if(typeof data === "string") return s2ab(data);
  3000. if(Array.isArray(data)) return a2u(data);
  3001. return data;
  3002. }
  3003. /* write or download file */
  3004. function write_dl(fname, payload, enc) {
  3005. /*global IE_SaveFile, Blob, navigator, saveAs, document, File, chrome */
  3006. if(typeof _fs !== 'undefined' && _fs.writeFileSync) return enc ? _fs.writeFileSync(fname, payload, enc) : _fs.writeFileSync(fname, payload);
  3007. if(typeof Deno !== 'undefined') {
  3008. /* in this spot, it's safe to assume typed arrays and TextEncoder/TextDecoder exist */
  3009. if(enc && typeof payload == "string") switch(enc) {
  3010. case "utf8": payload = new TextEncoder(enc).encode(payload); break;
  3011. case "binary": payload = s2ab(payload); break;
  3012. /* TODO: binary equivalent */
  3013. default: throw new Error("Unsupported encoding " + enc);
  3014. }
  3015. return Deno.writeFileSync(fname, payload);
  3016. }
  3017. var data = (enc == "utf8") ? utf8write(payload) : payload;
  3018. if(typeof IE_SaveFile !== 'undefined') return IE_SaveFile(data, fname);
  3019. if(typeof Blob !== 'undefined') {
  3020. var blob = new Blob([blobify(data)], {type:"application/octet-stream"});
  3021. if(typeof navigator !== 'undefined' && navigator.msSaveBlob) return navigator.msSaveBlob(blob, fname);
  3022. if(typeof saveAs !== 'undefined') return saveAs(blob, fname);
  3023. if(typeof URL !== 'undefined' && typeof document !== 'undefined' && document.createElement && URL.createObjectURL) {
  3024. var url = URL.createObjectURL(blob);
  3025. if(typeof chrome === 'object' && typeof (chrome.downloads||{}).download == "function") {
  3026. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  3027. return chrome.downloads.download({ url: url, filename: fname, saveAs: true});
  3028. }
  3029. var a = document.createElement("a");
  3030. if(a.download != null) {
  3031. a.download = fname; a.href = url; document.body.appendChild(a); a.click();
  3032. document.body.removeChild(a);
  3033. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  3034. return url;
  3035. }
  3036. }
  3037. }
  3038. // $FlowIgnore
  3039. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  3040. // $FlowIgnore
  3041. var out = File(fname); out.open("w"); out.encoding = "binary";
  3042. if(Array.isArray(payload)) payload = a2s(payload);
  3043. out.write(payload); out.close(); return payload;
  3044. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  3045. throw new Error("cannot save file " + fname);
  3046. }
  3047. /* read binary data from file */
  3048. function read_binary(path) {
  3049. if(typeof _fs !== 'undefined') return _fs.readFileSync(path);
  3050. if(typeof Deno !== 'undefined') return Deno.readFileSync(path);
  3051. // $FlowIgnore
  3052. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  3053. // $FlowIgnore
  3054. var infile = File(path); infile.open("r"); infile.encoding = "binary";
  3055. var data = infile.read(); infile.close();
  3056. return data;
  3057. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  3058. throw new Error("Cannot access file " + path);
  3059. }
  3060. function keys(o) {
  3061. var ks = Object.keys(o), o2 = [];
  3062. for(var i = 0; i < ks.length; ++i) if(Object.prototype.hasOwnProperty.call(o, ks[i])) o2.push(ks[i]);
  3063. return o2;
  3064. }
  3065. function evert_key(obj, key) {
  3066. var o = ([]), K = keys(obj);
  3067. for(var i = 0; i !== K.length; ++i) if(o[obj[K[i]][key]] == null) o[obj[K[i]][key]] = K[i];
  3068. return o;
  3069. }
  3070. function evert(obj) {
  3071. var o = ([]), K = keys(obj);
  3072. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
  3073. return o;
  3074. }
  3075. function evert_num(obj) {
  3076. var o = ([]), K = keys(obj);
  3077. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
  3078. return o;
  3079. }
  3080. function evert_arr(obj) {
  3081. var o = ([]), K = keys(obj);
  3082. for(var i = 0; i !== K.length; ++i) {
  3083. if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
  3084. o[obj[K[i]]].push(K[i]);
  3085. }
  3086. return o;
  3087. }
  3088. var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
  3089. function datenum(v, date1904) {
  3090. var epoch = v.getTime();
  3091. if(date1904) epoch -= 1462*24*60*60*1000;
  3092. var dnthresh = basedate.getTime() + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  3093. return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
  3094. }
  3095. var refdate = new Date();
  3096. var dnthresh = basedate.getTime() + (refdate.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  3097. var refoffset = refdate.getTimezoneOffset();
  3098. function numdate(v) {
  3099. var out = new Date();
  3100. out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  3101. if (out.getTimezoneOffset() !== refoffset) {
  3102. out.setTime(out.getTime() + (out.getTimezoneOffset() - refoffset) * 60000);
  3103. }
  3104. return out;
  3105. }
  3106. /* ISO 8601 Duration */
  3107. function parse_isodur(s) {
  3108. var sec = 0, mt = 0, time = false;
  3109. var m = s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
  3110. if(!m) throw new Error("|" + s + "| is not an ISO8601 Duration");
  3111. for(var i = 1; i != m.length; ++i) {
  3112. if(!m[i]) continue;
  3113. mt = 1;
  3114. if(i > 3) time = true;
  3115. switch(m[i].slice(m[i].length-1)) {
  3116. case 'Y':
  3117. throw new Error("Unsupported ISO Duration Field: " + m[i].slice(m[i].length-1));
  3118. case 'D': mt *= 24;
  3119. /* falls through */
  3120. case 'H': mt *= 60;
  3121. /* falls through */
  3122. case 'M':
  3123. if(!time) throw new Error("Unsupported ISO Duration Field: M");
  3124. else mt *= 60;
  3125. /* falls through */
  3126. case 'S': break;
  3127. }
  3128. sec += mt * parseInt(m[i], 10);
  3129. }
  3130. return sec;
  3131. }
  3132. var good_pd_date_1 = new Date('2017-02-19T19:06:09.000Z');
  3133. var good_pd_date = isNaN(good_pd_date_1.getFullYear()) ? new Date('2/19/17') : good_pd_date_1;
  3134. var good_pd = good_pd_date.getFullYear() == 2017;
  3135. /* parses a date as a local date */
  3136. function parseDate(str, fixdate) {
  3137. var d = new Date(str);
  3138. if(good_pd) {
  3139. if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
  3140. else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
  3141. return d;
  3142. }
  3143. if(str instanceof Date) return str;
  3144. if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
  3145. var s = d.getFullYear();
  3146. if(str.indexOf("" + s) > -1) return d;
  3147. d.setFullYear(d.getFullYear() + 100); return d;
  3148. }
  3149. var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
  3150. var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
  3151. if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
  3152. return out;
  3153. }
  3154. function cc2str(arr, debomit) {
  3155. if(has_buf && Buffer.isBuffer(arr)) {
  3156. if(debomit) {
  3157. if(arr[0] == 0xFF && arr[1] == 0xFE) return utf8write(arr.slice(2).toString("utf16le"));
  3158. if(arr[1] == 0xFE && arr[2] == 0xFF) return utf8write(utf16beread(arr.slice(2).toString("binary")));
  3159. }
  3160. return arr.toString("binary");
  3161. }
  3162. if(typeof TextDecoder !== "undefined") try {
  3163. if(debomit) {
  3164. if(arr[0] == 0xFF && arr[1] == 0xFE) return utf8write(new TextDecoder("utf-16le").decode(arr.slice(2)));
  3165. if(arr[0] == 0xFE && arr[1] == 0xFF) return utf8write(new TextDecoder("utf-16be").decode(arr.slice(2)));
  3166. }
  3167. var rev = {
  3168. "\u20ac": "\x80", "\u201a": "\x82", "\u0192": "\x83", "\u201e": "\x84",
  3169. "\u2026": "\x85", "\u2020": "\x86", "\u2021": "\x87", "\u02c6": "\x88",
  3170. "\u2030": "\x89", "\u0160": "\x8a", "\u2039": "\x8b", "\u0152": "\x8c",
  3171. "\u017d": "\x8e", "\u2018": "\x91", "\u2019": "\x92", "\u201c": "\x93",
  3172. "\u201d": "\x94", "\u2022": "\x95", "\u2013": "\x96", "\u2014": "\x97",
  3173. "\u02dc": "\x98", "\u2122": "\x99", "\u0161": "\x9a", "\u203a": "\x9b",
  3174. "\u0153": "\x9c", "\u017e": "\x9e", "\u0178": "\x9f"
  3175. };
  3176. if(Array.isArray(arr)) arr = new Uint8Array(arr);
  3177. return new TextDecoder("latin1").decode(arr).replace(/[€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ]/g, function(c) { return rev[c] || c; });
  3178. } catch(e) {}
  3179. var o = [];
  3180. for(var i = 0; i != arr.length; ++i) o.push(String.fromCharCode(arr[i]));
  3181. return o.join("");
  3182. }
  3183. function dup(o) {
  3184. if(typeof JSON != 'undefined' && !Array.isArray(o)) return JSON.parse(JSON.stringify(o));
  3185. if(typeof o != 'object' || o == null) return o;
  3186. if(o instanceof Date) return new Date(o.getTime());
  3187. var out = {};
  3188. for(var k in o) if(Object.prototype.hasOwnProperty.call(o, k)) out[k] = dup(o[k]);
  3189. return out;
  3190. }
  3191. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  3192. /* TODO: stress test */
  3193. function fuzzynum(s) {
  3194. var v = Number(s);
  3195. if(!isNaN(v)) return isFinite(v) ? v : NaN;
  3196. if(!/\d/.test(s)) return v;
  3197. var wt = 1;
  3198. var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
  3199. if(!isNaN(v = Number(ss))) return v / wt;
  3200. ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
  3201. if(!isNaN(v = Number(ss))) return v / wt;
  3202. return v;
  3203. }
  3204. var lower_months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
  3205. function fuzzydate(s) {
  3206. var o = new Date(s), n = new Date(NaN);
  3207. var y = o.getYear(), m = o.getMonth(), d = o.getDate();
  3208. if(isNaN(d)) return n;
  3209. var lower = s.toLowerCase();
  3210. if(lower.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) {
  3211. lower = lower.replace(/[^a-z]/g,"").replace(/([^a-z]|^)[ap]m?([^a-z]|$)/,"");
  3212. if(lower.length > 3 && lower_months.indexOf(lower) == -1) return n;
  3213. } else if(lower.match(/[a-z]/)) return n;
  3214. if(y < 0 || y > 8099) return n;
  3215. if((m > 0 || d > 1) && y != 101) return o;
  3216. if(s.match(/[^-0-9:,\/\\]/)) return n;
  3217. return o;
  3218. }
  3219. var split_regex = (function() {
  3220. var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  3221. return function split_regex(str, re, def) {
  3222. if(safe_split_regex || typeof re == "string") return str.split(re);
  3223. var p = str.split(re), o = [p[0]];
  3224. for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
  3225. return o;
  3226. };
  3227. })();
  3228. function getdatastr(data) {
  3229. if(!data) return null;
  3230. if(data.content && data.type) return cc2str(data.content, true);
  3231. if(data.data) return debom(data.data);
  3232. if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
  3233. if(data.asBinary) return debom(data.asBinary());
  3234. if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
  3235. return null;
  3236. }
  3237. function getdatabin(data) {
  3238. if(!data) return null;
  3239. if(data.data) return char_codes(data.data);
  3240. if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  3241. if(data._data && data._data.getContent) {
  3242. var o = data._data.getContent();
  3243. if(typeof o == "string") return char_codes(o);
  3244. return Array.prototype.slice.call(o);
  3245. }
  3246. if(data.content && data.type) return data.content;
  3247. return null;
  3248. }
  3249. function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }
  3250. /* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
  3251. /* OASIS does not comment on filename case sensitivity */
  3252. function safegetzipfile(zip, file) {
  3253. var k = zip.FullPaths || keys(zip.files);
  3254. var f = file.toLowerCase().replace(/[\/]/g, '\\'), g = f.replace(/\\/g,'\/');
  3255. for(var i=0; i<k.length; ++i) {
  3256. var n = k[i].replace(/^Root Entry[\/]/,"").toLowerCase();
  3257. if(f == n || g == n) return zip.files ? zip.files[k[i]] : zip.FileIndex[i];
  3258. }
  3259. return null;
  3260. }
  3261. function getzipfile(zip, file) {
  3262. var o = safegetzipfile(zip, file);
  3263. if(o == null) throw new Error("Cannot find file " + file + " in zip");
  3264. return o;
  3265. }
  3266. function getzipdata(zip, file, safe) {
  3267. if(!safe) return getdata(getzipfile(zip, file));
  3268. if(!file) return null;
  3269. try { return getzipdata(zip, file); } catch(e) { return null; }
  3270. }
  3271. function getzipstr(zip, file, safe) {
  3272. if(!safe) return getdatastr(getzipfile(zip, file));
  3273. if(!file) return null;
  3274. try { return getzipstr(zip, file); } catch(e) { return null; }
  3275. }
  3276. function getzipbin(zip, file, safe) {
  3277. if(!safe) return getdatabin(getzipfile(zip, file));
  3278. if(!file) return null;
  3279. try { return getzipbin(zip, file); } catch(e) { return null; }
  3280. }
  3281. function zipentries(zip) {
  3282. var k = zip.FullPaths || keys(zip.files), o = [];
  3283. for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i].replace(/^Root Entry[\/]/, ""));
  3284. return o.sort();
  3285. }
  3286. function zip_add_file(zip, path, content) {
  3287. if(zip.FullPaths) {
  3288. if(typeof content == "string") {
  3289. var res;
  3290. if(has_buf) res = Buffer_from(content);
  3291. /* TODO: investigate performance in Edge 13 */
  3292. //else if(typeof TextEncoder !== "undefined") res = new TextEncoder().encode(content);
  3293. else res = utf8decode(content);
  3294. return CFB.utils.cfb_add(zip, path, res);
  3295. }
  3296. CFB.utils.cfb_add(zip, path, content);
  3297. }
  3298. else zip.file(path, content);
  3299. }
  3300. function zip_new() { return CFB.utils.cfb_new(); }
  3301. function zip_read(d, o) {
  3302. switch(o.type) {
  3303. case "base64": return CFB.read(d, { type: "base64" });
  3304. case "binary": return CFB.read(d, { type: "binary" });
  3305. case "buffer": case "array": return CFB.read(d, { type: "buffer" });
  3306. }
  3307. throw new Error("Unrecognized type " + o.type);
  3308. }
  3309. function resolve_path(path, base) {
  3310. if(path.charAt(0) == "/") return path.slice(1);
  3311. var result = base.split('/');
  3312. if(base.slice(-1) != "/") result.pop(); // folder path
  3313. var target = path.split('/');
  3314. while (target.length !== 0) {
  3315. var step = target.shift();
  3316. if (step === '..') result.pop();
  3317. else if (step !== '.') result.push(step);
  3318. }
  3319. return result.join('/');
  3320. }
  3321. var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
  3322. var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
  3323. var tagregex1=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s*[\/\?]?>/mg, tagregex2 = /<[^>]*>/g;
  3324. var tagregex = XML_HEADER.match(tagregex1) ? tagregex1 : tagregex2;
  3325. var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
  3326. function parsexmltag(tag, skip_root, skip_LC) {
  3327. var z = ({});
  3328. var eq = 0, c = 0;
  3329. for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
  3330. if(!skip_root) z[0] = tag.slice(0, eq);
  3331. if(eq === tag.length) return z;
  3332. var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
  3333. if(m) for(i = 0; i != m.length; ++i) {
  3334. cc = m[i];
  3335. for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
  3336. q = cc.slice(0,c).trim();
  3337. while(cc.charCodeAt(c+1) == 32) ++c;
  3338. quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
  3339. v = cc.slice(c+1+quot, cc.length-quot);
  3340. for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
  3341. if(j===q.length) {
  3342. if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
  3343. z[q] = v;
  3344. if(!skip_LC) z[q.toLowerCase()] = v;
  3345. }
  3346. else {
  3347. var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
  3348. if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
  3349. z[k] = v;
  3350. if(!skip_LC) z[k.toLowerCase()] = v;
  3351. }
  3352. }
  3353. return z;
  3354. }
  3355. function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
  3356. var encodings = {
  3357. '&quot;': '"',
  3358. '&apos;': "'",
  3359. '&gt;': '>',
  3360. '&lt;': '<',
  3361. '&amp;': '&'
  3362. };
  3363. var rencoding = evert(encodings);
  3364. //var rencstr = "&<>'\"".split("");
  3365. // TODO: CP remap (need to read file version to determine OS)
  3366. var unescapexml = (function() {
  3367. /* 22.4.2.4 bstr (Basic String) */
  3368. var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  3369. return function unescapexml(text) {
  3370. var s = text + '', i = s.indexOf("<![CDATA[");
  3371. 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));});
  3372. var j = s.indexOf("]]>");
  3373. return unescapexml(s.slice(0, i)) + s.slice(i+9,j) + unescapexml(s.slice(j+3));
  3374. };
  3375. })();
  3376. var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
  3377. function escapexml(text){
  3378. var s = text + '';
  3379. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
  3380. }
  3381. function escapexmltag(text){ return escapexml(text).replace(/ /g,"_x0020_"); }
  3382. var htmlcharegex = /[\u0000-\u001f]/g;
  3383. function escapehtml(text){
  3384. var s = text + '';
  3385. 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) + ";"; });
  3386. }
  3387. function escapexlml(text){
  3388. var s = text + '';
  3389. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
  3390. }
  3391. /* TODO: handle codepages */
  3392. var xlml_fixstr = (function() {
  3393. var entregex = /&#(\d+);/g;
  3394. function entrepl($$,$1) { return String.fromCharCode(parseInt($1,10)); }
  3395. return function xlml_fixstr(str) { return str.replace(entregex,entrepl); };
  3396. })();
  3397. function xlml_unfixstr(str) { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); }
  3398. function parsexmlbool(value) {
  3399. switch(value) {
  3400. case 1: case true: case '1': case 'true': case 'TRUE': return true;
  3401. /* case '0': case 'false': case 'FALSE':*/
  3402. default: return false;
  3403. }
  3404. }
  3405. function utf8reada(orig) {
  3406. var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
  3407. while (i < orig.length) {
  3408. c = orig.charCodeAt(i++);
  3409. if (c < 128) { out += String.fromCharCode(c); continue; }
  3410. d = orig.charCodeAt(i++);
  3411. if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
  3412. e = orig.charCodeAt(i++);
  3413. if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
  3414. f = orig.charCodeAt(i++);
  3415. w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
  3416. out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
  3417. out += String.fromCharCode(0xDC00 + (w&1023));
  3418. }
  3419. return out;
  3420. }
  3421. function utf8readb(data) {
  3422. var out = new_raw_buf(2*data.length), w, i, j = 1, k = 0, ww=0, c;
  3423. for(i = 0; i < data.length; i+=j) {
  3424. j = 1;
  3425. if((c=data.charCodeAt(i)) < 128) w = c;
  3426. else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
  3427. else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
  3428. else { j = 4;
  3429. w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
  3430. w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
  3431. }
  3432. if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
  3433. out[k++] = w%256; out[k++] = w>>>8;
  3434. }
  3435. return out.slice(0,k).toString('ucs2');
  3436. }
  3437. function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); }
  3438. var utf8corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
  3439. var utf8read = has_buf && (utf8readc(utf8corpus) == utf8reada(utf8corpus) && utf8readc || utf8readb(utf8corpus) == utf8reada(utf8corpus) && utf8readb) || utf8reada;
  3440. var utf8write = has_buf ? function(data) { return Buffer_from(data, 'utf8').toString("binary"); } : function(orig) {
  3441. var out = [], i = 0, c = 0, d = 0;
  3442. while(i < orig.length) {
  3443. c = orig.charCodeAt(i++);
  3444. switch(true) {
  3445. case c < 128: out.push(String.fromCharCode(c)); break;
  3446. case c < 2048:
  3447. out.push(String.fromCharCode(192 + (c >> 6)));
  3448. out.push(String.fromCharCode(128 + (c & 63)));
  3449. break;
  3450. case c >= 55296 && c < 57344:
  3451. c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
  3452. out.push(String.fromCharCode(240 + ((d >>18) & 7)));
  3453. out.push(String.fromCharCode(144 + ((d >>12) & 63)));
  3454. out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
  3455. out.push(String.fromCharCode(128 + (d & 63)));
  3456. break;
  3457. default:
  3458. out.push(String.fromCharCode(224 + (c >> 12)));
  3459. out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
  3460. out.push(String.fromCharCode(128 + (c & 63)));
  3461. }
  3462. }
  3463. return out.join("");
  3464. };
  3465. // matches <foo>...</foo> extracts content
  3466. var matchtag = (function() {
  3467. var mtcache = ({});
  3468. return function matchtag(f,g) {
  3469. var t = f+"|"+(g||"");
  3470. if(mtcache[t]) return mtcache[t];
  3471. return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||""))));
  3472. };
  3473. })();
  3474. var htmldecode = (function() {
  3475. var entities = [
  3476. ['nbsp', ' '], ['middot', '·'],
  3477. ['quot', '"'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['amp', '&']
  3478. ].map(function(x) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
  3479. return function htmldecode(str) {
  3480. var o = str
  3481. // Remove new lines and spaces from start of content
  3482. .replace(/^[\t\n\r ]+/, "")
  3483. // Remove new lines and spaces from end of content
  3484. .replace(/[\t\n\r ]+$/,"")
  3485. // Added line which removes any white space characters after and before html tags
  3486. .replace(/>\s+/g,">").replace(/\s+</g,"<")
  3487. // Replace remaining new lines and spaces with space
  3488. .replace(/[\t\n\r ]+/g, " ")
  3489. // Replace <br> tags with new lines
  3490. .replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
  3491. // Strip HTML elements
  3492. .replace(/<[^>]*>/g,"");
  3493. for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
  3494. return o;
  3495. };
  3496. })();
  3497. var vtregex = (function(){ var vt_cache = {};
  3498. return function vt_regex(bt) {
  3499. if(vt_cache[bt] !== undefined) return vt_cache[bt];
  3500. return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
  3501. };})();
  3502. var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
  3503. function parseVector(data, opts) {
  3504. var h = parsexmltag(data);
  3505. var matches = data.match(vtregex(h.baseType))||[];
  3506. var res = [];
  3507. if(matches.length != h.size) {
  3508. if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
  3509. return res;
  3510. }
  3511. matches.forEach(function(x) {
  3512. var v = x.replace(vtvregex,"").match(vtmregex);
  3513. if(v) res.push({v:utf8read(v[2]), t:v[1]});
  3514. });
  3515. return res;
  3516. }
  3517. var wtregex = /(^\s|\s$|\n)/;
  3518. function writetag(f,g) { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }
  3519. function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
  3520. function writextag(f,g,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
  3521. function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
  3522. function write_vt(s, xlsx) {
  3523. switch(typeof s) {
  3524. case 'string':
  3525. var o = writextag('vt:lpwstr', escapexml(s));
  3526. if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
  3527. return o;
  3528. case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
  3529. case 'boolean': return writextag('vt:bool',s?'true':'false');
  3530. }
  3531. if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
  3532. throw new Error("Unable to serialize " + s);
  3533. }
  3534. function xlml_normalize(d) {
  3535. if(has_buf && Buffer.isBuffer(d)) return d.toString('utf8');
  3536. if(typeof d === 'string') return d;
  3537. /* duktape */
  3538. if(typeof Uint8Array !== 'undefined' && d instanceof Uint8Array) return utf8read(a2s(ab2a(d)));
  3539. throw new Error("Bad input format: expected Buffer or string");
  3540. }
  3541. /* UOS uses CJK in tags */
  3542. var xlmlregex = /<(\/?)([^\s?><!\/:]*:|)([^\s?<>:\/]+)(?:[\s?:\/][^>]*)?>/mg;
  3543. //var xlmlregex = /<(\/?)([a-z0-9]*:|)(\w+)[^>]*>/mg;
  3544. var XMLNS = ({
  3545. CORE_PROPS: 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
  3546. CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
  3547. EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
  3548. CT: 'http://schemas.openxmlformats.org/package/2006/content-types',
  3549. RELS: 'http://schemas.openxmlformats.org/package/2006/relationships',
  3550. TCMNT: 'http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments',
  3551. 'dc': 'http://purl.org/dc/elements/1.1/',
  3552. 'dcterms': 'http://purl.org/dc/terms/',
  3553. 'dcmitype': 'http://purl.org/dc/dcmitype/',
  3554. 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
  3555. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  3556. 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
  3557. 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
  3558. 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
  3559. 'xsd': 'http://www.w3.org/2001/XMLSchema'
  3560. });
  3561. var XMLNS_main = [
  3562. 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  3563. 'http://purl.oclc.org/ooxml/spreadsheetml/main',
  3564. 'http://schemas.microsoft.com/office/excel/2006/main',
  3565. 'http://schemas.microsoft.com/office/excel/2006/2'
  3566. ];
  3567. var XLMLNS = ({
  3568. 'o': 'urn:schemas-microsoft-com:office:office',
  3569. 'x': 'urn:schemas-microsoft-com:office:excel',
  3570. 'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
  3571. 'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
  3572. 'mv': 'http://macVmlSchemaUri',
  3573. 'v': 'urn:schemas-microsoft-com:vml',
  3574. 'html': 'http://www.w3.org/TR/REC-html40'
  3575. });
  3576. function read_double_le(b, idx) {
  3577. var s = 1 - 2 * (b[idx + 7] >>> 7);
  3578. var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
  3579. var m = (b[idx+6]&0x0f);
  3580. for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
  3581. if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
  3582. if(e == 0) e = -1022;
  3583. else { e -= 1023; m += Math.pow(2,52); }
  3584. return s * Math.pow(2, e - 52) * m;
  3585. }
  3586. function write_double_le(b, v, idx) {
  3587. var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
  3588. var av = bs ? (-v) : v;
  3589. if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
  3590. else if(av == 0) e = m = 0;
  3591. else {
  3592. e = Math.floor(Math.log(av) / Math.LN2);
  3593. m = av * Math.pow(2, 52 - e);
  3594. if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
  3595. else { m -= Math.pow(2,52); e+=1023; }
  3596. }
  3597. for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
  3598. b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
  3599. b[idx + 7] = (e >> 4) | bs;
  3600. }
  3601. 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; };
  3602. 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;
  3603. 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,''); };
  3604. var __utf16le = has_buf ? function(b,s,e) { if(!Buffer.isBuffer(b)) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; } : ___utf16le;
  3605. 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(""); };
  3606. var __hexlify = has_buf ? function(b,s,l) { return Buffer.isBuffer(b) ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); } : ___hexlify;
  3607. 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(""); };
  3608. var __utf8 = has_buf ? function utf8_b(b, s, e) { return (Buffer.isBuffer(b)) ? b.toString('utf8',s,e) : ___utf8(b,s,e); } : ___utf8;
  3609. var ___lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3610. var __lpstr = ___lpstr;
  3611. var ___cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3612. var __cpstr = ___cpstr;
  3613. var ___lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  3614. var __lpwstr = ___lpwstr;
  3615. var ___lpp4 = function lpp4_(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
  3616. var __lpp4 = ___lpp4;
  3617. var ___8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
  3618. var __8lpp4 = ___8lpp4;
  3619. var ___double = function(b, idx) { return read_double_le(b, idx);};
  3620. var __double = ___double;
  3621. var is_buf = function is_buf_a(a) { return Array.isArray(a) || (typeof Uint8Array !== "undefined" && a instanceof Uint8Array); };
  3622. if(has_buf) {
  3623. __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) : "";};
  3624. __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) : "";};
  3625. __lpwstr = function lpwstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpwstr(b, i); var len = 2*b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len-1);};
  3626. __lpp4 = function lpp4_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len);};
  3627. __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);};
  3628. __double = function double_(b, i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
  3629. is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a) || (typeof Uint8Array !== "undefined" && a instanceof Uint8Array); };
  3630. }
  3631. /* from js-xls */
  3632. function cpdoit() {
  3633. __utf16le = function(b,s,e) { return $cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
  3634. __utf8 = function(b,s,e) { return $cptable.utils.decode(65001, b.slice(s,e)); };
  3635. __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)) : "";};
  3636. __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)) : "";};
  3637. __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)) : "";};
  3638. __lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
  3639. __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? $cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
  3640. }
  3641. if(typeof $cptable !== 'undefined') cpdoit();
  3642. var __readUInt8 = function(b, idx) { return b[idx]; };
  3643. var __readUInt16LE = function(b, idx) { return (b[idx+1]*(1<<8))+b[idx]; };
  3644. var __readInt16LE = function(b, idx) { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
  3645. var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
  3646. var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
  3647. var __readInt32BE = function(b, idx) { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };
  3648. function ReadShift(size, t) {
  3649. var o="", oI, oR, oo=[], w, vv, i, loc;
  3650. switch(t) {
  3651. case 'dbcs':
  3652. loc = this.l;
  3653. if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
  3654. else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
  3655. size *= 2;
  3656. break;
  3657. case 'utf8': o = __utf8(this, this.l, this.l + size); break;
  3658. case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;
  3659. case 'wstr':
  3660. if(typeof $cptable !== 'undefined') o = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
  3661. else return ReadShift.call(this, size, 'dbcs');
  3662. size = 2 * size; break;
  3663. /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
  3664. case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3665. case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  3666. /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
  3667. case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
  3668. /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
  3669. case 'lpp4': size = 4 + __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
  3670. /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
  3671. case '8lpp4': size = 4 + __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;
  3672. case 'cstr': size = 0; o = "";
  3673. while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
  3674. o = oo.join(""); break;
  3675. case '_wstr': size = 0; o = "";
  3676. while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
  3677. size+=2; o = oo.join(""); break;
  3678. /* sbcs and dbcs support continue records in the SST way TODO codepages */
  3679. case 'dbcs-cont': o = ""; loc = this.l;
  3680. for(i = 0; i < size; ++i) {
  3681. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3682. w = __readUInt8(this, loc);
  3683. this.l = loc + 1;
  3684. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3685. return oo.join("") + vv;
  3686. }
  3687. oo.push(_getchar(__readUInt16LE(this, loc)));
  3688. loc+=2;
  3689. } o = oo.join(""); size *= 2; break;
  3690. case 'cpstr':
  3691. if(typeof $cptable !== 'undefined') {
  3692. o = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
  3693. break;
  3694. }
  3695. /* falls through */
  3696. case 'sbcs-cont': o = ""; loc = this.l;
  3697. for(i = 0; i != size; ++i) {
  3698. if(this.lens && this.lens.indexOf(loc) !== -1) {
  3699. w = __readUInt8(this, loc);
  3700. this.l = loc + 1;
  3701. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  3702. return oo.join("") + vv;
  3703. }
  3704. oo.push(_getchar(__readUInt8(this, loc)));
  3705. loc+=1;
  3706. } o = oo.join(""); break;
  3707. default:
  3708. switch(size) {
  3709. case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
  3710. case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
  3711. case 4: case -4:
  3712. if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
  3713. else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
  3714. case 8: case -8:
  3715. if(t === 'f') {
  3716. if(size == 8) oR = __double(this, this.l);
  3717. 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);
  3718. this.l += 8; return oR;
  3719. } else size = 8;
  3720. /* falls through */
  3721. case 16: o = __hexlify(this, this.l, size); break;
  3722. }}
  3723. this.l+=size; return o;
  3724. }
  3725. 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); };
  3726. 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); };
  3727. var __writeUInt16LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };
  3728. function WriteShift(t, val, f) {
  3729. var size = 0, i = 0;
  3730. if(f === 'dbcs') {
  3731. for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
  3732. size = 2 * val.length;
  3733. } else if(f === 'sbcs') {
  3734. if(typeof $cptable !== 'undefined' && current_ansi == 874) {
  3735. /* TODO: use tables directly, don't encode */
  3736. for(i = 0; i != val.length; ++i) {
  3737. var cppayload = $cptable.utils.encode(current_ansi, val.charAt(i));
  3738. this[this.l + i] = cppayload[0];
  3739. }
  3740. } else {
  3741. val = val.replace(/[^\x00-\x7F]/g, "_");
  3742. for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
  3743. }
  3744. size = val.length;
  3745. } else if(f === 'hex') {
  3746. for(; i < t; ++i) {
  3747. this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
  3748. } return this;
  3749. } else if(f === 'utf16le') {
  3750. var end = Math.min(this.l + t, this.length);
  3751. for(i = 0; i < Math.min(val.length, t); ++i) {
  3752. var cc = val.charCodeAt(i);
  3753. this[this.l++] = (cc & 0xff);
  3754. this[this.l++] = (cc >> 8);
  3755. }
  3756. while(this.l < end) this[this.l++] = 0;
  3757. return this;
  3758. } else switch(t) {
  3759. case 1: size = 1; this[this.l] = val&0xFF; break;
  3760. case 2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
  3761. 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;
  3762. case 4: size = 4; __writeUInt32LE(this, val, this.l); break;
  3763. case 8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
  3764. /* falls through */
  3765. case 16: break;
  3766. case -4: size = 4; __writeInt32LE(this, val, this.l); break;
  3767. }
  3768. this.l += size; return this;
  3769. }
  3770. function CheckField(hexstr, fld) {
  3771. var m = __hexlify(this,this.l,hexstr.length>>1);
  3772. if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
  3773. this.l += hexstr.length>>1;
  3774. }
  3775. function prep_blob(blob, pos) {
  3776. blob.l = pos;
  3777. blob.read_shift = ReadShift;
  3778. blob.chk = CheckField;
  3779. blob.write_shift = WriteShift;
  3780. }
  3781. function parsenoop(blob, length) { blob.l += length; }
  3782. function new_buf(sz) {
  3783. var o = new_raw_buf(sz);
  3784. prep_blob(o, 0);
  3785. return o;
  3786. }
  3787. /* [MS-XLSB] 2.1.4 Record */
  3788. function recordhopper(data, cb, opts) {
  3789. if(!data) return;
  3790. var tmpbyte, cntbyte, length;
  3791. prep_blob(data, data.l || 0);
  3792. var L = data.length, RT = 0, tgt = 0;
  3793. while(data.l < L) {
  3794. RT = data.read_shift(1);
  3795. if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
  3796. var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
  3797. tmpbyte = data.read_shift(1);
  3798. length = tmpbyte & 0x7F;
  3799. for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
  3800. tgt = data.l + length;
  3801. var d = R.f && R.f(data, length, opts);
  3802. data.l = tgt;
  3803. if(cb(d, R, RT)) return;
  3804. }
  3805. }
  3806. /* control buffer usage for fixed-length buffers */
  3807. function buf_array() {
  3808. var bufs = [], blksz = has_buf ? 256 : 2048;
  3809. var newblk = function ba_newblk(sz) {
  3810. var o = (new_buf(sz));
  3811. prep_blob(o, 0);
  3812. return o;
  3813. };
  3814. var curbuf = newblk(blksz);
  3815. var endbuf = function ba_endbuf() {
  3816. if(!curbuf) return;
  3817. if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
  3818. if(curbuf.length > 0) bufs.push(curbuf);
  3819. curbuf = null;
  3820. };
  3821. var next = function ba_next(sz) {
  3822. if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
  3823. endbuf();
  3824. return (curbuf = newblk(Math.max(sz+1, blksz)));
  3825. };
  3826. var end = function ba_end() {
  3827. endbuf();
  3828. return bconcat(bufs);
  3829. };
  3830. var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };
  3831. return ({ next:next, push:push, end:end, _bufs:bufs });
  3832. }
  3833. function write_record(ba, type, payload, length) {
  3834. var t = +type, l;
  3835. if(isNaN(t)) return; // TODO: throw something here?
  3836. if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
  3837. l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
  3838. if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
  3839. var o = ba.next(l);
  3840. if(t <= 0x7F) o.write_shift(1, t);
  3841. else {
  3842. o.write_shift(1, (t & 0x7F) + 0x80);
  3843. o.write_shift(1, (t >> 7));
  3844. }
  3845. for(var i = 0; i != 4; ++i) {
  3846. if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
  3847. else { o.write_shift(1, length); break; }
  3848. }
  3849. if(length > 0 && is_buf(payload)) ba.push(payload);
  3850. }
  3851. /* XLS ranges enforced */
  3852. function shift_cell_xls(cell, tgt, opts) {
  3853. var out = dup(cell);
  3854. if(tgt.s) {
  3855. if(out.cRel) out.c += tgt.s.c;
  3856. if(out.rRel) out.r += tgt.s.r;
  3857. } else {
  3858. if(out.cRel) out.c += tgt.c;
  3859. if(out.rRel) out.r += tgt.r;
  3860. }
  3861. if(!opts || opts.biff < 12) {
  3862. while(out.c >= 0x100) out.c -= 0x100;
  3863. while(out.r >= 0x10000) out.r -= 0x10000;
  3864. }
  3865. return out;
  3866. }
  3867. function shift_range_xls(cell, range, opts) {
  3868. var out = dup(cell);
  3869. out.s = shift_cell_xls(out.s, range.s, opts);
  3870. out.e = shift_cell_xls(out.e, range.s, opts);
  3871. return out;
  3872. }
  3873. function encode_cell_xls(c, biff) {
  3874. if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
  3875. if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
  3876. var s = encode_cell(c);
  3877. if(!c.cRel && c.cRel != null) s = fix_col(s);
  3878. if(!c.rRel && c.rRel != null) s = fix_row(s);
  3879. return s;
  3880. }
  3881. function encode_range_xls(r, opts) {
  3882. if(r.s.r == 0 && !r.s.rRel) {
  3883. if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
  3884. return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
  3885. }
  3886. }
  3887. if(r.s.c == 0 && !r.s.cRel) {
  3888. if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
  3889. return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
  3890. }
  3891. }
  3892. return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
  3893. }
  3894. function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
  3895. function encode_row(row) { return "" + (row + 1); }
  3896. function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
  3897. function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
  3898. 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; }
  3899. 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; }
  3900. function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
  3901. function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
  3902. function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
  3903. //function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
  3904. function decode_cell(cstr) {
  3905. var R = 0, C = 0;
  3906. for(var i = 0; i < cstr.length; ++i) {
  3907. var cc = cstr.charCodeAt(i);
  3908. if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
  3909. else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
  3910. }
  3911. return { c: C - 1, r:R - 1 };
  3912. }
  3913. //function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
  3914. function encode_cell(cell) {
  3915. var col = cell.c + 1;
  3916. var s="";
  3917. for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
  3918. return s + (cell.r + 1);
  3919. }
  3920. function decode_range(range) {
  3921. var idx = range.indexOf(":");
  3922. if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
  3923. return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
  3924. }
  3925. function encode_range(cs,ce) {
  3926. if(typeof ce === 'undefined' || typeof ce === 'number') {
  3927. return encode_range(cs.s, cs.e);
  3928. }
  3929. if(typeof cs !== 'string') cs = encode_cell((cs));
  3930. if(typeof ce !== 'string') ce = encode_cell((ce));
  3931. return cs == ce ? cs : cs + ":" + ce;
  3932. }
  3933. function safe_decode_range(range) {
  3934. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  3935. var idx = 0, i = 0, cc = 0;
  3936. var len = range.length;
  3937. for(idx = 0; i < len; ++i) {
  3938. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3939. idx = 26*idx + cc;
  3940. }
  3941. o.s.c = --idx;
  3942. for(idx = 0; i < len; ++i) {
  3943. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3944. idx = 10*idx + cc;
  3945. }
  3946. o.s.r = --idx;
  3947. if(i === len || cc != 10) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
  3948. ++i;
  3949. for(idx = 0; i != len; ++i) {
  3950. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  3951. idx = 26*idx + cc;
  3952. }
  3953. o.e.c = --idx;
  3954. for(idx = 0; i != len; ++i) {
  3955. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  3956. idx = 10*idx + cc;
  3957. }
  3958. o.e.r = --idx;
  3959. return o;
  3960. }
  3961. function safe_format_cell(cell, v) {
  3962. var q = (cell.t == 'd' && v instanceof Date);
  3963. if(cell.z != null) try { return (cell.w = SSF_format(cell.z, q ? datenum(v) : v)); } catch(e) { }
  3964. try { return (cell.w = SSF_format((cell.XF||{}).numFmtId||(q ? 14 : 0), q ? datenum(v) : v)); } catch(e) { return ''+v; }
  3965. }
  3966. function format_cell(cell, v, o) {
  3967. if(cell == null || cell.t == null || cell.t == 'z') return "";
  3968. if(cell.w !== undefined) return cell.w;
  3969. if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
  3970. if(cell.t == "e") return BErr[cell.v] || cell.v;
  3971. if(v == undefined) return safe_format_cell(cell, cell.v);
  3972. return safe_format_cell(cell, v);
  3973. }
  3974. function sheet_to_workbook(sheet, opts) {
  3975. var n = opts && opts.sheet ? opts.sheet : "Sheet1";
  3976. var sheets = {}; sheets[n] = sheet;
  3977. return { SheetNames: [n], Sheets: sheets };
  3978. }
  3979. function sheet_add_aoa(_ws, data, opts) {
  3980. var o = opts || {};
  3981. var dense = _ws ? Array.isArray(_ws) : o.dense;
  3982. if(DENSE != null && dense == null) dense = DENSE;
  3983. var ws = _ws || (dense ? ([]) : ({}));
  3984. var _R = 0, _C = 0;
  3985. if(ws && o.origin != null) {
  3986. if(typeof o.origin == 'number') _R = o.origin;
  3987. else {
  3988. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  3989. _R = _origin.r; _C = _origin.c;
  3990. }
  3991. if(!ws["!ref"]) ws["!ref"] = "A1:A1";
  3992. }
  3993. var range = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}});
  3994. if(ws['!ref']) {
  3995. var _range = safe_decode_range(ws['!ref']);
  3996. range.s.c = _range.s.c;
  3997. range.s.r = _range.s.r;
  3998. range.e.c = Math.max(range.e.c, _range.e.c);
  3999. range.e.r = Math.max(range.e.r, _range.e.r);
  4000. if(_R == -1) range.e.r = _R = _range.e.r + 1;
  4001. }
  4002. for(var R = 0; R != data.length; ++R) {
  4003. if(!data[R]) continue;
  4004. if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
  4005. for(var C = 0; C != data[R].length; ++C) {
  4006. if(typeof data[R][C] === 'undefined') continue;
  4007. var cell = ({v: data[R][C] });
  4008. var __R = _R + R, __C = _C + C;
  4009. if(range.s.r > __R) range.s.r = __R;
  4010. if(range.s.c > __C) range.s.c = __C;
  4011. if(range.e.r < __R) range.e.r = __R;
  4012. if(range.e.c < __C) range.e.c = __C;
  4013. if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
  4014. else {
  4015. if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
  4016. if(cell.v === null) {
  4017. if(cell.f) cell.t = 'n';
  4018. else if(o.nullError) { cell.t = 'e'; cell.v = 0; }
  4019. else if(!o.sheetStubs) continue;
  4020. else cell.t = 'z';
  4021. }
  4022. else if(typeof cell.v === 'number') cell.t = 'n';
  4023. else if(typeof cell.v === 'boolean') cell.t = 'b';
  4024. else if(cell.v instanceof Date) {
  4025. cell.z = o.dateNF || table_fmt[14];
  4026. if(o.cellDates) { cell.t = 'd'; cell.w = SSF_format(cell.z, datenum(cell.v)); }
  4027. else { cell.t = 'n'; cell.v = datenum(cell.v); cell.w = SSF_format(cell.z, cell.v); }
  4028. }
  4029. else cell.t = 's';
  4030. }
  4031. if(dense) {
  4032. if(!ws[__R]) ws[__R] = [];
  4033. if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
  4034. ws[__R][__C] = cell;
  4035. } else {
  4036. var cell_ref = encode_cell(({c:__C,r:__R}));
  4037. if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
  4038. ws[cell_ref] = cell;
  4039. }
  4040. }
  4041. }
  4042. if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
  4043. return ws;
  4044. }
  4045. function aoa_to_sheet(data, opts) { return sheet_add_aoa(null, data, opts); }
  4046. function parse_Int32LE(data) {
  4047. return data.read_shift(4, 'i');
  4048. }
  4049. function write_UInt32LE(x, o) {
  4050. if (!o) o = new_buf(4);
  4051. o.write_shift(4, x);
  4052. return o;
  4053. }
  4054. /* [MS-XLSB] 2.5.168 */
  4055. function parse_XLWideString(data) {
  4056. var cchCharacters = data.read_shift(4);
  4057. return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, 'dbcs');
  4058. }
  4059. function write_XLWideString(data, o) {
  4060. var _null = false; if (o == null) { _null = true; o = new_buf(4 + 2 * data.length); }
  4061. o.write_shift(4, data.length);
  4062. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  4063. return _null ? o.slice(0, o.l) : o;
  4064. }
  4065. /* [MS-XLSB] 2.5.91 */
  4066. //function parse_LPWideString(data) {
  4067. // var cchCharacters = data.read_shift(2);
  4068. // return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "utf16le");
  4069. //}
  4070. /* [MS-XLSB] 2.5.143 */
  4071. function parse_StrRun(data) {
  4072. return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
  4073. }
  4074. function write_StrRun(run, o) {
  4075. if (!o) o = new_buf(4);
  4076. o.write_shift(2, run.ich || 0);
  4077. o.write_shift(2, run.ifnt || 0);
  4078. return o;
  4079. }
  4080. /* [MS-XLSB] 2.5.121 */
  4081. function parse_RichStr(data, length) {
  4082. var start = data.l;
  4083. var flags = data.read_shift(1);
  4084. var str = parse_XLWideString(data);
  4085. var rgsStrRun = [];
  4086. var z = ({ t: str, h: str });
  4087. if ((flags & 1) !== 0) { /* fRichStr */
  4088. /* TODO: formatted string */
  4089. var dwSizeStrRun = data.read_shift(4);
  4090. for (var i = 0; i != dwSizeStrRun; ++i) rgsStrRun.push(parse_StrRun(data));
  4091. z.r = rgsStrRun;
  4092. }
  4093. else z.r = [{ ich: 0, ifnt: 0 }];
  4094. //if((flags & 2) !== 0) { /* fExtStr */
  4095. // /* TODO: phonetic string */
  4096. //}
  4097. data.l = start + length;
  4098. return z;
  4099. }
  4100. function write_RichStr(str, o) {
  4101. /* TODO: formatted string */
  4102. var _null = false; if (o == null) { _null = true; o = new_buf(15 + 4 * str.t.length); }
  4103. o.write_shift(1, 0);
  4104. write_XLWideString(str.t, o);
  4105. return _null ? o.slice(0, o.l) : o;
  4106. }
  4107. /* [MS-XLSB] 2.4.328 BrtCommentText (RichStr w/1 run) */
  4108. var parse_BrtCommentText = parse_RichStr;
  4109. function write_BrtCommentText(str, o) {
  4110. /* TODO: formatted string */
  4111. var _null = false; if (o == null) { _null = true; o = new_buf(23 + 4 * str.t.length); }
  4112. o.write_shift(1, 1);
  4113. write_XLWideString(str.t, o);
  4114. o.write_shift(4, 1);
  4115. write_StrRun({ ich: 0, ifnt: 0 }, o);
  4116. return _null ? o.slice(0, o.l) : o;
  4117. }
  4118. /* [MS-XLSB] 2.5.9 */
  4119. function parse_XLSBCell(data) {
  4120. var col = data.read_shift(4);
  4121. var iStyleRef = data.read_shift(2);
  4122. iStyleRef += data.read_shift(1) << 16;
  4123. data.l++; //var fPhShow = data.read_shift(1);
  4124. return { c: col, iStyleRef: iStyleRef };
  4125. }
  4126. function write_XLSBCell(cell, o) {
  4127. if (o == null) o = new_buf(8);
  4128. o.write_shift(-4, cell.c);
  4129. o.write_shift(3, cell.iStyleRef || cell.s);
  4130. o.write_shift(1, 0); /* fPhShow */
  4131. return o;
  4132. }
  4133. /* Short XLSB Cell does not include column */
  4134. function parse_XLSBShortCell(data) {
  4135. var iStyleRef = data.read_shift(2);
  4136. iStyleRef += data.read_shift(1) <<16;
  4137. data.l++; //var fPhShow = data.read_shift(1);
  4138. return { c:-1, iStyleRef: iStyleRef };
  4139. }
  4140. function write_XLSBShortCell(cell, o) {
  4141. if(o == null) o = new_buf(4);
  4142. o.write_shift(3, cell.iStyleRef || cell.s);
  4143. o.write_shift(1, 0); /* fPhShow */
  4144. return o;
  4145. }
  4146. /* [MS-XLSB] 2.5.21 */
  4147. var parse_XLSBCodeName = parse_XLWideString;
  4148. var write_XLSBCodeName = write_XLWideString;
  4149. /* [MS-XLSB] 2.5.166 */
  4150. function parse_XLNullableWideString(data) {
  4151. var cchCharacters = data.read_shift(4);
  4152. return cchCharacters === 0 || cchCharacters === 0xFFFFFFFF ? "" : data.read_shift(cchCharacters, 'dbcs');
  4153. }
  4154. function write_XLNullableWideString(data, o) {
  4155. var _null = false; if (o == null) { _null = true; o = new_buf(127); }
  4156. o.write_shift(4, data.length > 0 ? data.length : 0xFFFFFFFF);
  4157. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  4158. return _null ? o.slice(0, o.l) : o;
  4159. }
  4160. /* [MS-XLSB] 2.5.165 */
  4161. var parse_XLNameWideString = parse_XLWideString;
  4162. //var write_XLNameWideString = write_XLWideString;
  4163. /* [MS-XLSB] 2.5.114 */
  4164. var parse_RelID = parse_XLNullableWideString;
  4165. var write_RelID = write_XLNullableWideString;
  4166. /* [MS-XLS] 2.5.217 ; [MS-XLSB] 2.5.122 */
  4167. function parse_RkNumber(data) {
  4168. var b = data.slice(data.l, data.l + 4);
  4169. var fX100 = (b[0] & 1), fInt = (b[0] & 2);
  4170. data.l += 4;
  4171. var RK = fInt === 0 ? __double([0, 0, 0, 0, (b[0] & 0xFC), b[1], b[2], b[3]], 0) : __readInt32LE(b, 0) >> 2;
  4172. return fX100 ? (RK / 100) : RK;
  4173. }
  4174. function write_RkNumber(data, o) {
  4175. if (o == null) o = new_buf(4);
  4176. var fX100 = 0, fInt = 0, d100 = data * 100;
  4177. if ((data == (data | 0)) && (data >= -(1 << 29)) && (data < (1 << 29))) { fInt = 1; }
  4178. else if ((d100 == (d100 | 0)) && (d100 >= -(1 << 29)) && (d100 < (1 << 29))) { fInt = 1; fX100 = 1; }
  4179. if (fInt) o.write_shift(-4, ((fX100 ? d100 : data) << 2) + (fX100 + 2));
  4180. else throw new Error("unsupported RkNumber " + data); // TODO
  4181. }
  4182. /* [MS-XLSB] 2.5.117 RfX */
  4183. function parse_RfX(data ) {
  4184. var cell = ({ s: {}, e: {} });
  4185. cell.s.r = data.read_shift(4);
  4186. cell.e.r = data.read_shift(4);
  4187. cell.s.c = data.read_shift(4);
  4188. cell.e.c = data.read_shift(4);
  4189. return cell;
  4190. }
  4191. function write_RfX(r, o) {
  4192. if (!o) o = new_buf(16);
  4193. o.write_shift(4, r.s.r);
  4194. o.write_shift(4, r.e.r);
  4195. o.write_shift(4, r.s.c);
  4196. o.write_shift(4, r.e.c);
  4197. return o;
  4198. }
  4199. /* [MS-XLSB] 2.5.153 UncheckedRfX */
  4200. var parse_UncheckedRfX = parse_RfX;
  4201. var write_UncheckedRfX = write_RfX;
  4202. /* [MS-XLSB] 2.5.155 UncheckedSqRfX */
  4203. //function parse_UncheckedSqRfX(data) {
  4204. // var cnt = data.read_shift(4);
  4205. // var out = [];
  4206. // for(var i = 0; i < cnt; ++i) {
  4207. // var rng = parse_UncheckedRfX(data);
  4208. // out.push(encode_range(rng));
  4209. // }
  4210. // return out.join(",");
  4211. //}
  4212. //function write_UncheckedSqRfX(sqrfx) {
  4213. // var parts = sqrfx.split(/\s*,\s*/);
  4214. // var o = new_buf(4); o.write_shift(4, parts.length);
  4215. // var out = [o];
  4216. // parts.forEach(function(rng) {
  4217. // out.push(write_UncheckedRfX(safe_decode_range(rng)));
  4218. // });
  4219. // return bconcat(out);
  4220. //}
  4221. /* [MS-XLS] 2.5.342 ; [MS-XLSB] 2.5.171 */
  4222. /* TODO: error checking, NaN and Infinity values are not valid Xnum */
  4223. function parse_Xnum(data) {
  4224. if(data.length - data.l < 8) throw "XLS Xnum Buffer underflow";
  4225. return data.read_shift(8, 'f');
  4226. }
  4227. function write_Xnum(data, o) { return (o || new_buf(8)).write_shift(8, data, 'f'); }
  4228. /* [MS-XLSB] 2.4.324 BrtColor */
  4229. function parse_BrtColor(data) {
  4230. var out = {};
  4231. var d = data.read_shift(1);
  4232. //var fValidRGB = d & 1;
  4233. var xColorType = d >>> 1;
  4234. var index = data.read_shift(1);
  4235. var nTS = data.read_shift(2, 'i');
  4236. var bR = data.read_shift(1);
  4237. var bG = data.read_shift(1);
  4238. var bB = data.read_shift(1);
  4239. data.l++; //var bAlpha = data.read_shift(1);
  4240. switch (xColorType) {
  4241. case 0: out.auto = 1; break;
  4242. case 1:
  4243. out.index = index;
  4244. var icv = XLSIcv[index];
  4245. /* automatic pseudo index 81 */
  4246. if (icv) out.rgb = rgb2Hex(icv);
  4247. break;
  4248. case 2:
  4249. /* if(!fValidRGB) throw new Error("invalid"); */
  4250. out.rgb = rgb2Hex([bR, bG, bB]);
  4251. break;
  4252. case 3: out.theme = index; break;
  4253. }
  4254. if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;
  4255. return out;
  4256. }
  4257. function write_BrtColor(color, o) {
  4258. if (!o) o = new_buf(8);
  4259. if (!color || color.auto) { o.write_shift(4, 0); o.write_shift(4, 0); return o; }
  4260. if (color.index != null) {
  4261. o.write_shift(1, 0x02);
  4262. o.write_shift(1, color.index);
  4263. } else if (color.theme != null) {
  4264. o.write_shift(1, 0x06);
  4265. o.write_shift(1, color.theme);
  4266. } else {
  4267. o.write_shift(1, 0x05);
  4268. o.write_shift(1, 0);
  4269. }
  4270. var nTS = color.tint || 0;
  4271. if (nTS > 0) nTS *= 32767;
  4272. else if (nTS < 0) nTS *= 32768;
  4273. o.write_shift(2, nTS);
  4274. if (!color.rgb || color.theme != null) {
  4275. o.write_shift(2, 0);
  4276. o.write_shift(1, 0);
  4277. o.write_shift(1, 0);
  4278. } else {
  4279. var rgb = (color.rgb || 'FFFFFF');
  4280. if (typeof rgb == 'number') rgb = ("000000" + rgb.toString(16)).slice(-6);
  4281. o.write_shift(1, parseInt(rgb.slice(0, 2), 16));
  4282. o.write_shift(1, parseInt(rgb.slice(2, 4), 16));
  4283. o.write_shift(1, parseInt(rgb.slice(4, 6), 16));
  4284. o.write_shift(1, 0xFF);
  4285. }
  4286. return o;
  4287. }
  4288. /* [MS-XLSB] 2.5.52 */
  4289. function parse_FontFlags(data) {
  4290. var d = data.read_shift(1);
  4291. data.l++;
  4292. var out = {
  4293. fBold: d & 0x01,
  4294. fItalic: d & 0x02,
  4295. fUnderline: d & 0x04,
  4296. fStrikeout: d & 0x08,
  4297. fOutline: d & 0x10,
  4298. fShadow: d & 0x20,
  4299. fCondense: d & 0x40,
  4300. fExtend: d & 0x80
  4301. };
  4302. return out;
  4303. }
  4304. function write_FontFlags(font, o) {
  4305. if (!o) o = new_buf(2);
  4306. var grbit =
  4307. (font.italic ? 0x02 : 0) |
  4308. (font.strike ? 0x08 : 0) |
  4309. (font.outline ? 0x10 : 0) |
  4310. (font.shadow ? 0x20 : 0) |
  4311. (font.condense ? 0x40 : 0) |
  4312. (font.extend ? 0x80 : 0);
  4313. o.write_shift(1, grbit);
  4314. o.write_shift(1, 0);
  4315. return o;
  4316. }
  4317. /* [MS-OLEDS] 2.3.1 and 2.3.2 */
  4318. function parse_ClipboardFormatOrString(o, w) {
  4319. // $FlowIgnore
  4320. var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
  4321. var m = o.read_shift(4);
  4322. switch (m) {
  4323. case 0x00000000: return "";
  4324. case 0xffffffff: case 0xfffffffe: return ClipFmt[o.read_shift(4)] || "";
  4325. }
  4326. if (m > 0x190) throw new Error("Unsupported Clipboard: " + m.toString(16));
  4327. o.l -= 4;
  4328. return o.read_shift(0, w == 1 ? "lpstr" : "lpwstr");
  4329. }
  4330. function parse_ClipboardFormatOrAnsiString(o) { return parse_ClipboardFormatOrString(o, 1); }
  4331. function parse_ClipboardFormatOrUnicodeString(o) { return parse_ClipboardFormatOrString(o, 2); }
  4332. /* [MS-OLEPS] 2.2 PropertyType */
  4333. // Note: some tree shakers cannot handle VT_VECTOR | $CONST, hence extra vars
  4334. //var VT_EMPTY = 0x0000;
  4335. //var VT_NULL = 0x0001;
  4336. var VT_I2 = 0x0002;
  4337. var VT_I4 = 0x0003;
  4338. //var VT_R4 = 0x0004;
  4339. //var VT_R8 = 0x0005;
  4340. //var VT_CY = 0x0006;
  4341. //var VT_DATE = 0x0007;
  4342. //var VT_BSTR = 0x0008;
  4343. //var VT_ERROR = 0x000A;
  4344. var VT_BOOL = 0x000B;
  4345. var VT_VARIANT = 0x000C;
  4346. //var VT_DECIMAL = 0x000E;
  4347. //var VT_I1 = 0x0010;
  4348. //var VT_UI1 = 0x0011;
  4349. //var VT_UI2 = 0x0012;
  4350. var VT_UI4 = 0x0013;
  4351. //var VT_I8 = 0x0014;
  4352. //var VT_UI8 = 0x0015;
  4353. //var VT_INT = 0x0016;
  4354. //var VT_UINT = 0x0017;
  4355. var VT_LPSTR = 0x001E;
  4356. //var VT_LPWSTR = 0x001F;
  4357. var VT_FILETIME = 0x0040;
  4358. var VT_BLOB = 0x0041;
  4359. //var VT_STREAM = 0x0042;
  4360. //var VT_STORAGE = 0x0043;
  4361. //var VT_STREAMED_Object = 0x0044;
  4362. //var VT_STORED_Object = 0x0045;
  4363. //var VT_BLOB_Object = 0x0046;
  4364. var VT_CF = 0x0047;
  4365. //var VT_CLSID = 0x0048;
  4366. //var VT_VERSIONED_STREAM = 0x0049;
  4367. var VT_VECTOR = 0x1000;
  4368. var VT_VECTOR_VARIANT = 0x100C;
  4369. var VT_VECTOR_LPSTR = 0x101E;
  4370. //var VT_ARRAY = 0x2000;
  4371. var VT_STRING = 0x0050; // 2.3.3.1.11 VtString
  4372. var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString
  4373. var VT_CUSTOM = [VT_STRING, VT_USTR];
  4374. /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
  4375. var DocSummaryPIDDSI = {
  4376. 0x01: { n: 'CodePage', t: VT_I2 },
  4377. 0x02: { n: 'Category', t: VT_STRING },
  4378. 0x03: { n: 'PresentationFormat', t: VT_STRING },
  4379. 0x04: { n: 'ByteCount', t: VT_I4 },
  4380. 0x05: { n: 'LineCount', t: VT_I4 },
  4381. 0x06: { n: 'ParagraphCount', t: VT_I4 },
  4382. 0x07: { n: 'SlideCount', t: VT_I4 },
  4383. 0x08: { n: 'NoteCount', t: VT_I4 },
  4384. 0x09: { n: 'HiddenCount', t: VT_I4 },
  4385. 0x0a: { n: 'MultimediaClipCount', t: VT_I4 },
  4386. 0x0b: { n: 'ScaleCrop', t: VT_BOOL },
  4387. 0x0c: { n: 'HeadingPairs', t: VT_VECTOR_VARIANT /* VT_VECTOR | VT_VARIANT */ },
  4388. 0x0d: { n: 'TitlesOfParts', t: VT_VECTOR_LPSTR /* VT_VECTOR | VT_LPSTR */ },
  4389. 0x0e: { n: 'Manager', t: VT_STRING },
  4390. 0x0f: { n: 'Company', t: VT_STRING },
  4391. 0x10: { n: 'LinksUpToDate', t: VT_BOOL },
  4392. 0x11: { n: 'CharacterCount', t: VT_I4 },
  4393. 0x13: { n: 'SharedDoc', t: VT_BOOL },
  4394. 0x16: { n: 'HyperlinksChanged', t: VT_BOOL },
  4395. 0x17: { n: 'AppVersion', t: VT_I4, p: 'version' },
  4396. 0x18: { n: 'DigSig', t: VT_BLOB },
  4397. 0x1A: { n: 'ContentType', t: VT_STRING },
  4398. 0x1B: { n: 'ContentStatus', t: VT_STRING },
  4399. 0x1C: { n: 'Language', t: VT_STRING },
  4400. 0x1D: { n: 'Version', t: VT_STRING },
  4401. 0xFF: {},
  4402. /* [MS-OLEPS] 2.18 */
  4403. 0x80000000: { n: 'Locale', t: VT_UI4 },
  4404. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  4405. 0x72627262: {}
  4406. };
  4407. /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
  4408. var SummaryPIDSI = {
  4409. 0x01: { n: 'CodePage', t: VT_I2 },
  4410. 0x02: { n: 'Title', t: VT_STRING },
  4411. 0x03: { n: 'Subject', t: VT_STRING },
  4412. 0x04: { n: 'Author', t: VT_STRING },
  4413. 0x05: { n: 'Keywords', t: VT_STRING },
  4414. 0x06: { n: 'Comments', t: VT_STRING },
  4415. 0x07: { n: 'Template', t: VT_STRING },
  4416. 0x08: { n: 'LastAuthor', t: VT_STRING },
  4417. 0x09: { n: 'RevNumber', t: VT_STRING },
  4418. 0x0A: { n: 'EditTime', t: VT_FILETIME },
  4419. 0x0B: { n: 'LastPrinted', t: VT_FILETIME },
  4420. 0x0C: { n: 'CreatedDate', t: VT_FILETIME },
  4421. 0x0D: { n: 'ModifiedDate', t: VT_FILETIME },
  4422. 0x0E: { n: 'PageCount', t: VT_I4 },
  4423. 0x0F: { n: 'WordCount', t: VT_I4 },
  4424. 0x10: { n: 'CharCount', t: VT_I4 },
  4425. 0x11: { n: 'Thumbnail', t: VT_CF },
  4426. 0x12: { n: 'Application', t: VT_STRING },
  4427. 0x13: { n: 'DocSecurity', t: VT_I4 },
  4428. 0xFF: {},
  4429. /* [MS-OLEPS] 2.18 */
  4430. 0x80000000: { n: 'Locale', t: VT_UI4 },
  4431. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  4432. 0x72627262: {}
  4433. };
  4434. /* [MS-XLS] 2.4.63 Country/Region codes */
  4435. var CountryEnum = {
  4436. 0x0001: "US", // United States
  4437. 0x0002: "CA", // Canada
  4438. 0x0003: "", // Latin America (except Brazil)
  4439. 0x0007: "RU", // Russia
  4440. 0x0014: "EG", // Egypt
  4441. 0x001E: "GR", // Greece
  4442. 0x001F: "NL", // Netherlands
  4443. 0x0020: "BE", // Belgium
  4444. 0x0021: "FR", // France
  4445. 0x0022: "ES", // Spain
  4446. 0x0024: "HU", // Hungary
  4447. 0x0027: "IT", // Italy
  4448. 0x0029: "CH", // Switzerland
  4449. 0x002B: "AT", // Austria
  4450. 0x002C: "GB", // United Kingdom
  4451. 0x002D: "DK", // Denmark
  4452. 0x002E: "SE", // Sweden
  4453. 0x002F: "NO", // Norway
  4454. 0x0030: "PL", // Poland
  4455. 0x0031: "DE", // Germany
  4456. 0x0034: "MX", // Mexico
  4457. 0x0037: "BR", // Brazil
  4458. 0x003d: "AU", // Australia
  4459. 0x0040: "NZ", // New Zealand
  4460. 0x0042: "TH", // Thailand
  4461. 0x0051: "JP", // Japan
  4462. 0x0052: "KR", // Korea
  4463. 0x0054: "VN", // Viet Nam
  4464. 0x0056: "CN", // China
  4465. 0x005A: "TR", // Turkey
  4466. 0x0069: "JS", // Ramastan
  4467. 0x00D5: "DZ", // Algeria
  4468. 0x00D8: "MA", // Morocco
  4469. 0x00DA: "LY", // Libya
  4470. 0x015F: "PT", // Portugal
  4471. 0x0162: "IS", // Iceland
  4472. 0x0166: "FI", // Finland
  4473. 0x01A4: "CZ", // Czech Republic
  4474. 0x0376: "TW", // Taiwan
  4475. 0x03C1: "LB", // Lebanon
  4476. 0x03C2: "JO", // Jordan
  4477. 0x03C3: "SY", // Syria
  4478. 0x03C4: "IQ", // Iraq
  4479. 0x03C5: "KW", // Kuwait
  4480. 0x03C6: "SA", // Saudi Arabia
  4481. 0x03CB: "AE", // United Arab Emirates
  4482. 0x03CC: "IL", // Israel
  4483. 0x03CE: "QA", // Qatar
  4484. 0x03D5: "IR", // Iran
  4485. 0xFFFF: "US" // United States
  4486. };
  4487. /* [MS-XLS] 2.5.127 */
  4488. var XLSFillPattern = [
  4489. null,
  4490. 'solid',
  4491. 'mediumGray',
  4492. 'darkGray',
  4493. 'lightGray',
  4494. 'darkHorizontal',
  4495. 'darkVertical',
  4496. 'darkDown',
  4497. 'darkUp',
  4498. 'darkGrid',
  4499. 'darkTrellis',
  4500. 'lightHorizontal',
  4501. 'lightVertical',
  4502. 'lightDown',
  4503. 'lightUp',
  4504. 'lightGrid',
  4505. 'lightTrellis',
  4506. 'gray125',
  4507. 'gray0625'
  4508. ];
  4509. function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }
  4510. /* [MS-XLS] 2.5.161 */
  4511. /* [MS-XLSB] 2.5.75 Icv */
  4512. var _XLSIcv = rgbify([
  4513. /* Color Constants */
  4514. 0x000000,
  4515. 0xFFFFFF,
  4516. 0xFF0000,
  4517. 0x00FF00,
  4518. 0x0000FF,
  4519. 0xFFFF00,
  4520. 0xFF00FF,
  4521. 0x00FFFF,
  4522. /* Overridable Defaults */
  4523. 0x000000,
  4524. 0xFFFFFF,
  4525. 0xFF0000,
  4526. 0x00FF00,
  4527. 0x0000FF,
  4528. 0xFFFF00,
  4529. 0xFF00FF,
  4530. 0x00FFFF,
  4531. 0x800000,
  4532. 0x008000,
  4533. 0x000080,
  4534. 0x808000,
  4535. 0x800080,
  4536. 0x008080,
  4537. 0xC0C0C0,
  4538. 0x808080,
  4539. 0x9999FF,
  4540. 0x993366,
  4541. 0xFFFFCC,
  4542. 0xCCFFFF,
  4543. 0x660066,
  4544. 0xFF8080,
  4545. 0x0066CC,
  4546. 0xCCCCFF,
  4547. 0x000080,
  4548. 0xFF00FF,
  4549. 0xFFFF00,
  4550. 0x00FFFF,
  4551. 0x800080,
  4552. 0x800000,
  4553. 0x008080,
  4554. 0x0000FF,
  4555. 0x00CCFF,
  4556. 0xCCFFFF,
  4557. 0xCCFFCC,
  4558. 0xFFFF99,
  4559. 0x99CCFF,
  4560. 0xFF99CC,
  4561. 0xCC99FF,
  4562. 0xFFCC99,
  4563. 0x3366FF,
  4564. 0x33CCCC,
  4565. 0x99CC00,
  4566. 0xFFCC00,
  4567. 0xFF9900,
  4568. 0xFF6600,
  4569. 0x666699,
  4570. 0x969696,
  4571. 0x003366,
  4572. 0x339966,
  4573. 0x003300,
  4574. 0x333300,
  4575. 0x993300,
  4576. 0x993366,
  4577. 0x333399,
  4578. 0x333333,
  4579. /* Other entries to appease BIFF8/12 */
  4580. 0xFFFFFF, /* 0x40 icvForeground ?? */
  4581. 0x000000, /* 0x41 icvBackground ?? */
  4582. 0x000000, /* 0x42 icvFrame ?? */
  4583. 0x000000, /* 0x43 icv3D ?? */
  4584. 0x000000, /* 0x44 icv3DText ?? */
  4585. 0x000000, /* 0x45 icv3DHilite ?? */
  4586. 0x000000, /* 0x46 icv3DShadow ?? */
  4587. 0x000000, /* 0x47 icvHilite ?? */
  4588. 0x000000, /* 0x48 icvCtlText ?? */
  4589. 0x000000, /* 0x49 icvCtlScrl ?? */
  4590. 0x000000, /* 0x4A icvCtlInv ?? */
  4591. 0x000000, /* 0x4B icvCtlBody ?? */
  4592. 0x000000, /* 0x4C icvCtlFrame ?? */
  4593. 0x000000, /* 0x4D icvCtlFore ?? */
  4594. 0x000000, /* 0x4E icvCtlBack ?? */
  4595. 0x000000, /* 0x4F icvCtlNeutral */
  4596. 0x000000, /* 0x50 icvInfoBk ?? */
  4597. 0x000000 /* 0x51 icvInfoText ?? */
  4598. ]);
  4599. var XLSIcv = dup(_XLSIcv);
  4600. /* [MS-XLSB] 2.5.97.2 */
  4601. var BErr = {
  4602. 0x00: "#NULL!",
  4603. 0x07: "#DIV/0!",
  4604. 0x0F: "#VALUE!",
  4605. 0x17: "#REF!",
  4606. 0x1D: "#NAME?",
  4607. 0x24: "#NUM!",
  4608. 0x2A: "#N/A",
  4609. 0x2B: "#GETTING_DATA",
  4610. 0xFF: "#WTF?"
  4611. };
  4612. //var RBErr = evert_num(BErr);
  4613. var RBErr = {
  4614. "#NULL!": 0x00,
  4615. "#DIV/0!": 0x07,
  4616. "#VALUE!": 0x0F,
  4617. "#REF!": 0x17,
  4618. "#NAME?": 0x1D,
  4619. "#NUM!": 0x24,
  4620. "#N/A": 0x2A,
  4621. "#GETTING_DATA": 0x2B,
  4622. "#WTF?": 0xFF
  4623. };
  4624. /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
  4625. /* 12.3 Part Summary <SpreadsheetML> */
  4626. /* 14.2 Part Summary <DrawingML> */
  4627. /* [MS-XLSX] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
  4628. var ct2type/*{[string]:string}*/ = ({
  4629. /* Workbook */
  4630. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  4631. "application/vnd.ms-excel.sheet.macroEnabled.main+xml": "workbooks",
  4632. "application/vnd.ms-excel.sheet.binary.macroEnabled.main": "workbooks",
  4633. "application/vnd.ms-excel.addin.macroEnabled.main+xml": "workbooks",
  4634. "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": "workbooks",
  4635. /* Worksheet */
  4636. "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": "sheets",
  4637. "application/vnd.ms-excel.worksheet": "sheets",
  4638. "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
  4639. /* Chartsheet */
  4640. "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "charts",
  4641. "application/vnd.ms-excel.chartsheet": "charts",
  4642. /* Macrosheet */
  4643. "application/vnd.ms-excel.macrosheet+xml": "macros",
  4644. "application/vnd.ms-excel.macrosheet": "macros",
  4645. "application/vnd.ms-excel.intlmacrosheet": "TODO",
  4646. "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
  4647. /* Dialogsheet */
  4648. "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "dialogs",
  4649. "application/vnd.ms-excel.dialogsheet": "dialogs",
  4650. /* Shared Strings */
  4651. "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs",
  4652. "application/vnd.ms-excel.sharedStrings": "strs",
  4653. /* Styles */
  4654. "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": "styles",
  4655. "application/vnd.ms-excel.styles": "styles",
  4656. /* File Properties */
  4657. "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  4658. "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  4659. "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  4660. /* Custom Data Properties */
  4661. "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  4662. "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  4663. /* Comments */
  4664. "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments",
  4665. "application/vnd.ms-excel.comments": "comments",
  4666. "application/vnd.ms-excel.threadedcomments+xml": "threadedcomments",
  4667. "application/vnd.ms-excel.person+xml": "people",
  4668. /* Metadata (Stock/Geography and Dynamic Array) */
  4669. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "metadata",
  4670. "application/vnd.ms-excel.sheetMetadata": "metadata",
  4671. /* PivotTable */
  4672. "application/vnd.ms-excel.pivotTable": "TODO",
  4673. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  4674. /* Chart Objects */
  4675. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  4676. /* Chart Colors */
  4677. "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  4678. /* Chart Style */
  4679. "application/vnd.ms-office.chartstyle+xml": "TODO",
  4680. /* Chart Advanced */
  4681. "application/vnd.ms-office.chartex+xml": "TODO",
  4682. /* Calculation Chain */
  4683. "application/vnd.ms-excel.calcChain": "calcchains",
  4684. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  4685. /* Printer Settings */
  4686. "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  4687. /* ActiveX */
  4688. "application/vnd.ms-office.activeX": "TODO",
  4689. "application/vnd.ms-office.activeX+xml": "TODO",
  4690. /* Custom Toolbars */
  4691. "application/vnd.ms-excel.attachedToolbars": "TODO",
  4692. /* External Data Connections */
  4693. "application/vnd.ms-excel.connections": "TODO",
  4694. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  4695. /* External Links */
  4696. "application/vnd.ms-excel.externalLink": "links",
  4697. "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  4698. /* PivotCache */
  4699. "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  4700. "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  4701. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  4702. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  4703. /* Query Table */
  4704. "application/vnd.ms-excel.queryTable": "TODO",
  4705. "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  4706. /* Shared Workbook */
  4707. "application/vnd.ms-excel.userNames": "TODO",
  4708. "application/vnd.ms-excel.revisionHeaders": "TODO",
  4709. "application/vnd.ms-excel.revisionLog": "TODO",
  4710. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  4711. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  4712. "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  4713. /* Single Cell Table */
  4714. "application/vnd.ms-excel.tableSingleCells": "TODO",
  4715. "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  4716. /* Slicer */
  4717. "application/vnd.ms-excel.slicer": "TODO",
  4718. "application/vnd.ms-excel.slicerCache": "TODO",
  4719. "application/vnd.ms-excel.slicer+xml": "TODO",
  4720. "application/vnd.ms-excel.slicerCache+xml": "TODO",
  4721. /* Sort Map */
  4722. "application/vnd.ms-excel.wsSortMap": "TODO",
  4723. /* Table */
  4724. "application/vnd.ms-excel.table": "TODO",
  4725. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  4726. /* Themes */
  4727. "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  4728. /* Theme Override */
  4729. "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  4730. /* Timeline */
  4731. "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
  4732. "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
  4733. /* VBA */
  4734. "application/vnd.ms-office.vbaProject": "vba",
  4735. "application/vnd.ms-office.vbaProjectSignature": "TODO",
  4736. /* Volatile Dependencies */
  4737. "application/vnd.ms-office.volatileDependencies": "TODO",
  4738. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  4739. /* Control Properties */
  4740. "application/vnd.ms-excel.controlproperties+xml": "TODO",
  4741. /* Data Model */
  4742. "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  4743. /* Survey */
  4744. "application/vnd.ms-excel.Survey+xml": "TODO",
  4745. /* Drawing */
  4746. "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  4747. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  4748. "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  4749. "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  4750. "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  4751. "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  4752. /* VML */
  4753. "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  4754. "application/vnd.openxmlformats-package.relationships+xml": "rels",
  4755. "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  4756. /* Image */
  4757. "image/png": "TODO",
  4758. "sheet": "js"
  4759. });
  4760. var CT_LIST = {
  4761. workbooks: {
  4762. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  4763. xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
  4764. xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
  4765. xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
  4766. xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
  4767. },
  4768. strs: { /* Shared Strings */
  4769. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
  4770. xlsb: "application/vnd.ms-excel.sharedStrings"
  4771. },
  4772. comments: { /* Comments */
  4773. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  4774. xlsb: "application/vnd.ms-excel.comments"
  4775. },
  4776. sheets: { /* Worksheet */
  4777. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  4778. xlsb: "application/vnd.ms-excel.worksheet"
  4779. },
  4780. charts: { /* Chartsheet */
  4781. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
  4782. xlsb: "application/vnd.ms-excel.chartsheet"
  4783. },
  4784. dialogs: { /* Dialogsheet */
  4785. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
  4786. xlsb: "application/vnd.ms-excel.dialogsheet"
  4787. },
  4788. macros: { /* Macrosheet (Excel 4.0 Macros) */
  4789. xlsx: "application/vnd.ms-excel.macrosheet+xml",
  4790. xlsb: "application/vnd.ms-excel.macrosheet"
  4791. },
  4792. metadata: { /* Metadata (Stock/Geography and Dynamic Array) */
  4793. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",
  4794. xlsb: "application/vnd.ms-excel.sheetMetadata"
  4795. },
  4796. styles: { /* Styles */
  4797. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
  4798. xlsb: "application/vnd.ms-excel.styles"
  4799. }
  4800. };
  4801. function new_ct() {
  4802. return ({
  4803. workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
  4804. rels:[], strs:[], comments:[], threadedcomments:[], links:[],
  4805. coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
  4806. calcchains:[], vba: [], drawings: [], metadata: [], people:[],
  4807. TODO:[], xmlns: "" });
  4808. }
  4809. function parse_ct(data) {
  4810. var ct = new_ct();
  4811. if(!data || !data.match) return ct;
  4812. var ctext = {};
  4813. (data.match(tagregex)||[]).forEach(function(x) {
  4814. var y = parsexmltag(x);
  4815. switch(y[0].replace(nsregex,"<")) {
  4816. case '<?xml': break;
  4817. case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
  4818. case '<Default': ctext[y.Extension] = y.ContentType; break;
  4819. case '<Override':
  4820. if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
  4821. break;
  4822. }
  4823. });
  4824. if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  4825. ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  4826. ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  4827. ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  4828. ct.defaults = ctext;
  4829. delete ct.calcchains;
  4830. return ct;
  4831. }
  4832. function write_ct(ct, opts) {
  4833. var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);
  4834. var o = [], v;
  4835. o[o.length] = (XML_HEADER);
  4836. o[o.length] = writextag('Types', null, {
  4837. 'xmlns': XMLNS.CT,
  4838. 'xmlns:xsd': XMLNS.xsd,
  4839. 'xmlns:xsi': XMLNS.xsi
  4840. });
  4841. o = o.concat([
  4842. ['xml', 'application/xml'],
  4843. ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
  4844. ['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
  4845. ['data', 'application/vnd.openxmlformats-officedocument.model+data'],
  4846. /* from test files */
  4847. ['bmp', 'image/bmp'],
  4848. ['png', 'image/png'],
  4849. ['gif', 'image/gif'],
  4850. ['emf', 'image/x-emf'],
  4851. ['wmf', 'image/x-wmf'],
  4852. ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
  4853. ['tif', 'image/tiff'], ['tiff', 'image/tiff'],
  4854. ['pdf', 'application/pdf'],
  4855. ['rels', 'application/vnd.openxmlformats-package.relationships+xml']
  4856. ].map(function(x) {
  4857. return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
  4858. }));
  4859. /* only write first instance */
  4860. var f1 = function(w) {
  4861. if(ct[w] && ct[w].length > 0) {
  4862. v = ct[w][0];
  4863. o[o.length] = (writextag('Override', null, {
  4864. 'PartName': (v[0] == '/' ? "":"/") + v,
  4865. 'ContentType': CT_LIST[w][opts.bookType] || CT_LIST[w]['xlsx']
  4866. }));
  4867. }
  4868. };
  4869. /* book type-specific */
  4870. var f2 = function(w) {
  4871. (ct[w]||[]).forEach(function(v) {
  4872. o[o.length] = (writextag('Override', null, {
  4873. 'PartName': (v[0] == '/' ? "":"/") + v,
  4874. 'ContentType': CT_LIST[w][opts.bookType] || CT_LIST[w]['xlsx']
  4875. }));
  4876. });
  4877. };
  4878. /* standard type */
  4879. var f3 = function(t) {
  4880. (ct[t]||[]).forEach(function(v) {
  4881. o[o.length] = (writextag('Override', null, {
  4882. 'PartName': (v[0] == '/' ? "":"/") + v,
  4883. 'ContentType': type2ct[t][0]
  4884. }));
  4885. });
  4886. };
  4887. f1('workbooks');
  4888. f2('sheets');
  4889. f2('charts');
  4890. f3('themes');
  4891. ['strs', 'styles'].forEach(f1);
  4892. ['coreprops', 'extprops', 'custprops'].forEach(f3);
  4893. f3('vba');
  4894. f3('comments');
  4895. f3('threadedcomments');
  4896. f3('drawings');
  4897. f2('metadata');
  4898. f3('people');
  4899. if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
  4900. return o.join("");
  4901. }
  4902. /* 9.3 Relationships */
  4903. var RELS = ({
  4904. WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4905. SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  4906. HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  4907. VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  4908. XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  4909. XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  4910. XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  4911. CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  4912. CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  4913. CMNT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
  4914. CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
  4915. EXT_PROPS: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
  4916. CUST_PROPS: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
  4917. SST: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
  4918. STY: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
  4919. THEME: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
  4920. CHART: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",
  4921. CHARTEX: "http://schemas.microsoft.com/office/2014/relationships/chartEx",
  4922. CS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet",
  4923. WS: [
  4924. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  4925. "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  4926. ],
  4927. DS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet",
  4928. MS: "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet",
  4929. IMG: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
  4930. DRAW: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",
  4931. XLMETA: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata",
  4932. TCMNT: "http://schemas.microsoft.com/office/2017/10/relationships/threadedComment",
  4933. PEOPLE: "http://schemas.microsoft.com/office/2017/10/relationships/person",
  4934. VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
  4935. });
  4936. /* 9.3.3 Representing Relationships */
  4937. function get_rels_path(file) {
  4938. var n = file.lastIndexOf("/");
  4939. return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
  4940. }
  4941. function parse_rels(data, currentFilePath) {
  4942. var rels = {"!id":{}};
  4943. if (!data) return rels;
  4944. if (currentFilePath.charAt(0) !== '/') {
  4945. currentFilePath = '/'+currentFilePath;
  4946. }
  4947. var hash = {};
  4948. (data.match(tagregex)||[]).forEach(function(x) {
  4949. var y = parsexmltag(x);
  4950. /* 9.3.2.2 OPC_Relationships */
  4951. if (y[0] === '<Relationship') {
  4952. var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; if(y.TargetMode) rel.TargetMode = y.TargetMode;
  4953. var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
  4954. rels[canonictarget] = rel;
  4955. hash[y.Id] = rel;
  4956. }
  4957. });
  4958. rels["!id"] = hash;
  4959. return rels;
  4960. }
  4961. /* TODO */
  4962. function write_rels(rels) {
  4963. var o = [XML_HEADER, writextag('Relationships', null, {
  4964. //'xmlns:ns0': XMLNS.RELS,
  4965. 'xmlns': XMLNS.RELS
  4966. })];
  4967. keys(rels['!id']).forEach(function(rid) {
  4968. o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
  4969. });
  4970. if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
  4971. return o.join("");
  4972. }
  4973. function add_rels(rels, rId, f, type, relobj, targetmode) {
  4974. if(!relobj) relobj = {};
  4975. if(!rels['!id']) rels['!id'] = {};
  4976. if(!rels['!idx']) rels['!idx'] = 1;
  4977. if(rId < 0) for(rId = rels['!idx']; rels['!id']['rId' + rId]; ++rId){/* empty */}
  4978. rels['!idx'] = rId + 1;
  4979. relobj.Id = 'rId' + rId;
  4980. relobj.Type = type;
  4981. relobj.Target = f;
  4982. if(targetmode) relobj.TargetMode = targetmode;
  4983. else if([RELS.HLINK, RELS.XPATH, RELS.XMISS].indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
  4984. if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
  4985. rels['!id'][relobj.Id] = relobj;
  4986. rels[('/' + relobj.Target).replace("//","/")] = relobj;
  4987. return rId;
  4988. }
  4989. /* Open Document Format for Office Applications (OpenDocument) Version 1.2 */
  4990. /* Part 3 Section 4 Manifest File */
  4991. var CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
  4992. function parse_manifest(d, opts) {
  4993. var str = xlml_normalize(d);
  4994. var Rn;
  4995. var FEtag;
  4996. while((Rn = xlmlregex.exec(str))) switch(Rn[3]) {
  4997. case 'manifest': break; // 4.2 <manifest:manifest>
  4998. case 'file-entry': // 4.3 <manifest:file-entry>
  4999. FEtag = parsexmltag(Rn[0], false);
  5000. if(FEtag.path == '/' && FEtag.type !== CT_ODS) throw new Error("This OpenDocument is not a spreadsheet");
  5001. break;
  5002. case 'encryption-data': // 4.4 <manifest:encryption-data>
  5003. case 'algorithm': // 4.5 <manifest:algorithm>
  5004. case 'start-key-generation': // 4.6 <manifest:start-key-generation>
  5005. case 'key-derivation': // 4.7 <manifest:key-derivation>
  5006. throw new Error("Unsupported ODS Encryption");
  5007. default: if(opts && opts.WTF) throw Rn;
  5008. }
  5009. }
  5010. function write_manifest(manifest) {
  5011. var o = [XML_HEADER];
  5012. o.push('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">\n');
  5013. o.push(' <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>\n');
  5014. 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');
  5015. o.push('</manifest:manifest>');
  5016. return o.join("");
  5017. }
  5018. /* Part 3 Section 6 Metadata Manifest File */
  5019. function write_rdf_type(file, res, tag) {
  5020. return [
  5021. ' <rdf:Description rdf:about="' + file + '">\n',
  5022. ' <rdf:type rdf:resource="http://docs.oasis-open.org/ns/office/1.2/meta/' + (tag || "odf") + '#' + res + '"/>\n',
  5023. ' </rdf:Description>\n'
  5024. ].join("");
  5025. }
  5026. function write_rdf_has(base, file) {
  5027. return [
  5028. ' <rdf:Description rdf:about="' + base + '">\n',
  5029. ' <ns0:hasPart xmlns:ns0="http://docs.oasis-open.org/ns/office/1.2/meta/pkg#" rdf:resource="' + file + '"/>\n',
  5030. ' </rdf:Description>\n'
  5031. ].join("");
  5032. }
  5033. function write_rdf(rdf) {
  5034. var o = [XML_HEADER];
  5035. o.push('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n');
  5036. for(var i = 0; i != rdf.length; ++i) {
  5037. o.push(write_rdf_type(rdf[i][0], rdf[i][1]));
  5038. o.push(write_rdf_has("",rdf[i][0]));
  5039. }
  5040. o.push(write_rdf_type("","Document", "pkg"));
  5041. o.push('</rdf:RDF>');
  5042. return o.join("");
  5043. }
  5044. /* TODO: pull properties */
  5045. function write_meta_ods() {
  5046. 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>';
  5047. }
  5048. /* ECMA-376 Part II 11.1 Core Properties Part */
  5049. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  5050. var CORE_PROPS = [
  5051. ["cp:category", "Category"],
  5052. ["cp:contentStatus", "ContentStatus"],
  5053. ["cp:keywords", "Keywords"],
  5054. ["cp:lastModifiedBy", "LastAuthor"],
  5055. ["cp:lastPrinted", "LastPrinted"],
  5056. ["cp:revision", "RevNumber"],
  5057. ["cp:version", "Version"],
  5058. ["dc:creator", "Author"],
  5059. ["dc:description", "Comments"],
  5060. ["dc:identifier", "Identifier"],
  5061. ["dc:language", "Language"],
  5062. ["dc:subject", "Subject"],
  5063. ["dc:title", "Title"],
  5064. ["dcterms:created", "CreatedDate", 'date'],
  5065. ["dcterms:modified", "ModifiedDate", 'date']
  5066. ];
  5067. var CORE_PROPS_REGEX = (function() {
  5068. var r = new Array(CORE_PROPS.length);
  5069. for(var i = 0; i < CORE_PROPS.length; ++i) {
  5070. var f = CORE_PROPS[i];
  5071. var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
  5072. r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
  5073. }
  5074. return r;
  5075. })();
  5076. function parse_core_props(data) {
  5077. var p = {};
  5078. data = utf8read(data);
  5079. for(var i = 0; i < CORE_PROPS.length; ++i) {
  5080. var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
  5081. if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
  5082. if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
  5083. }
  5084. return p;
  5085. }
  5086. function cp_doit(f, g, h, o, p) {
  5087. if(p[f] != null || g == null || g === "") return;
  5088. p[f] = g;
  5089. g = escapexml(g);
  5090. o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
  5091. }
  5092. function write_core_props(cp, _opts) {
  5093. var opts = _opts || {};
  5094. var o = [XML_HEADER, writextag('cp:coreProperties', null, {
  5095. //'xmlns': XMLNS.CORE_PROPS,
  5096. 'xmlns:cp': XMLNS.CORE_PROPS,
  5097. 'xmlns:dc': XMLNS.dc,
  5098. 'xmlns:dcterms': XMLNS.dcterms,
  5099. 'xmlns:dcmitype': XMLNS.dcmitype,
  5100. 'xmlns:xsi': XMLNS.xsi
  5101. })], p = {};
  5102. if(!cp && !opts.Props) return o.join("");
  5103. if(cp) {
  5104. 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);
  5105. 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);
  5106. }
  5107. for(var i = 0; i != CORE_PROPS.length; ++i) {
  5108. var f = CORE_PROPS[i];
  5109. var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
  5110. if(v === true) v = "1";
  5111. else if(v === false) v = "0";
  5112. else if(typeof v == "number") v = String(v);
  5113. if(v != null) cp_doit(f[0], v, null, o, p);
  5114. }
  5115. if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
  5116. return o.join("");
  5117. }
  5118. /* 15.2.12.3 Extended File Properties Part */
  5119. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  5120. var EXT_PROPS = [
  5121. ["Application", "Application", "string"],
  5122. ["AppVersion", "AppVersion", "string"],
  5123. ["Company", "Company", "string"],
  5124. ["DocSecurity", "DocSecurity", "string"],
  5125. ["Manager", "Manager", "string"],
  5126. ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  5127. ["SharedDoc", "SharedDoc", "bool"],
  5128. ["LinksUpToDate", "LinksUpToDate", "bool"],
  5129. ["ScaleCrop", "ScaleCrop", "bool"],
  5130. ["HeadingPairs", "HeadingPairs", "raw"],
  5131. ["TitlesOfParts", "TitlesOfParts", "raw"]
  5132. ];
  5133. var PseudoPropsPairs = [
  5134. "Worksheets", "SheetNames",
  5135. "NamedRanges", "DefinedNames",
  5136. "Chartsheets", "ChartNames"
  5137. ];
  5138. function load_props_pairs(HP, TOP, props, opts) {
  5139. var v = [];
  5140. if(typeof HP == "string") v = parseVector(HP, opts);
  5141. else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
  5142. var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
  5143. var idx = 0, len = 0;
  5144. if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
  5145. len = +(v[i+1].v);
  5146. switch(v[i].v) {
  5147. case "Worksheets":
  5148. case "工作表":
  5149. case "Листы":
  5150. case "أوراق العمل":
  5151. case "ワークシート":
  5152. case "גליונות עבודה":
  5153. case "Arbeitsblätter":
  5154. case "Çalışma Sayfaları":
  5155. case "Feuilles de calcul":
  5156. case "Fogli di lavoro":
  5157. case "Folhas de cálculo":
  5158. case "Planilhas":
  5159. case "Regneark":
  5160. case "Hojas de cálculo":
  5161. case "Werkbladen":
  5162. props.Worksheets = len;
  5163. props.SheetNames = parts.slice(idx, idx + len);
  5164. break;
  5165. case "Named Ranges":
  5166. case "Rangos con nombre":
  5167. case "名前付き一覧":
  5168. case "Benannte Bereiche":
  5169. case "Navngivne områder":
  5170. props.NamedRanges = len;
  5171. props.DefinedNames = parts.slice(idx, idx + len);
  5172. break;
  5173. case "Charts":
  5174. case "Diagramme":
  5175. props.Chartsheets = len;
  5176. props.ChartNames = parts.slice(idx, idx + len);
  5177. break;
  5178. }
  5179. idx += len;
  5180. }
  5181. }
  5182. function parse_ext_props(data, p, opts) {
  5183. var q = {}; if(!p) p = {};
  5184. data = utf8read(data);
  5185. EXT_PROPS.forEach(function(f) {
  5186. var xml = (data.match(matchtag(f[0]))||[])[1];
  5187. switch(f[2]) {
  5188. case "string": if(xml) p[f[1]] = unescapexml(xml); break;
  5189. case "bool": p[f[1]] = xml === "true"; break;
  5190. case "raw":
  5191. var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
  5192. if(cur && cur.length > 0) q[f[1]] = cur[1];
  5193. break;
  5194. }
  5195. });
  5196. if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);
  5197. return p;
  5198. }
  5199. function write_ext_props(cp) {
  5200. var o = [], W = writextag;
  5201. if(!cp) cp = {};
  5202. cp.Application = "SheetJS";
  5203. o[o.length] = (XML_HEADER);
  5204. o[o.length] = (writextag('Properties', null, {
  5205. 'xmlns': XMLNS.EXT_PROPS,
  5206. 'xmlns:vt': XMLNS.vt
  5207. }));
  5208. EXT_PROPS.forEach(function(f) {
  5209. if(cp[f[1]] === undefined) return;
  5210. var v;
  5211. switch(f[2]) {
  5212. case 'string': v = escapexml(String(cp[f[1]])); break;
  5213. case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
  5214. }
  5215. if(v !== undefined) o[o.length] = (W(f[0], v));
  5216. });
  5217. /* TODO: HeadingPairs, TitlesOfParts */
  5218. 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"})));
  5219. 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"})));
  5220. if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
  5221. return o.join("");
  5222. }
  5223. /* 15.2.12.2 Custom File Properties Part */
  5224. var custregex = /<[^>]+>[^<]*/g;
  5225. function parse_cust_props(data, opts) {
  5226. var p = {}, name = "";
  5227. var m = data.match(custregex);
  5228. if(m) for(var i = 0; i != m.length; ++i) {
  5229. var x = m[i], y = parsexmltag(x);
  5230. switch(y[0]) {
  5231. case '<?xml': break;
  5232. case '<Properties': break;
  5233. case '<property': name = unescapexml(y.name); break;
  5234. case '</property>': name = null; break;
  5235. default: if (x.indexOf('<vt:') === 0) {
  5236. var toks = x.split('>');
  5237. var type = toks[0].slice(4), text = toks[1];
  5238. /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
  5239. switch(type) {
  5240. case 'lpstr': case 'bstr': case 'lpwstr':
  5241. p[name] = unescapexml(text);
  5242. break;
  5243. case 'bool':
  5244. p[name] = parsexmlbool(text);
  5245. break;
  5246. case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
  5247. p[name] = parseInt(text, 10);
  5248. break;
  5249. case 'r4': case 'r8': case 'decimal':
  5250. p[name] = parseFloat(text);
  5251. break;
  5252. case 'filetime': case 'date':
  5253. p[name] = parseDate(text);
  5254. break;
  5255. case 'cy': case 'error':
  5256. p[name] = unescapexml(text);
  5257. break;
  5258. default:
  5259. if(type.slice(-1) == '/') break;
  5260. if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
  5261. }
  5262. } else if(x.slice(0,2) === "</") {/* empty */
  5263. } else if(opts.WTF) throw new Error(x);
  5264. }
  5265. }
  5266. return p;
  5267. }
  5268. function write_cust_props(cp) {
  5269. var o = [XML_HEADER, writextag('Properties', null, {
  5270. 'xmlns': XMLNS.CUST_PROPS,
  5271. 'xmlns:vt': XMLNS.vt
  5272. })];
  5273. if(!cp) return o.join("");
  5274. var pid = 1;
  5275. keys(cp).forEach(function custprop(k) { ++pid;
  5276. o[o.length] = (writextag('property', write_vt(cp[k], true), {
  5277. 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
  5278. 'pid': pid,
  5279. 'name': escapexml(k)
  5280. }));
  5281. });
  5282. if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
  5283. return o.join("");
  5284. }
  5285. /* Common Name -> XLML Name */
  5286. var XLMLDocPropsMap = {
  5287. Title: 'Title',
  5288. Subject: 'Subject',
  5289. Author: 'Author',
  5290. Keywords: 'Keywords',
  5291. Comments: 'Description',
  5292. LastAuthor: 'LastAuthor',
  5293. RevNumber: 'Revision',
  5294. Application: 'AppName',
  5295. /* TotalTime: 'TotalTime', */
  5296. LastPrinted: 'LastPrinted',
  5297. CreatedDate: 'Created',
  5298. ModifiedDate: 'LastSaved',
  5299. /* Pages */
  5300. /* Words */
  5301. /* Characters */
  5302. Category: 'Category',
  5303. /* PresentationFormat */
  5304. Manager: 'Manager',
  5305. Company: 'Company',
  5306. /* Guid */
  5307. /* HyperlinkBase */
  5308. /* Bytes */
  5309. /* Lines */
  5310. /* Paragraphs */
  5311. /* CharactersWithSpaces */
  5312. AppVersion: 'Version',
  5313. ContentStatus: 'ContentStatus', /* NOTE: missing from schema */
  5314. Identifier: 'Identifier', /* NOTE: missing from schema */
  5315. Language: 'Language' /* NOTE: missing from schema */
  5316. };
  5317. var evert_XLMLDPM;
  5318. function xlml_set_prop(Props, tag, val) {
  5319. if(!evert_XLMLDPM) evert_XLMLDPM = evert(XLMLDocPropsMap);
  5320. tag = evert_XLMLDPM[tag] || tag;
  5321. Props[tag] = val;
  5322. }
  5323. function xlml_write_docprops(Props, opts) {
  5324. var o = [];
  5325. keys(XLMLDocPropsMap).map(function(m) {
  5326. for(var i = 0; i < CORE_PROPS.length; ++i) if(CORE_PROPS[i][1] == m) return CORE_PROPS[i];
  5327. for(i = 0; i < EXT_PROPS.length; ++i) if(EXT_PROPS[i][1] == m) return EXT_PROPS[i];
  5328. throw m;
  5329. }).forEach(function(p) {
  5330. if(Props[p[1]] == null) return;
  5331. var m = opts && opts.Props && opts.Props[p[1]] != null ? opts.Props[p[1]] : Props[p[1]];
  5332. switch(p[2]) {
  5333. case 'date': m = new Date(m).toISOString().replace(/\.\d*Z/,"Z"); break;
  5334. }
  5335. if(typeof m == 'number') m = String(m);
  5336. else if(m === true || m === false) { m = m ? "1" : "0"; }
  5337. else if(m instanceof Date) m = new Date(m).toISOString().replace(/\.\d*Z/,"");
  5338. o.push(writetag(XLMLDocPropsMap[p[1]] || p[1], m));
  5339. });
  5340. return writextag('DocumentProperties', o.join(""), {xmlns:XLMLNS.o });
  5341. }
  5342. function xlml_write_custprops(Props, Custprops) {
  5343. var BLACKLIST = ["Worksheets","SheetNames"];
  5344. var T = 'CustomDocumentProperties';
  5345. var o = [];
  5346. if(Props) keys(Props).forEach(function(k) {
  5347. if(!Object.prototype.hasOwnProperty.call(Props, k)) return;
  5348. for(var i = 0; i < CORE_PROPS.length; ++i) if(k == CORE_PROPS[i][1]) return;
  5349. for(i = 0; i < EXT_PROPS.length; ++i) if(k == EXT_PROPS[i][1]) return;
  5350. for(i = 0; i < BLACKLIST.length; ++i) if(k == BLACKLIST[i]) return;
  5351. var m = Props[k];
  5352. var t = "string";
  5353. if(typeof m == 'number') { t = "float"; m = String(m); }
  5354. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  5355. else m = String(m);
  5356. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  5357. });
  5358. if(Custprops) keys(Custprops).forEach(function(k) {
  5359. if(!Object.prototype.hasOwnProperty.call(Custprops, k)) return;
  5360. if(Props && Object.prototype.hasOwnProperty.call(Props, k)) return;
  5361. var m = Custprops[k];
  5362. var t = "string";
  5363. if(typeof m == 'number') { t = "float"; m = String(m); }
  5364. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  5365. else if(m instanceof Date) { t = "dateTime.tz"; m = m.toISOString(); }
  5366. else m = String(m);
  5367. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  5368. });
  5369. return '<' + T + ' xmlns="' + XLMLNS.o + '">' + o.join("") + '</' + T + '>';
  5370. }
  5371. /* [MS-DTYP] 2.3.3 FILETIME */
  5372. /* [MS-OLEDS] 2.1.3 FILETIME (Packet Version) */
  5373. /* [MS-OLEPS] 2.8 FILETIME (Packet Version) */
  5374. function parse_FILETIME(blob) {
  5375. var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
  5376. return new Date(((dwHighDateTime/1e7*Math.pow(2,32) + dwLowDateTime/1e7) - 11644473600)*1000).toISOString().replace(/\.000/,"");
  5377. }
  5378. function write_FILETIME(time) {
  5379. var date = (typeof time == "string") ? new Date(Date.parse(time)) : time;
  5380. var t = date.getTime() / 1000 + 11644473600;
  5381. var l = t % Math.pow(2,32), h = (t - l) / Math.pow(2,32);
  5382. l *= 1e7; h *= 1e7;
  5383. var w = (l / Math.pow(2,32)) | 0;
  5384. if(w > 0) { l = l % Math.pow(2,32); h += w; }
  5385. var o = new_buf(8); o.write_shift(4, l); o.write_shift(4, h); return o;
  5386. }
  5387. /* [MS-OSHARED] 2.3.3.1.4 Lpstr */
  5388. function parse_lpstr(blob, type, pad) {
  5389. var start = blob.l;
  5390. var str = blob.read_shift(0, 'lpstr-cp');
  5391. if(pad) while((blob.l - start) & 3) ++blob.l;
  5392. return str;
  5393. }
  5394. /* [MS-OSHARED] 2.3.3.1.6 Lpwstr */
  5395. function parse_lpwstr(blob, type, pad) {
  5396. var str = blob.read_shift(0, 'lpwstr');
  5397. if(pad) blob.l += (4 - ((str.length+1) & 3)) & 3;
  5398. return str;
  5399. }
  5400. /* [MS-OSHARED] 2.3.3.1.11 VtString */
  5401. /* [MS-OSHARED] 2.3.3.1.12 VtUnalignedString */
  5402. function parse_VtStringBase(blob, stringType, pad) {
  5403. if(stringType === 0x1F /*VT_LPWSTR*/) return parse_lpwstr(blob);
  5404. return parse_lpstr(blob, stringType, pad);
  5405. }
  5406. function parse_VtString(blob, t, pad) { return parse_VtStringBase(blob, t, pad === false ? 0: 4); }
  5407. function parse_VtUnalignedString(blob, t) { if(!t) throw new Error("VtUnalignedString must have positive length"); return parse_VtStringBase(blob, t, 0); }
  5408. /* [MS-OSHARED] 2.3.3.1.7 VtVecLpwstrValue */
  5409. function parse_VtVecLpwstrValue(blob) {
  5410. var length = blob.read_shift(4);
  5411. var ret = [];
  5412. for(var i = 0; i != length; ++i) {
  5413. var start = blob.l;
  5414. ret[i] = blob.read_shift(0, 'lpwstr').replace(chr0,'');
  5415. if((blob.l - start) & 0x02) blob.l += 2;
  5416. }
  5417. return ret;
  5418. }
  5419. /* [MS-OSHARED] 2.3.3.1.9 VtVecUnalignedLpstrValue */
  5420. function parse_VtVecUnalignedLpstrValue(blob) {
  5421. var length = blob.read_shift(4);
  5422. var ret = [];
  5423. for(var i = 0; i != length; ++i) ret[i] = blob.read_shift(0, 'lpstr-cp').replace(chr0,'');
  5424. return ret;
  5425. }
  5426. /* [MS-OSHARED] 2.3.3.1.13 VtHeadingPair */
  5427. function parse_VtHeadingPair(blob) {
  5428. var start = blob.l;
  5429. var headingString = parse_TypedPropertyValue(blob, VT_USTR);
  5430. if(blob[blob.l] == 0x00 && blob[blob.l+1] == 0x00 && ((blob.l - start) & 0x02)) blob.l += 2;
  5431. var headerParts = parse_TypedPropertyValue(blob, VT_I4);
  5432. return [headingString, headerParts];
  5433. }
  5434. /* [MS-OSHARED] 2.3.3.1.14 VtVecHeadingPairValue */
  5435. function parse_VtVecHeadingPairValue(blob) {
  5436. var cElements = blob.read_shift(4);
  5437. var out = [];
  5438. for(var i = 0; i < cElements / 2; ++i) out.push(parse_VtHeadingPair(blob));
  5439. return out;
  5440. }
  5441. /* [MS-OLEPS] 2.18.1 Dictionary (uses 2.17, 2.16) */
  5442. function parse_dictionary(blob,CodePage) {
  5443. var cnt = blob.read_shift(4);
  5444. var dict = ({});
  5445. for(var j = 0; j != cnt; ++j) {
  5446. var pid = blob.read_shift(4);
  5447. var len = blob.read_shift(4);
  5448. dict[pid] = blob.read_shift(len, (CodePage === 0x4B0 ?'utf16le':'utf8')).replace(chr0,'').replace(chr1,'!');
  5449. if(CodePage === 0x4B0 && (len % 2)) blob.l += 2;
  5450. }
  5451. if(blob.l & 3) blob.l = (blob.l>>2+1)<<2;
  5452. return dict;
  5453. }
  5454. /* [MS-OLEPS] 2.9 BLOB */
  5455. function parse_BLOB(blob) {
  5456. var size = blob.read_shift(4);
  5457. var bytes = blob.slice(blob.l,blob.l+size);
  5458. blob.l += size;
  5459. if((size & 3) > 0) blob.l += (4 - (size & 3)) & 3;
  5460. return bytes;
  5461. }
  5462. /* [MS-OLEPS] 2.11 ClipboardData */
  5463. function parse_ClipboardData(blob) {
  5464. // TODO
  5465. var o = {};
  5466. o.Size = blob.read_shift(4);
  5467. //o.Format = blob.read_shift(4);
  5468. blob.l += o.Size + 3 - (o.Size - 1) % 4;
  5469. return o;
  5470. }
  5471. /* [MS-OLEPS] 2.15 TypedPropertyValue */
  5472. function parse_TypedPropertyValue(blob, type, _opts) {
  5473. var t = blob.read_shift(2), ret, opts = _opts||{};
  5474. blob.l += 2;
  5475. if(type !== VT_VARIANT)
  5476. if(t !== type && VT_CUSTOM.indexOf(type)===-1 && !((type & 0xFFFE) == 0x101E && (t & 0xFFFE) == 0x101E)) throw new Error('Expected type ' + type + ' saw ' + t);
  5477. switch(type === VT_VARIANT ? t : type) {
  5478. case 0x02 /*VT_I2*/: ret = blob.read_shift(2, 'i'); if(!opts.raw) blob.l += 2; return ret;
  5479. case 0x03 /*VT_I4*/: ret = blob.read_shift(4, 'i'); return ret;
  5480. case 0x0B /*VT_BOOL*/: return blob.read_shift(4) !== 0x0;
  5481. case 0x13 /*VT_UI4*/: ret = blob.read_shift(4); return ret;
  5482. case 0x1E /*VT_LPSTR*/: return parse_lpstr(blob, t, 4).replace(chr0,'');
  5483. case 0x1F /*VT_LPWSTR*/: return parse_lpwstr(blob);
  5484. case 0x40 /*VT_FILETIME*/: return parse_FILETIME(blob);
  5485. case 0x41 /*VT_BLOB*/: return parse_BLOB(blob);
  5486. case 0x47 /*VT_CF*/: return parse_ClipboardData(blob);
  5487. case 0x50 /*VT_STRING*/: return parse_VtString(blob, t, !opts.raw).replace(chr0,'');
  5488. case 0x51 /*VT_USTR*/: return parse_VtUnalignedString(blob, t/*, 4*/).replace(chr0,'');
  5489. case 0x100C /*VT_VECTOR|VT_VARIANT*/: return parse_VtVecHeadingPairValue(blob);
  5490. case 0x101E /*VT_VECTOR|VT_LPSTR*/:
  5491. case 0x101F /*VT_VECTOR|VT_LPWSTR*/:
  5492. return t == 0x101F ? parse_VtVecLpwstrValue(blob) : parse_VtVecUnalignedLpstrValue(blob);
  5493. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + t);
  5494. }
  5495. }
  5496. function write_TypedPropertyValue(type, value) {
  5497. var o = new_buf(4), p = new_buf(4);
  5498. o.write_shift(4, type == 0x50 ? 0x1F : type);
  5499. switch(type) {
  5500. case 0x03 /*VT_I4*/: p.write_shift(-4, value); break;
  5501. case 0x05 /*VT_I4*/: p = new_buf(8); p.write_shift(8, value, 'f'); break;
  5502. case 0x0B /*VT_BOOL*/: p.write_shift(4, value ? 0x01 : 0x00); break;
  5503. case 0x40 /*VT_FILETIME*/: p = write_FILETIME(value); break;
  5504. case 0x1F /*VT_LPWSTR*/:
  5505. case 0x50 /*VT_STRING*/:
  5506. p = new_buf(4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  5507. p.write_shift(4, value.length + 1);
  5508. p.write_shift(0, value, "dbcs");
  5509. while(p.l != p.length) p.write_shift(1, 0);
  5510. break;
  5511. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + value);
  5512. }
  5513. return bconcat([o, p]);
  5514. }
  5515. /* [MS-OLEPS] 2.20 PropertySet */
  5516. function parse_PropertySet(blob, PIDSI) {
  5517. var start_addr = blob.l;
  5518. var size = blob.read_shift(4);
  5519. var NumProps = blob.read_shift(4);
  5520. var Props = [], i = 0;
  5521. var CodePage = 0;
  5522. var Dictionary = -1, DictObj = ({});
  5523. for(i = 0; i != NumProps; ++i) {
  5524. var PropID = blob.read_shift(4);
  5525. var Offset = blob.read_shift(4);
  5526. Props[i] = [PropID, Offset + start_addr];
  5527. }
  5528. Props.sort(function(x,y) { return x[1] - y[1]; });
  5529. var PropH = {};
  5530. for(i = 0; i != NumProps; ++i) {
  5531. if(blob.l !== Props[i][1]) {
  5532. var fail = true;
  5533. if(i>0 && PIDSI) switch(PIDSI[Props[i-1][0]].t) {
  5534. case 0x02 /*VT_I2*/: if(blob.l+2 === Props[i][1]) { blob.l+=2; fail = false; } break;
  5535. case 0x50 /*VT_STRING*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  5536. case 0x100C /*VT_VECTOR|VT_VARIANT*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  5537. }
  5538. if((!PIDSI||i==0) && blob.l <= Props[i][1]) { fail=false; blob.l = Props[i][1]; }
  5539. if(fail) throw new Error("Read Error: Expected address " + Props[i][1] + ' at ' + blob.l + ' :' + i);
  5540. }
  5541. if(PIDSI) {
  5542. var piddsi = PIDSI[Props[i][0]];
  5543. PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, {raw:true});
  5544. if(piddsi.p === 'version') PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 0xFFFF)).slice(-4);
  5545. if(piddsi.n == "CodePage") switch(PropH[piddsi.n]) {
  5546. case 0: PropH[piddsi.n] = 1252;
  5547. /* falls through */
  5548. case 874:
  5549. case 932:
  5550. case 936:
  5551. case 949:
  5552. case 950:
  5553. case 1250:
  5554. case 1251:
  5555. case 1253:
  5556. case 1254:
  5557. case 1255:
  5558. case 1256:
  5559. case 1257:
  5560. case 1258:
  5561. case 10000:
  5562. case 1200:
  5563. case 1201:
  5564. case 1252:
  5565. case 65000: case -536:
  5566. case 65001: case -535:
  5567. set_cp(CodePage = (PropH[piddsi.n]>>>0) & 0xFFFF); break;
  5568. default: throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
  5569. }
  5570. } else {
  5571. if(Props[i][0] === 0x1) {
  5572. CodePage = PropH.CodePage = (parse_TypedPropertyValue(blob, VT_I2));
  5573. set_cp(CodePage);
  5574. if(Dictionary !== -1) {
  5575. var oldpos = blob.l;
  5576. blob.l = Props[Dictionary][1];
  5577. DictObj = parse_dictionary(blob,CodePage);
  5578. blob.l = oldpos;
  5579. }
  5580. } else if(Props[i][0] === 0) {
  5581. if(CodePage === 0) { Dictionary = i; blob.l = Props[i+1][1]; continue; }
  5582. DictObj = parse_dictionary(blob,CodePage);
  5583. } else {
  5584. var name = DictObj[Props[i][0]];
  5585. var val;
  5586. /* [MS-OSHARED] 2.3.3.2.3.1.2 + PROPVARIANT */
  5587. switch(blob[blob.l]) {
  5588. case 0x41 /*VT_BLOB*/: blob.l += 4; val = parse_BLOB(blob); break;
  5589. case 0x1E /*VT_LPSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  5590. case 0x1F /*VT_LPWSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  5591. case 0x03 /*VT_I4*/: blob.l += 4; val = blob.read_shift(4, 'i'); break;
  5592. case 0x13 /*VT_UI4*/: blob.l += 4; val = blob.read_shift(4); break;
  5593. case 0x05 /*VT_R8*/: blob.l += 4; val = blob.read_shift(8, 'f'); break;
  5594. case 0x0B /*VT_BOOL*/: blob.l += 4; val = parsebool(blob, 4); break;
  5595. case 0x40 /*VT_FILETIME*/: blob.l += 4; val = parseDate(parse_FILETIME(blob)); break;
  5596. default: throw new Error("unparsed value: " + blob[blob.l]);
  5597. }
  5598. PropH[name] = val;
  5599. }
  5600. }
  5601. }
  5602. blob.l = start_addr + size; /* step ahead to skip padding */
  5603. return PropH;
  5604. }
  5605. var XLSPSSkip = [ "CodePage", "Thumbnail", "_PID_LINKBASE", "_PID_HLINKS", "SystemIdentifier", "FMTID" ]; //.concat(PseudoPropsPairs);
  5606. function guess_property_type(val) {
  5607. switch(typeof val) {
  5608. case "boolean": return 0x0B;
  5609. case "number": return ((val|0)==val) ? 0x03 : 0x05;
  5610. case "string": return 0x1F;
  5611. case "object": if(val instanceof Date) return 0x40; break;
  5612. }
  5613. return -1;
  5614. }
  5615. function write_PropertySet(entries, RE, PIDSI) {
  5616. var hdr = new_buf(8), piao = [], prop = [];
  5617. var sz = 8, i = 0;
  5618. var pr = new_buf(8), pio = new_buf(8);
  5619. pr.write_shift(4, 0x0002);
  5620. pr.write_shift(4, 0x04B0);
  5621. pio.write_shift(4, 0x0001);
  5622. prop.push(pr); piao.push(pio);
  5623. sz += 8 + pr.length;
  5624. if(!RE) {
  5625. pio = new_buf(8);
  5626. pio.write_shift(4, 0);
  5627. piao.unshift(pio);
  5628. var bufs = [new_buf(4)];
  5629. bufs[0].write_shift(4, entries.length);
  5630. for(i = 0; i < entries.length; ++i) {
  5631. var value = entries[i][0];
  5632. pr = new_buf(4 + 4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  5633. pr.write_shift(4, i+2);
  5634. pr.write_shift(4, value.length + 1);
  5635. pr.write_shift(0, value, "dbcs");
  5636. while(pr.l != pr.length) pr.write_shift(1, 0);
  5637. bufs.push(pr);
  5638. }
  5639. pr = bconcat(bufs);
  5640. prop.unshift(pr);
  5641. sz += 8 + pr.length;
  5642. }
  5643. for(i = 0; i < entries.length; ++i) {
  5644. if(RE && !RE[entries[i][0]]) continue;
  5645. if(XLSPSSkip.indexOf(entries[i][0]) > -1 || PseudoPropsPairs.indexOf(entries[i][0]) > -1) continue;
  5646. if(entries[i][1] == null) continue;
  5647. var val = entries[i][1], idx = 0;
  5648. if(RE) {
  5649. idx = +RE[entries[i][0]];
  5650. var pinfo = (PIDSI)[idx];
  5651. if(pinfo.p == "version" && typeof val == "string") {
  5652. var arr = val.split(".");
  5653. val = ((+arr[0])<<16) + ((+arr[1])||0);
  5654. }
  5655. pr = write_TypedPropertyValue(pinfo.t, val);
  5656. } else {
  5657. var T = guess_property_type(val);
  5658. if(T == -1) { T = 0x1F; val = String(val); }
  5659. pr = write_TypedPropertyValue(T, val);
  5660. }
  5661. prop.push(pr);
  5662. pio = new_buf(8);
  5663. pio.write_shift(4, !RE ? 2+i : idx);
  5664. piao.push(pio);
  5665. sz += 8 + pr.length;
  5666. }
  5667. var w = 8 * (prop.length + 1);
  5668. for(i = 0; i < prop.length; ++i) { piao[i].write_shift(4, w); w += prop[i].length; }
  5669. hdr.write_shift(4, sz);
  5670. hdr.write_shift(4, prop.length);
  5671. return bconcat([hdr].concat(piao).concat(prop));
  5672. }
  5673. /* [MS-OLEPS] 2.21 PropertySetStream */
  5674. function parse_PropertySetStream(file, PIDSI, clsid) {
  5675. var blob = file.content;
  5676. if(!blob) return ({});
  5677. prep_blob(blob, 0);
  5678. var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
  5679. blob.chk('feff', 'Byte Order: ');
  5680. /*var vers = */blob.read_shift(2); // TODO: check version
  5681. var SystemIdentifier = blob.read_shift(4);
  5682. var CLSID = blob.read_shift(16);
  5683. if(CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
  5684. NumSets = blob.read_shift(4);
  5685. if(NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
  5686. FMTID0 = blob.read_shift(16); Offset0 = blob.read_shift(4);
  5687. if(NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
  5688. else if(NumSets === 2) { FMTID1 = blob.read_shift(16); Offset1 = blob.read_shift(4); }
  5689. var PSet0 = parse_PropertySet(blob, PIDSI);
  5690. var rval = ({ SystemIdentifier: SystemIdentifier });
  5691. for(var y in PSet0) rval[y] = PSet0[y];
  5692. //rval.blob = blob;
  5693. rval.FMTID = FMTID0;
  5694. //rval.PSet0 = PSet0;
  5695. if(NumSets === 1) return rval;
  5696. if(Offset1 - blob.l == 2) blob.l += 2;
  5697. if(blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
  5698. var PSet1;
  5699. try { PSet1 = parse_PropertySet(blob, null); } catch(e) {/* empty */}
  5700. for(y in PSet1) rval[y] = PSet1[y];
  5701. rval.FMTID = [FMTID0, FMTID1]; // TODO: verify FMTID0/1
  5702. return rval;
  5703. }
  5704. function write_PropertySetStream(entries, clsid, RE, PIDSI, entries2, clsid2) {
  5705. var hdr = new_buf(entries2 ? 68 : 48);
  5706. var bufs = [hdr];
  5707. hdr.write_shift(2, 0xFFFE);
  5708. hdr.write_shift(2, 0x0000); /* TODO: type 1 props */
  5709. hdr.write_shift(4, 0x32363237);
  5710. hdr.write_shift(16, CFB.utils.consts.HEADER_CLSID, "hex");
  5711. hdr.write_shift(4, (entries2 ? 2 : 1));
  5712. hdr.write_shift(16, clsid, "hex");
  5713. hdr.write_shift(4, (entries2 ? 68 : 48));
  5714. var ps0 = write_PropertySet(entries, RE, PIDSI);
  5715. bufs.push(ps0);
  5716. if(entries2) {
  5717. var ps1 = write_PropertySet(entries2, null, null);
  5718. hdr.write_shift(16, clsid2, "hex");
  5719. hdr.write_shift(4, 68 + ps0.length);
  5720. bufs.push(ps1);
  5721. }
  5722. return bconcat(bufs);
  5723. }
  5724. function parsenoop2(blob, length) { blob.read_shift(length); return null; }
  5725. function writezeroes(n, o) { if(!o) o=new_buf(n); for(var j=0; j<n; ++j) o.write_shift(1, 0); return o; }
  5726. function parslurp(blob, length, cb) {
  5727. var arr = [], target = blob.l + length;
  5728. while(blob.l < target) arr.push(cb(blob, target - blob.l));
  5729. if(target !== blob.l) throw new Error("Slurp error");
  5730. return arr;
  5731. }
  5732. function parsebool(blob, length) { return blob.read_shift(length) === 0x1; }
  5733. function writebool(v, o) { if(!o) o=new_buf(2); o.write_shift(2, +!!v); return o; }
  5734. function parseuint16(blob) { return blob.read_shift(2, 'u'); }
  5735. function writeuint16(v, o) { if(!o) o=new_buf(2); o.write_shift(2, v); return o; }
  5736. function parseuint16a(blob, length) { return parslurp(blob,length,parseuint16);}
  5737. /* --- 2.5 Structures --- */
  5738. /* [MS-XLS] 2.5.10 Bes (boolean or error) */
  5739. function parse_Bes(blob) {
  5740. var v = blob.read_shift(1), t = blob.read_shift(1);
  5741. return t === 0x01 ? v : v === 0x01;
  5742. }
  5743. function write_Bes(v, t, o) {
  5744. if(!o) o = new_buf(2);
  5745. o.write_shift(1, ((t == 'e') ? +v : +!!v));
  5746. o.write_shift(1, ((t == 'e') ? 1 : 0));
  5747. return o;
  5748. }
  5749. /* [MS-XLS] 2.5.240 ShortXLUnicodeString */
  5750. function parse_ShortXLUnicodeString(blob, length, opts) {
  5751. var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
  5752. var encoding = 'sbcs-cont';
  5753. var cp = current_codepage;
  5754. if(opts && opts.biff >= 8) current_codepage = 1200;
  5755. if(!opts || opts.biff == 8 ) {
  5756. var fHighByte = blob.read_shift(1);
  5757. if(fHighByte) { encoding = 'dbcs-cont'; }
  5758. } else if(opts.biff == 12) {
  5759. encoding = 'wstr';
  5760. }
  5761. if(opts.biff >= 2 && opts.biff <= 5) encoding = 'cpstr';
  5762. var o = cch ? blob.read_shift(cch, encoding) : "";
  5763. current_codepage = cp;
  5764. return o;
  5765. }
  5766. /* 2.5.293 XLUnicodeRichExtendedString */
  5767. function parse_XLUnicodeRichExtendedString(blob) {
  5768. var cp = current_codepage;
  5769. current_codepage = 1200;
  5770. var cch = blob.read_shift(2), flags = blob.read_shift(1);
  5771. var /*fHighByte = flags & 0x1,*/ fExtSt = flags & 0x4, fRichSt = flags & 0x8;
  5772. var width = 1 + (flags & 0x1); // 0x0 -> utf8, 0x1 -> dbcs
  5773. var cRun = 0, cbExtRst;
  5774. var z = {};
  5775. if(fRichSt) cRun = blob.read_shift(2);
  5776. if(fExtSt) cbExtRst = blob.read_shift(4);
  5777. var encoding = width == 2 ? 'dbcs-cont' : 'sbcs-cont';
  5778. var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
  5779. if(fRichSt) blob.l += 4 * cRun; //TODO: parse this
  5780. if(fExtSt) blob.l += cbExtRst; //TODO: parse this
  5781. z.t = msg;
  5782. if(!fRichSt) { z.raw = "<t>" + z.t + "</t>"; z.r = z.t; }
  5783. current_codepage = cp;
  5784. return z;
  5785. }
  5786. function write_XLUnicodeRichExtendedString(xlstr) {
  5787. var str = (xlstr.t||""), nfmts = 1;
  5788. var hdr = new_buf(3 + (nfmts > 1 ? 2 : 0));
  5789. hdr.write_shift(2, str.length);
  5790. hdr.write_shift(1, (nfmts > 1 ? 0x08 : 0x00) | 0x01);
  5791. if(nfmts > 1) hdr.write_shift(2, nfmts);
  5792. var otext = new_buf(2 * str.length);
  5793. otext.write_shift(2 * str.length, str, 'utf16le');
  5794. var out = [hdr, otext];
  5795. return bconcat(out);
  5796. }
  5797. /* 2.5.296 XLUnicodeStringNoCch */
  5798. function parse_XLUnicodeStringNoCch(blob, cch, opts) {
  5799. var retval;
  5800. if(opts) {
  5801. if(opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, 'cpstr');
  5802. if(opts.biff >= 12) return blob.read_shift(cch, 'dbcs-cont');
  5803. }
  5804. var fHighByte = blob.read_shift(1);
  5805. if(fHighByte===0) { retval = blob.read_shift(cch, 'sbcs-cont'); }
  5806. else { retval = blob.read_shift(cch, 'dbcs-cont'); }
  5807. return retval;
  5808. }
  5809. /* 2.5.294 XLUnicodeString */
  5810. function parse_XLUnicodeString(blob, length, opts) {
  5811. var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  5812. if(cch === 0) { blob.l++; return ""; }
  5813. return parse_XLUnicodeStringNoCch(blob, cch, opts);
  5814. }
  5815. /* BIFF5 override */
  5816. function parse_XLUnicodeString2(blob, length, opts) {
  5817. if(opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
  5818. var cch = blob.read_shift(1);
  5819. if(cch === 0) { blob.l++; return ""; }
  5820. return blob.read_shift(cch, (opts.biff <= 4 || !blob.lens ) ? 'cpstr' : 'sbcs-cont');
  5821. }
  5822. /* TODO: BIFF5 and lower, codepage awareness */
  5823. function write_XLUnicodeString(str, opts, o) {
  5824. if(!o) o = new_buf(3 + 2 * str.length);
  5825. o.write_shift(2, str.length);
  5826. o.write_shift(1, 1);
  5827. o.write_shift(31, str, 'utf16le');
  5828. return o;
  5829. }
  5830. /* [MS-XLS] 2.5.61 ControlInfo */
  5831. function parse_ControlInfo(blob) {
  5832. var flags = blob.read_shift(1);
  5833. blob.l++;
  5834. var accel = blob.read_shift(2);
  5835. blob.l += 2;
  5836. return [flags, accel];
  5837. }
  5838. /* [MS-OSHARED] 2.3.7.6 URLMoniker TODO: flags */
  5839. function parse_URLMoniker(blob) {
  5840. var len = blob.read_shift(4), start = blob.l;
  5841. var extra = false;
  5842. if(len > 24) {
  5843. /* look ahead */
  5844. blob.l += len - 24;
  5845. if(blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
  5846. blob.l = start;
  5847. }
  5848. var url = blob.read_shift((extra?len-24:len)>>1, 'utf16le').replace(chr0,"");
  5849. if(extra) blob.l += 24;
  5850. return url;
  5851. }
  5852. /* [MS-OSHARED] 2.3.7.8 FileMoniker TODO: all fields */
  5853. function parse_FileMoniker(blob) {
  5854. var cAnti = blob.read_shift(2);
  5855. var preamble = ""; while(cAnti-- > 0) preamble += "../";
  5856. var ansiPath = blob.read_shift(0, 'lpstr-ansi');
  5857. blob.l += 2; //var endServer = blob.read_shift(2);
  5858. if(blob.read_shift(2) != 0xDEAD) throw new Error("Bad FileMoniker");
  5859. var sz = blob.read_shift(4);
  5860. if(sz === 0) return preamble + ansiPath.replace(/\\/g,"/");
  5861. var bytes = blob.read_shift(4);
  5862. if(blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
  5863. var unicodePath = blob.read_shift(bytes>>1, 'utf16le').replace(chr0,"");
  5864. return preamble + unicodePath;
  5865. }
  5866. /* [MS-OSHARED] 2.3.7.2 HyperlinkMoniker TODO: all the monikers */
  5867. function parse_HyperlinkMoniker(blob, length) {
  5868. var clsid = blob.read_shift(16); length -= 16;
  5869. switch(clsid) {
  5870. case "e0c9ea79f9bace118c8200aa004ba90b": return parse_URLMoniker(blob, length);
  5871. case "0303000000000000c000000000000046": return parse_FileMoniker(blob, length);
  5872. default: throw new Error("Unsupported Moniker " + clsid);
  5873. }
  5874. }
  5875. /* [MS-OSHARED] 2.3.7.9 HyperlinkString */
  5876. function parse_HyperlinkString(blob) {
  5877. var len = blob.read_shift(4);
  5878. var o = len > 0 ? blob.read_shift(len, 'utf16le').replace(chr0, "") : "";
  5879. return o;
  5880. }
  5881. function write_HyperlinkString(str, o) {
  5882. if(!o) o = new_buf(6 + str.length * 2);
  5883. o.write_shift(4, 1 + str.length);
  5884. for(var i = 0; i < str.length; ++i) o.write_shift(2, str.charCodeAt(i));
  5885. o.write_shift(2, 0);
  5886. return o;
  5887. }
  5888. /* [MS-OSHARED] 2.3.7.1 Hyperlink Object */
  5889. function parse_Hyperlink(blob, length) {
  5890. var end = blob.l + length;
  5891. var sVer = blob.read_shift(4);
  5892. if(sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
  5893. var flags = blob.read_shift(2);
  5894. blob.l += 2;
  5895. var displayName, targetFrameName, moniker, oleMoniker, Loc="", guid, fileTime;
  5896. if(flags & 0x0010) displayName = parse_HyperlinkString(blob, end - blob.l);
  5897. if(flags & 0x0080) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
  5898. if((flags & 0x0101) === 0x0101) moniker = parse_HyperlinkString(blob, end - blob.l);
  5899. if((flags & 0x0101) === 0x0001) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
  5900. if(flags & 0x0008) Loc = parse_HyperlinkString(blob, end - blob.l);
  5901. if(flags & 0x0020) guid = blob.read_shift(16);
  5902. if(flags & 0x0040) fileTime = parse_FILETIME(blob/*, 8*/);
  5903. blob.l = end;
  5904. var target = targetFrameName||moniker||oleMoniker||"";
  5905. if(target && Loc) target+="#"+Loc;
  5906. if(!target) target = "#" + Loc;
  5907. if((flags & 0x0002) && target.charAt(0) == "/" && target.charAt(1) != "/") target = "file://" + target;
  5908. var out = ({Target:target});
  5909. if(guid) out.guid = guid;
  5910. if(fileTime) out.time = fileTime;
  5911. if(displayName) out.Tooltip = displayName;
  5912. return out;
  5913. }
  5914. function write_Hyperlink(hl) {
  5915. var out = new_buf(512), i = 0;
  5916. var Target = hl.Target;
  5917. if(Target.slice(0,7) == "file://") Target = Target.slice(7);
  5918. var hashidx = Target.indexOf("#");
  5919. var F = hashidx > -1 ? 0x1f : 0x17;
  5920. switch(Target.charAt(0)) { case "#": F=0x1c; break; case ".": F&=~2; break; }
  5921. out.write_shift(4,2); out.write_shift(4, F);
  5922. var data = [8,6815827,6619237,4849780,83]; for(i = 0; i < data.length; ++i) out.write_shift(4, data[i]);
  5923. if(F == 0x1C) {
  5924. Target = Target.slice(1);
  5925. write_HyperlinkString(Target, out);
  5926. } else if(F & 0x02) {
  5927. data = "e0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  5928. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  5929. var Pretarget = hashidx > -1 ? Target.slice(0, hashidx) : Target;
  5930. out.write_shift(4, 2*(Pretarget.length + 1));
  5931. for(i = 0; i < Pretarget.length; ++i) out.write_shift(2, Pretarget.charCodeAt(i));
  5932. out.write_shift(2, 0);
  5933. if(F & 0x08) write_HyperlinkString(hashidx > -1 ? Target.slice(hashidx+1): "", out);
  5934. } else {
  5935. data = "03 03 00 00 00 00 00 00 c0 00 00 00 00 00 00 46".split(" ");
  5936. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  5937. var P = 0;
  5938. while(Target.slice(P*3,P*3+3)=="../"||Target.slice(P*3,P*3+3)=="..\\") ++P;
  5939. out.write_shift(2, P);
  5940. out.write_shift(4, Target.length - 3 * P + 1);
  5941. for(i = 0; i < Target.length - 3 * P; ++i) out.write_shift(1, Target.charCodeAt(i + 3 * P) & 0xFF);
  5942. out.write_shift(1, 0);
  5943. out.write_shift(2, 0xFFFF);
  5944. out.write_shift(2, 0xDEAD);
  5945. for(i = 0; i < 6; ++i) out.write_shift(4, 0);
  5946. }
  5947. return out.slice(0, out.l);
  5948. }
  5949. /* 2.5.178 LongRGBA */
  5950. 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]; }
  5951. /* 2.5.177 LongRGB */
  5952. function parse_LongRGB(blob, length) { var x = parse_LongRGBA(blob, length); x[3] = 0; return x; }
  5953. /* [MS-XLS] 2.5.19 */
  5954. function parse_XLSCell(blob) {
  5955. var rw = blob.read_shift(2); // 0-indexed
  5956. var col = blob.read_shift(2);
  5957. var ixfe = blob.read_shift(2);
  5958. return ({r:rw, c:col, ixfe:ixfe});
  5959. }
  5960. function write_XLSCell(R, C, ixfe, o) {
  5961. if(!o) o = new_buf(6);
  5962. o.write_shift(2, R);
  5963. o.write_shift(2, C);
  5964. o.write_shift(2, ixfe||0);
  5965. return o;
  5966. }
  5967. /* [MS-XLS] 2.5.134 */
  5968. function parse_frtHeader(blob) {
  5969. var rt = blob.read_shift(2);
  5970. var flags = blob.read_shift(2); // TODO: parse these flags
  5971. blob.l += 8;
  5972. return {type: rt, flags: flags};
  5973. }
  5974. function parse_OptXLUnicodeString(blob, length, opts) { return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts); }
  5975. /* [MS-XLS] 2.5.344 */
  5976. function parse_XTI(blob, length, opts) {
  5977. var w = opts.biff > 8 ? 4 : 2;
  5978. var iSupBook = blob.read_shift(w), itabFirst = blob.read_shift(w,'i'), itabLast = blob.read_shift(w,'i');
  5979. return [iSupBook, itabFirst, itabLast];
  5980. }
  5981. /* [MS-XLS] 2.5.218 */
  5982. function parse_RkRec(blob) {
  5983. var ixfe = blob.read_shift(2);
  5984. var RK = parse_RkNumber(blob);
  5985. return [ixfe, RK];
  5986. }
  5987. /* [MS-XLS] 2.5.1 */
  5988. function parse_AddinUdf(blob, length, opts) {
  5989. blob.l += 4; length -= 4;
  5990. var l = blob.l + length;
  5991. var udfName = parse_ShortXLUnicodeString(blob, length, opts);
  5992. var cb = blob.read_shift(2);
  5993. l -= blob.l;
  5994. if(cb !== l) throw new Error("Malformed AddinUdf: padding = " + l + " != " + cb);
  5995. blob.l += cb;
  5996. return udfName;
  5997. }
  5998. /* [MS-XLS] 2.5.209 TODO: Check sizes */
  5999. function parse_Ref8U(blob) {
  6000. var rwFirst = blob.read_shift(2);
  6001. var rwLast = blob.read_shift(2);
  6002. var colFirst = blob.read_shift(2);
  6003. var colLast = blob.read_shift(2);
  6004. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  6005. }
  6006. function write_Ref8U(r, o) {
  6007. if(!o) o = new_buf(8);
  6008. o.write_shift(2, r.s.r);
  6009. o.write_shift(2, r.e.r);
  6010. o.write_shift(2, r.s.c);
  6011. o.write_shift(2, r.e.c);
  6012. return o;
  6013. }
  6014. /* [MS-XLS] 2.5.211 */
  6015. function parse_RefU(blob) {
  6016. var rwFirst = blob.read_shift(2);
  6017. var rwLast = blob.read_shift(2);
  6018. var colFirst = blob.read_shift(1);
  6019. var colLast = blob.read_shift(1);
  6020. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  6021. }
  6022. /* [MS-XLS] 2.5.207 */
  6023. var parse_Ref = parse_RefU;
  6024. /* [MS-XLS] 2.5.143 */
  6025. function parse_FtCmo(blob) {
  6026. blob.l += 4;
  6027. var ot = blob.read_shift(2);
  6028. var id = blob.read_shift(2);
  6029. var flags = blob.read_shift(2);
  6030. blob.l+=12;
  6031. return [id, ot, flags];
  6032. }
  6033. /* [MS-XLS] 2.5.149 */
  6034. function parse_FtNts(blob) {
  6035. var out = {};
  6036. blob.l += 4;
  6037. blob.l += 16; // GUID TODO
  6038. out.fSharedNote = blob.read_shift(2);
  6039. blob.l += 4;
  6040. return out;
  6041. }
  6042. /* [MS-XLS] 2.5.142 */
  6043. function parse_FtCf(blob) {
  6044. var out = {};
  6045. blob.l += 4;
  6046. blob.cf = blob.read_shift(2);
  6047. return out;
  6048. }
  6049. /* [MS-XLS] 2.5.140 - 2.5.154 and friends */
  6050. function parse_FtSkip(blob) { blob.l += 2; blob.l += blob.read_shift(2); }
  6051. var FtTab = {
  6052. 0x00: parse_FtSkip, /* FtEnd */
  6053. 0x04: parse_FtSkip, /* FtMacro */
  6054. 0x05: parse_FtSkip, /* FtButton */
  6055. 0x06: parse_FtSkip, /* FtGmo */
  6056. 0x07: parse_FtCf, /* FtCf */
  6057. 0x08: parse_FtSkip, /* FtPioGrbit */
  6058. 0x09: parse_FtSkip, /* FtPictFmla */
  6059. 0x0A: parse_FtSkip, /* FtCbls */
  6060. 0x0B: parse_FtSkip, /* FtRbo */
  6061. 0x0C: parse_FtSkip, /* FtSbs */
  6062. 0x0D: parse_FtNts, /* FtNts */
  6063. 0x0E: parse_FtSkip, /* FtSbsFmla */
  6064. 0x0F: parse_FtSkip, /* FtGboData */
  6065. 0x10: parse_FtSkip, /* FtEdoData */
  6066. 0x11: parse_FtSkip, /* FtRboData */
  6067. 0x12: parse_FtSkip, /* FtCblsData */
  6068. 0x13: parse_FtSkip, /* FtLbsData */
  6069. 0x14: parse_FtSkip, /* FtCblsFmla */
  6070. 0x15: parse_FtCmo
  6071. };
  6072. function parse_FtArray(blob, length) {
  6073. var tgt = blob.l + length;
  6074. var fts = [];
  6075. while(blob.l < tgt) {
  6076. var ft = blob.read_shift(2);
  6077. blob.l-=2;
  6078. try {
  6079. fts.push(FtTab[ft](blob, tgt - blob.l));
  6080. } catch(e) { blob.l = tgt; return fts; }
  6081. }
  6082. if(blob.l != tgt) blob.l = tgt; //throw new Error("bad Object Ft-sequence");
  6083. return fts;
  6084. }
  6085. /* --- 2.4 Records --- */
  6086. /* [MS-XLS] 2.4.21 */
  6087. function parse_BOF(blob, length) {
  6088. var o = {BIFFVer:0, dt:0};
  6089. o.BIFFVer = blob.read_shift(2); length -= 2;
  6090. if(length >= 2) { o.dt = blob.read_shift(2); blob.l -= 2; }
  6091. switch(o.BIFFVer) {
  6092. case 0x0600: /* BIFF8 */
  6093. case 0x0500: /* BIFF5 */
  6094. case 0x0400: /* BIFF4 */
  6095. case 0x0300: /* BIFF3 */
  6096. case 0x0200: /* BIFF2 */
  6097. case 0x0002: case 0x0007: /* BIFF2 */
  6098. break;
  6099. default: if(length > 6) throw new Error("Unexpected BIFF Ver " + o.BIFFVer);
  6100. }
  6101. blob.read_shift(length);
  6102. return o;
  6103. }
  6104. function write_BOF(wb, t, o) {
  6105. var h = 0x0600, w = 16;
  6106. switch(o.bookType) {
  6107. case 'biff8': break;
  6108. case 'biff5': h = 0x0500; w = 8; break;
  6109. case 'biff4': h = 0x0004; w = 6; break;
  6110. case 'biff3': h = 0x0003; w = 6; break;
  6111. case 'biff2': h = 0x0002; w = 4; break;
  6112. case 'xla': break;
  6113. default: throw new Error("unsupported BIFF version");
  6114. }
  6115. var out = new_buf(w);
  6116. out.write_shift(2, h);
  6117. out.write_shift(2, t);
  6118. if(w > 4) out.write_shift(2, 0x7262);
  6119. if(w > 6) out.write_shift(2, 0x07CD);
  6120. if(w > 8) {
  6121. out.write_shift(2, 0xC009);
  6122. out.write_shift(2, 0x0001);
  6123. out.write_shift(2, 0x0706);
  6124. out.write_shift(2, 0x0000);
  6125. }
  6126. return out;
  6127. }
  6128. /* [MS-XLS] 2.4.146 */
  6129. function parse_InterfaceHdr(blob, length) {
  6130. if(length === 0) return 0x04b0;
  6131. if((blob.read_shift(2))!==0x04b0){/* empty */}
  6132. return 0x04b0;
  6133. }
  6134. /* [MS-XLS] 2.4.349 */
  6135. function parse_WriteAccess(blob, length, opts) {
  6136. if(opts.enc) { blob.l += length; return ""; }
  6137. var l = blob.l;
  6138. // TODO: make sure XLUnicodeString doesnt overrun
  6139. var UserName = parse_XLUnicodeString2(blob, 0, opts);
  6140. blob.read_shift(length + l - blob.l);
  6141. return UserName;
  6142. }
  6143. function write_WriteAccess(s, opts) {
  6144. var b8 = !opts || opts.biff == 8;
  6145. var o = new_buf(b8 ? 112 : 54);
  6146. o.write_shift(opts.biff == 8 ? 2 : 1, 7);
  6147. if(b8) o.write_shift(1, 0);
  6148. o.write_shift(4, 0x33336853);
  6149. o.write_shift(4, (0x00534A74 | (b8 ? 0 : 0x20000000)));
  6150. while(o.l < o.length) o.write_shift(1, (b8 ? 0 : 32));
  6151. return o;
  6152. }
  6153. /* [MS-XLS] 2.4.351 */
  6154. function parse_WsBool(blob, length, opts) {
  6155. var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
  6156. return { fDialog: flags & 0x10, fBelow: flags & 0x40, fRight: flags & 0x80 };
  6157. }
  6158. /* [MS-XLS] 2.4.28 */
  6159. function parse_BoundSheet8(blob, length, opts) {
  6160. var pos = blob.read_shift(4);
  6161. var hidden = blob.read_shift(1) & 0x03;
  6162. var dt = blob.read_shift(1);
  6163. switch(dt) {
  6164. case 0: dt = 'Worksheet'; break;
  6165. case 1: dt = 'Macrosheet'; break;
  6166. case 2: dt = 'Chartsheet'; break;
  6167. case 6: dt = 'VBAModule'; break;
  6168. }
  6169. var name = parse_ShortXLUnicodeString(blob, 0, opts);
  6170. if(name.length === 0) name = "Sheet1";
  6171. return { pos:pos, hs:hidden, dt:dt, name:name };
  6172. }
  6173. function write_BoundSheet8(data, opts) {
  6174. var w = (!opts || opts.biff >= 8 ? 2 : 1);
  6175. var o = new_buf(8 + w * data.name.length);
  6176. o.write_shift(4, data.pos);
  6177. o.write_shift(1, data.hs || 0);
  6178. o.write_shift(1, data.dt);
  6179. o.write_shift(1, data.name.length);
  6180. if(opts.biff >= 8) o.write_shift(1, 1);
  6181. o.write_shift(w * data.name.length, data.name, opts.biff < 8 ? 'sbcs' : 'utf16le');
  6182. var out = o.slice(0, o.l);
  6183. out.l = o.l; return out;
  6184. }
  6185. /* [MS-XLS] 2.4.265 TODO */
  6186. function parse_SST(blob, length) {
  6187. var end = blob.l + length;
  6188. var cnt = blob.read_shift(4);
  6189. var ucnt = blob.read_shift(4);
  6190. var strs = ([]);
  6191. for(var i = 0; i != ucnt && blob.l < end; ++i) {
  6192. strs.push(parse_XLUnicodeRichExtendedString(blob));
  6193. }
  6194. strs.Count = cnt; strs.Unique = ucnt;
  6195. return strs;
  6196. }
  6197. function write_SST(sst, opts) {
  6198. var header = new_buf(8);
  6199. header.write_shift(4, sst.Count);
  6200. header.write_shift(4, sst.Unique);
  6201. var strs = [];
  6202. for(var j = 0; j < sst.length; ++j) strs[j] = write_XLUnicodeRichExtendedString(sst[j], opts);
  6203. var o = bconcat([header].concat(strs));
  6204. o.parts = [header.length].concat(strs.map(function(str) { return str.length; }));
  6205. return o;
  6206. }
  6207. /* [MS-XLS] 2.4.107 */
  6208. function parse_ExtSST(blob, length) {
  6209. var extsst = {};
  6210. extsst.dsst = blob.read_shift(2);
  6211. blob.l += length-2;
  6212. return extsst;
  6213. }
  6214. /* [MS-XLS] 2.4.221 TODO: check BIFF2-4 */
  6215. function parse_Row(blob) {
  6216. var z = ({});
  6217. z.r = blob.read_shift(2);
  6218. z.c = blob.read_shift(2);
  6219. z.cnt = blob.read_shift(2) - z.c;
  6220. var miyRw = blob.read_shift(2);
  6221. blob.l += 4; // reserved(2), unused(2)
  6222. var flags = blob.read_shift(1); // various flags
  6223. blob.l += 3; // reserved(8), ixfe(12), flags(4)
  6224. if(flags & 0x07) z.level = flags & 0x07;
  6225. // collapsed: flags & 0x10
  6226. if(flags & 0x20) z.hidden = true;
  6227. if(flags & 0x40) z.hpt = miyRw / 20;
  6228. return z;
  6229. }
  6230. /* [MS-XLS] 2.4.125 */
  6231. function parse_ForceFullCalculation(blob) {
  6232. var header = parse_frtHeader(blob);
  6233. if(header.type != 0x08A3) throw new Error("Invalid Future Record " + header.type);
  6234. var fullcalc = blob.read_shift(4);
  6235. return fullcalc !== 0x0;
  6236. }
  6237. /* [MS-XLS] 2.4.215 rt */
  6238. function parse_RecalcId(blob) {
  6239. blob.read_shift(2);
  6240. return blob.read_shift(4);
  6241. }
  6242. /* [MS-XLS] 2.4.87 */
  6243. function parse_DefaultRowHeight(blob, length, opts) {
  6244. var f = 0;
  6245. if(!(opts && opts.biff == 2)) {
  6246. f = blob.read_shift(2);
  6247. }
  6248. var miyRw = blob.read_shift(2);
  6249. if((opts && opts.biff == 2)) {
  6250. f = 1 - (miyRw >> 15); miyRw &= 0x7fff;
  6251. }
  6252. var fl = {Unsynced:f&1,DyZero:(f&2)>>1,ExAsc:(f&4)>>2,ExDsc:(f&8)>>3};
  6253. return [fl, miyRw];
  6254. }
  6255. /* [MS-XLS] 2.4.345 TODO */
  6256. function parse_Window1(blob) {
  6257. var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
  6258. var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
  6259. var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
  6260. return { Pos: [xWn, yWn], Dim: [dxWn, dyWn], Flags: flags, CurTab: iTabCur,
  6261. FirstTab: iTabFirst, Selected: ctabSel, TabRatio: wTabRatio };
  6262. }
  6263. function write_Window1() {
  6264. var o = new_buf(18);
  6265. o.write_shift(2, 0);
  6266. o.write_shift(2, 0);
  6267. o.write_shift(2, 0x7260);
  6268. o.write_shift(2, 0x44c0);
  6269. o.write_shift(2, 0x38);
  6270. o.write_shift(2, 0);
  6271. o.write_shift(2, 0);
  6272. o.write_shift(2, 1);
  6273. o.write_shift(2, 0x01f4);
  6274. return o;
  6275. }
  6276. /* [MS-XLS] 2.4.346 TODO */
  6277. function parse_Window2(blob, length, opts) {
  6278. if(opts && opts.biff >= 2 && opts.biff < 5) return {};
  6279. var f = blob.read_shift(2);
  6280. return { RTL: f & 0x40 };
  6281. }
  6282. function write_Window2(view) {
  6283. var o = new_buf(18), f = 0x6b6;
  6284. if(view && view.RTL) f |= 0x40;
  6285. o.write_shift(2, f);
  6286. o.write_shift(4, 0);
  6287. o.write_shift(4, 64);
  6288. o.write_shift(4, 0);
  6289. o.write_shift(4, 0);
  6290. return o;
  6291. }
  6292. /* [MS-XLS] 2.4.189 TODO */
  6293. function parse_Pane(/*blob, length, opts*/) {
  6294. }
  6295. /* [MS-XLS] 2.4.122 TODO */
  6296. function parse_Font(blob, length, opts) {
  6297. var o = {
  6298. dyHeight: blob.read_shift(2),
  6299. fl: blob.read_shift(2)
  6300. };
  6301. switch((opts && opts.biff) || 8) {
  6302. case 2: break;
  6303. case 3: case 4: blob.l += 2; break;
  6304. default: blob.l += 10; break;
  6305. }
  6306. o.name = parse_ShortXLUnicodeString(blob, 0, opts);
  6307. return o;
  6308. }
  6309. function write_Font(data, opts) {
  6310. var name = data.name || "Arial";
  6311. var b5 = (opts && (opts.biff == 5)), w = (b5 ? (15 + name.length) : (16 + 2 * name.length));
  6312. var o = new_buf(w);
  6313. o.write_shift(2, (data.sz || 12) * 20);
  6314. o.write_shift(4, 0);
  6315. o.write_shift(2, 400);
  6316. o.write_shift(4, 0);
  6317. o.write_shift(2, 0);
  6318. o.write_shift(1, name.length);
  6319. if(!b5) o.write_shift(1, 1);
  6320. o.write_shift((b5 ? 1 : 2) * name.length, name, (b5 ? "sbcs" : "utf16le"));
  6321. return o;
  6322. }
  6323. /* [MS-XLS] 2.4.149 */
  6324. function parse_LabelSst(blob) {
  6325. var cell = parse_XLSCell(blob);
  6326. cell.isst = blob.read_shift(4);
  6327. return cell;
  6328. }
  6329. function write_LabelSst(R, C, v, os ) {
  6330. var o = new_buf(10);
  6331. write_XLSCell(R, C, os, o);
  6332. o.write_shift(4, v);
  6333. return o;
  6334. }
  6335. /* [MS-XLS] 2.4.148 */
  6336. function parse_Label(blob, length, opts) {
  6337. if(opts.biffguess && opts.biff == 2) opts.biff = 5;
  6338. var target = blob.l + length;
  6339. var cell = parse_XLSCell(blob, 6);
  6340. if(opts.biff == 2) blob.l++;
  6341. var str = parse_XLUnicodeString(blob, target - blob.l, opts);
  6342. cell.val = str;
  6343. return cell;
  6344. }
  6345. function write_Label(R, C, v, os, opts) {
  6346. var b8 = !opts || opts.biff == 8;
  6347. var o = new_buf(6 + 2 + (+b8) + (1 + b8) * v.length);
  6348. write_XLSCell(R, C, os, o);
  6349. o.write_shift(2, v.length);
  6350. if(b8) o.write_shift(1, 1);
  6351. o.write_shift((1 + b8) * v.length, v, b8 ? 'utf16le' : 'sbcs');
  6352. return o;
  6353. }
  6354. /* [MS-XLS] 2.4.126 Number Formats */
  6355. function parse_Format(blob, length, opts) {
  6356. var numFmtId = blob.read_shift(2);
  6357. var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
  6358. return [numFmtId, fmtstr];
  6359. }
  6360. function write_Format(i, f, opts, o) {
  6361. var b5 = (opts && (opts.biff == 5));
  6362. if(!o) o = new_buf(b5 ? (3 + f.length) : (5 + 2 * f.length));
  6363. o.write_shift(2, i);
  6364. o.write_shift((b5 ? 1 : 2), f.length);
  6365. if(!b5) o.write_shift(1, 1);
  6366. o.write_shift((b5 ? 1 : 2) * f.length, f, (b5 ? 'sbcs' : 'utf16le'));
  6367. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  6368. if(out.l == null) out.l = out.length;
  6369. return out;
  6370. }
  6371. var parse_BIFF2Format = parse_XLUnicodeString2;
  6372. /* [MS-XLS] 2.4.90 */
  6373. function parse_Dimensions(blob, length, opts) {
  6374. var end = blob.l + length;
  6375. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  6376. var r = blob.read_shift(w), R = blob.read_shift(w);
  6377. var c = blob.read_shift(2), C = blob.read_shift(2);
  6378. blob.l = end;
  6379. return {s: {r:r, c:c}, e: {r:R, c:C}};
  6380. }
  6381. function write_Dimensions(range, opts) {
  6382. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  6383. var o = new_buf(2*w + 6);
  6384. o.write_shift(w, range.s.r);
  6385. o.write_shift(w, range.e.r + 1);
  6386. o.write_shift(2, range.s.c);
  6387. o.write_shift(2, range.e.c + 1);
  6388. o.write_shift(2, 0);
  6389. return o;
  6390. }
  6391. /* [MS-XLS] 2.4.220 */
  6392. function parse_RK(blob) {
  6393. var rw = blob.read_shift(2), col = blob.read_shift(2);
  6394. var rkrec = parse_RkRec(blob);
  6395. return {r:rw, c:col, ixfe:rkrec[0], rknum:rkrec[1]};
  6396. }
  6397. /* [MS-XLS] 2.4.175 */
  6398. function parse_MulRk(blob, length) {
  6399. var target = blob.l + length - 2;
  6400. var rw = blob.read_shift(2), col = blob.read_shift(2);
  6401. var rkrecs = [];
  6402. while(blob.l < target) rkrecs.push(parse_RkRec(blob));
  6403. if(blob.l !== target) throw new Error("MulRK read error");
  6404. var lastcol = blob.read_shift(2);
  6405. if(rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
  6406. return {r:rw, c:col, C:lastcol, rkrec:rkrecs};
  6407. }
  6408. /* [MS-XLS] 2.4.174 */
  6409. function parse_MulBlank(blob, length) {
  6410. var target = blob.l + length - 2;
  6411. var rw = blob.read_shift(2), col = blob.read_shift(2);
  6412. var ixfes = [];
  6413. while(blob.l < target) ixfes.push(blob.read_shift(2));
  6414. if(blob.l !== target) throw new Error("MulBlank read error");
  6415. var lastcol = blob.read_shift(2);
  6416. if(ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
  6417. return {r:rw, c:col, C:lastcol, ixfe:ixfes};
  6418. }
  6419. /* [MS-XLS] 2.5.20 2.5.249 TODO: interpret values here */
  6420. function parse_CellStyleXF(blob, length, style, opts) {
  6421. var o = {};
  6422. var a = blob.read_shift(4), b = blob.read_shift(4);
  6423. var c = blob.read_shift(4), d = blob.read_shift(2);
  6424. o.patternType = XLSFillPattern[c >> 26];
  6425. if(!opts.cellStyles) return o;
  6426. o.alc = a & 0x07;
  6427. o.fWrap = (a >> 3) & 0x01;
  6428. o.alcV = (a >> 4) & 0x07;
  6429. o.fJustLast = (a >> 7) & 0x01;
  6430. o.trot = (a >> 8) & 0xFF;
  6431. o.cIndent = (a >> 16) & 0x0F;
  6432. o.fShrinkToFit = (a >> 20) & 0x01;
  6433. o.iReadOrder = (a >> 22) & 0x02;
  6434. o.fAtrNum = (a >> 26) & 0x01;
  6435. o.fAtrFnt = (a >> 27) & 0x01;
  6436. o.fAtrAlc = (a >> 28) & 0x01;
  6437. o.fAtrBdr = (a >> 29) & 0x01;
  6438. o.fAtrPat = (a >> 30) & 0x01;
  6439. o.fAtrProt = (a >> 31) & 0x01;
  6440. o.dgLeft = b & 0x0F;
  6441. o.dgRight = (b >> 4) & 0x0F;
  6442. o.dgTop = (b >> 8) & 0x0F;
  6443. o.dgBottom = (b >> 12) & 0x0F;
  6444. o.icvLeft = (b >> 16) & 0x7F;
  6445. o.icvRight = (b >> 23) & 0x7F;
  6446. o.grbitDiag = (b >> 30) & 0x03;
  6447. o.icvTop = c & 0x7F;
  6448. o.icvBottom = (c >> 7) & 0x7F;
  6449. o.icvDiag = (c >> 14) & 0x7F;
  6450. o.dgDiag = (c >> 21) & 0x0F;
  6451. o.icvFore = d & 0x7F;
  6452. o.icvBack = (d >> 7) & 0x7F;
  6453. o.fsxButton = (d >> 14) & 0x01;
  6454. return o;
  6455. }
  6456. //function parse_CellXF(blob, length, opts) {return parse_CellStyleXF(blob,length,0, opts);}
  6457. //function parse_StyleXF(blob, length, opts) {return parse_CellStyleXF(blob,length,1, opts);}
  6458. /* [MS-XLS] 2.4.353 TODO: actually do this right */
  6459. function parse_XF(blob, length, opts) {
  6460. var o = {};
  6461. o.ifnt = blob.read_shift(2); o.numFmtId = blob.read_shift(2); o.flags = blob.read_shift(2);
  6462. o.fStyle = (o.flags >> 2) & 0x01;
  6463. length -= 6;
  6464. o.data = parse_CellStyleXF(blob, length, o.fStyle, opts);
  6465. return o;
  6466. }
  6467. function write_XF(data, ixfeP, opts, o) {
  6468. var b5 = (opts && (opts.biff == 5));
  6469. if(!o) o = new_buf(b5 ? 16 : 20);
  6470. o.write_shift(2, 0);
  6471. if(data.style) {
  6472. o.write_shift(2, (data.numFmtId||0));
  6473. o.write_shift(2, 0xFFF4);
  6474. } else {
  6475. o.write_shift(2, (data.numFmtId||0));
  6476. o.write_shift(2, (ixfeP<<4));
  6477. }
  6478. var f = 0;
  6479. if(data.numFmtId > 0 && b5) f |= 0x0400;
  6480. o.write_shift(4, f);
  6481. o.write_shift(4, 0);
  6482. if(!b5) o.write_shift(4, 0);
  6483. o.write_shift(2, 0);
  6484. return o;
  6485. }
  6486. /* [MS-XLS] 2.4.134 */
  6487. function parse_Guts(blob) {
  6488. blob.l += 4;
  6489. var out = [blob.read_shift(2), blob.read_shift(2)];
  6490. if(out[0] !== 0) out[0]--;
  6491. if(out[1] !== 0) out[1]--;
  6492. if(out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
  6493. return out;
  6494. }
  6495. function write_Guts(guts) {
  6496. var o = new_buf(8);
  6497. o.write_shift(4, 0);
  6498. o.write_shift(2, guts[0] ? guts[0] + 1 : 0);
  6499. o.write_shift(2, guts[1] ? guts[1] + 1 : 0);
  6500. return o;
  6501. }
  6502. /* [MS-XLS] 2.4.24 */
  6503. function parse_BoolErr(blob, length, opts) {
  6504. var cell = parse_XLSCell(blob, 6);
  6505. if(opts.biff == 2 || length == 9) ++blob.l;
  6506. var val = parse_Bes(blob, 2);
  6507. cell.val = val;
  6508. cell.t = (val === true || val === false) ? 'b' : 'e';
  6509. return cell;
  6510. }
  6511. function write_BoolErr(R, C, v, os, opts, t) {
  6512. var o = new_buf(8);
  6513. write_XLSCell(R, C, os, o);
  6514. write_Bes(v, t, o);
  6515. return o;
  6516. }
  6517. /* [MS-XLS] 2.4.180 Number */
  6518. function parse_Number(blob, length, opts) {
  6519. if(opts.biffguess && opts.biff == 2) opts.biff = 5;
  6520. var cell = parse_XLSCell(blob, 6);
  6521. var xnum = parse_Xnum(blob, 8);
  6522. cell.val = xnum;
  6523. return cell;
  6524. }
  6525. function write_Number(R, C, v, os) {
  6526. var o = new_buf(14);
  6527. write_XLSCell(R, C, os, o);
  6528. write_Xnum(v, o);
  6529. return o;
  6530. }
  6531. var parse_XLHeaderFooter = parse_OptXLUnicodeString; // TODO: parse 2.4.136
  6532. /* [MS-XLS] 2.4.271 */
  6533. function parse_SupBook(blob, length, opts) {
  6534. var end = blob.l + length;
  6535. var ctab = blob.read_shift(2);
  6536. var cch = blob.read_shift(2);
  6537. opts.sbcch = cch;
  6538. if(cch == 0x0401 || cch == 0x3A01) return [cch, ctab];
  6539. if(cch < 0x01 || cch >0xff) throw new Error("Unexpected SupBook type: "+cch);
  6540. var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
  6541. /* TODO: 2.5.277 Virtual Path */
  6542. var rgst = [];
  6543. while(end > blob.l) rgst.push(parse_XLUnicodeString(blob));
  6544. return [cch, ctab, virtPath, rgst];
  6545. }
  6546. /* [MS-XLS] 2.4.105 TODO */
  6547. function parse_ExternName(blob, length, opts) {
  6548. var flags = blob.read_shift(2);
  6549. var body;
  6550. var o = ({
  6551. fBuiltIn: flags & 0x01,
  6552. fWantAdvise: (flags >>> 1) & 0x01,
  6553. fWantPict: (flags >>> 2) & 0x01,
  6554. fOle: (flags >>> 3) & 0x01,
  6555. fOleLink: (flags >>> 4) & 0x01,
  6556. cf: (flags >>> 5) & 0x3FF,
  6557. fIcon: flags >>> 15 & 0x01
  6558. });
  6559. if(opts.sbcch === 0x3A01) body = parse_AddinUdf(blob, length-2, opts);
  6560. //else throw new Error("unsupported SupBook cch: " + opts.sbcch);
  6561. o.body = body || blob.read_shift(length-2);
  6562. if(typeof body === "string") o.Name = body;
  6563. return o;
  6564. }
  6565. /* [MS-XLS] 2.4.150 TODO */
  6566. var XLSLblBuiltIn = [
  6567. "_xlnm.Consolidate_Area",
  6568. "_xlnm.Auto_Open",
  6569. "_xlnm.Auto_Close",
  6570. "_xlnm.Extract",
  6571. "_xlnm.Database",
  6572. "_xlnm.Criteria",
  6573. "_xlnm.Print_Area",
  6574. "_xlnm.Print_Titles",
  6575. "_xlnm.Recorder",
  6576. "_xlnm.Data_Form",
  6577. "_xlnm.Auto_Activate",
  6578. "_xlnm.Auto_Deactivate",
  6579. "_xlnm.Sheet_Title",
  6580. "_xlnm._FilterDatabase"
  6581. ];
  6582. function parse_Lbl(blob, length, opts) {
  6583. var target = blob.l + length;
  6584. var flags = blob.read_shift(2);
  6585. var chKey = blob.read_shift(1);
  6586. var cch = blob.read_shift(1);
  6587. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  6588. var itab = 0;
  6589. if(!opts || opts.biff >= 5) {
  6590. if(opts.biff != 5) blob.l += 2;
  6591. itab = blob.read_shift(2);
  6592. if(opts.biff == 5) blob.l += 2;
  6593. blob.l += 4;
  6594. }
  6595. var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
  6596. if(flags & 0x20) name = XLSLblBuiltIn[name.charCodeAt(0)];
  6597. var npflen = target - blob.l; if(opts && opts.biff == 2) --npflen;
  6598. /*jshint -W018 */
  6599. var rgce = (target == blob.l || cce === 0 || !(npflen > 0)) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
  6600. /*jshint +W018 */
  6601. return {
  6602. chKey: chKey,
  6603. Name: name,
  6604. itab: itab,
  6605. rgce: rgce
  6606. };
  6607. }
  6608. /* [MS-XLS] 2.4.106 TODO: verify filename encoding */
  6609. function parse_ExternSheet(blob, length, opts) {
  6610. if(opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
  6611. var o = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
  6612. while(len-- !== 0) o.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
  6613. // [iSupBook, itabFirst, itabLast];
  6614. if(blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
  6615. return o;
  6616. }
  6617. function parse_BIFF5ExternSheet(blob, length, opts) {
  6618. if(blob[blob.l + 1] == 0x03) blob[blob.l]++;
  6619. var o = parse_ShortXLUnicodeString(blob, length, opts);
  6620. return o.charCodeAt(0) == 0x03 ? o.slice(1) : o;
  6621. }
  6622. /* [MS-XLS] 2.4.176 TODO: check older biff */
  6623. function parse_NameCmt(blob, length, opts) {
  6624. if(opts.biff < 8) { blob.l += length; return; }
  6625. var cchName = blob.read_shift(2);
  6626. var cchComment = blob.read_shift(2);
  6627. var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
  6628. var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
  6629. return [name, comment];
  6630. }
  6631. /* [MS-XLS] 2.4.260 */
  6632. function parse_ShrFmla(blob, length, opts) {
  6633. var ref = parse_RefU(blob, 6);
  6634. blob.l++;
  6635. var cUse = blob.read_shift(1);
  6636. length -= 8;
  6637. return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
  6638. }
  6639. /* [MS-XLS] 2.4.4 TODO */
  6640. function parse_Array(blob, length, opts) {
  6641. var ref = parse_Ref(blob, 6);
  6642. /* TODO: fAlwaysCalc */
  6643. switch(opts.biff) {
  6644. case 2: blob.l ++; length -= 7; break;
  6645. case 3: case 4: blob.l += 2; length -= 8; break;
  6646. default: blob.l += 6; length -= 12;
  6647. }
  6648. return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
  6649. }
  6650. /* [MS-XLS] 2.4.173 */
  6651. function parse_MTRSettings(blob) {
  6652. var fMTREnabled = blob.read_shift(4) !== 0x00;
  6653. var fUserSetThreadCount = blob.read_shift(4) !== 0x00;
  6654. var cUserThreadCount = blob.read_shift(4);
  6655. return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
  6656. }
  6657. /* [MS-XLS] 2.5.186 TODO: BIFF5 */
  6658. function parse_NoteSh(blob, length, opts) {
  6659. if(opts.biff < 8) return;
  6660. var row = blob.read_shift(2), col = blob.read_shift(2);
  6661. var flags = blob.read_shift(2), idObj = blob.read_shift(2);
  6662. var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
  6663. if(opts.biff < 8) blob.read_shift(1);
  6664. return [{r:row,c:col}, stAuthor, idObj, flags];
  6665. }
  6666. /* [MS-XLS] 2.4.179 */
  6667. function parse_Note(blob, length, opts) {
  6668. /* TODO: Support revisions */
  6669. return parse_NoteSh(blob, length, opts);
  6670. }
  6671. /* [MS-XLS] 2.4.168 */
  6672. function parse_MergeCells(blob, length) {
  6673. var merges = [];
  6674. var cmcs = blob.read_shift(2);
  6675. while (cmcs--) merges.push(parse_Ref8U(blob,length));
  6676. return merges;
  6677. }
  6678. function write_MergeCells(merges) {
  6679. var o = new_buf(2 + merges.length * 8);
  6680. o.write_shift(2, merges.length);
  6681. for(var i = 0; i < merges.length; ++i) write_Ref8U(merges[i], o);
  6682. return o;
  6683. }
  6684. /* [MS-XLS] 2.4.181 TODO: parse all the things! */
  6685. function parse_Obj(blob, length, opts) {
  6686. if(opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
  6687. var cmo = parse_FtCmo(blob, 22); // id, ot, flags
  6688. var fts = parse_FtArray(blob, length-22, cmo[1]);
  6689. return { cmo: cmo, ft:fts };
  6690. }
  6691. /* from older spec */
  6692. var parse_BIFF5OT = {
  6693. 0x08: function(blob, length) {
  6694. var tgt = blob.l + length;
  6695. blob.l += 10; // todo
  6696. var cf = blob.read_shift(2);
  6697. blob.l += 4;
  6698. blob.l += 2; //var cbPictFmla = blob.read_shift(2);
  6699. blob.l += 2;
  6700. blob.l += 2; //var grbit = blob.read_shift(2);
  6701. blob.l += 4;
  6702. var cchName = blob.read_shift(1);
  6703. blob.l += cchName; // TODO: stName
  6704. blob.l = tgt; // TODO: fmla
  6705. return { fmt:cf };
  6706. }
  6707. };
  6708. function parse_BIFF5Obj(blob, length, opts) {
  6709. blob.l += 4; //var cnt = blob.read_shift(4);
  6710. var ot = blob.read_shift(2);
  6711. var id = blob.read_shift(2);
  6712. var grbit = blob.read_shift(2);
  6713. blob.l += 2; //var colL = blob.read_shift(2);
  6714. blob.l += 2; //var dxL = blob.read_shift(2);
  6715. blob.l += 2; //var rwT = blob.read_shift(2);
  6716. blob.l += 2; //var dyT = blob.read_shift(2);
  6717. blob.l += 2; //var colR = blob.read_shift(2);
  6718. blob.l += 2; //var dxR = blob.read_shift(2);
  6719. blob.l += 2; //var rwB = blob.read_shift(2);
  6720. blob.l += 2; //var dyB = blob.read_shift(2);
  6721. blob.l += 2; //var cbMacro = blob.read_shift(2);
  6722. blob.l += 6;
  6723. length -= 36;
  6724. var fts = [];
  6725. fts.push((parse_BIFF5OT[ot]||parsenoop)(blob, length, opts));
  6726. return { cmo: [id, ot, grbit], ft:fts };
  6727. }
  6728. /* [MS-XLS] 2.4.329 TODO: parse properly */
  6729. function parse_TxO(blob, length, opts) {
  6730. var s = blob.l;
  6731. var texts = "";
  6732. try {
  6733. blob.l += 4;
  6734. var ot = (opts.lastobj||{cmo:[0,0]}).cmo[1];
  6735. var controlInfo; // eslint-disable-line no-unused-vars
  6736. if([0,5,7,11,12,14].indexOf(ot) == -1) blob.l += 6;
  6737. else controlInfo = parse_ControlInfo(blob, 6, opts); // eslint-disable-line no-unused-vars
  6738. var cchText = blob.read_shift(2);
  6739. /*var cbRuns = */blob.read_shift(2);
  6740. /*var ifntEmpty = */parseuint16(blob, 2);
  6741. var len = blob.read_shift(2);
  6742. blob.l += len;
  6743. //var fmla = parse_ObjFmla(blob, s + length - blob.l);
  6744. for(var i = 1; i < blob.lens.length-1; ++i) {
  6745. if(blob.l-s != blob.lens[i]) throw new Error("TxO: bad continue record");
  6746. var hdr = blob[blob.l];
  6747. var t = parse_XLUnicodeStringNoCch(blob, blob.lens[i+1]-blob.lens[i]-1);
  6748. texts += t;
  6749. if(texts.length >= (hdr ? cchText : 2*cchText)) break;
  6750. }
  6751. if(texts.length !== cchText && texts.length !== cchText*2) {
  6752. throw new Error("cchText: " + cchText + " != " + texts.length);
  6753. }
  6754. blob.l = s + length;
  6755. /* [MS-XLS] 2.5.272 TxORuns */
  6756. // var rgTxoRuns = [];
  6757. // for(var j = 0; j != cbRuns/8-1; ++j) blob.l += 8;
  6758. // var cchText2 = blob.read_shift(2);
  6759. // if(cchText2 !== cchText) throw new Error("TxOLastRun mismatch: " + cchText2 + " " + cchText);
  6760. // blob.l += 6;
  6761. // if(s + length != blob.l) throw new Error("TxO " + (s + length) + ", at " + blob.l);
  6762. return { t: texts };
  6763. } catch(e) { blob.l = s + length; return { t: texts }; }
  6764. }
  6765. /* [MS-XLS] 2.4.140 */
  6766. function parse_HLink(blob, length) {
  6767. var ref = parse_Ref8U(blob, 8);
  6768. blob.l += 16; /* CLSID */
  6769. var hlink = parse_Hyperlink(blob, length-24);
  6770. return [ref, hlink];
  6771. }
  6772. function write_HLink(hl) {
  6773. var O = new_buf(24);
  6774. var ref = decode_cell(hl[0]);
  6775. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  6776. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  6777. var clsid = "d0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  6778. for(var i = 0; i < 16; ++i) O.write_shift(1, parseInt(clsid[i], 16));
  6779. return bconcat([O, write_Hyperlink(hl[1])]);
  6780. }
  6781. /* [MS-XLS] 2.4.141 */
  6782. function parse_HLinkTooltip(blob, length) {
  6783. blob.read_shift(2);
  6784. var ref = parse_Ref8U(blob, 8);
  6785. var wzTooltip = blob.read_shift((length-10)/2, 'dbcs-cont');
  6786. wzTooltip = wzTooltip.replace(chr0,"");
  6787. return [ref, wzTooltip];
  6788. }
  6789. function write_HLinkTooltip(hl) {
  6790. var TT = hl[1].Tooltip;
  6791. var O = new_buf(10 + 2 * (TT.length + 1));
  6792. O.write_shift(2, 0x0800);
  6793. var ref = decode_cell(hl[0]);
  6794. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  6795. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  6796. for(var i = 0; i < TT.length; ++i) O.write_shift(2, TT.charCodeAt(i));
  6797. O.write_shift(2, 0);
  6798. return O;
  6799. }
  6800. /* [MS-XLS] 2.4.63 */
  6801. function parse_Country(blob) {
  6802. var o = [0,0], d;
  6803. d = blob.read_shift(2); o[0] = CountryEnum[d] || d;
  6804. d = blob.read_shift(2); o[1] = CountryEnum[d] || d;
  6805. return o;
  6806. }
  6807. function write_Country(o) {
  6808. if(!o) o = new_buf(4);
  6809. o.write_shift(2, 0x01);
  6810. o.write_shift(2, 0x01);
  6811. return o;
  6812. }
  6813. /* [MS-XLS] 2.4.50 ClrtClient */
  6814. function parse_ClrtClient(blob) {
  6815. var ccv = blob.read_shift(2);
  6816. var o = [];
  6817. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  6818. return o;
  6819. }
  6820. /* [MS-XLS] 2.4.188 */
  6821. function parse_Palette(blob) {
  6822. var ccv = blob.read_shift(2);
  6823. var o = [];
  6824. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  6825. return o;
  6826. }
  6827. /* [MS-XLS] 2.4.354 */
  6828. function parse_XFCRC(blob) {
  6829. blob.l += 2;
  6830. var o = {cxfs:0, crc:0};
  6831. o.cxfs = blob.read_shift(2);
  6832. o.crc = blob.read_shift(4);
  6833. return o;
  6834. }
  6835. /* [MS-XLS] 2.4.53 TODO: parse flags */
  6836. /* [MS-XLSB] 2.4.323 TODO: parse flags */
  6837. function parse_ColInfo(blob, length, opts) {
  6838. if(!opts.cellStyles) return parsenoop(blob, length);
  6839. var w = opts && opts.biff >= 12 ? 4 : 2;
  6840. var colFirst = blob.read_shift(w);
  6841. var colLast = blob.read_shift(w);
  6842. var coldx = blob.read_shift(w);
  6843. var ixfe = blob.read_shift(w);
  6844. var flags = blob.read_shift(2);
  6845. if(w == 2) blob.l += 2;
  6846. var o = ({s:colFirst, e:colLast, w:coldx, ixfe:ixfe, flags:flags});
  6847. if(opts.biff >= 5 || !opts.biff) o.level = (flags >> 8) & 0x7;
  6848. return o;
  6849. }
  6850. function write_ColInfo(col, idx) {
  6851. var o = new_buf(12);
  6852. o.write_shift(2, idx);
  6853. o.write_shift(2, idx);
  6854. o.write_shift(2, col.width * 256);
  6855. o.write_shift(2, 0);
  6856. var f = 0;
  6857. if(col.hidden) f |= 1;
  6858. o.write_shift(1, f);
  6859. f = col.level || 0;
  6860. o.write_shift(1, f);
  6861. o.write_shift(2, 0);
  6862. return o;
  6863. }
  6864. /* [MS-XLS] 2.4.257 */
  6865. function parse_Setup(blob, length) {
  6866. var o = {};
  6867. if(length < 32) return o;
  6868. blob.l += 16;
  6869. o.header = parse_Xnum(blob, 8);
  6870. o.footer = parse_Xnum(blob, 8);
  6871. blob.l += 2;
  6872. return o;
  6873. }
  6874. /* [MS-XLS] 2.4.261 */
  6875. function parse_ShtProps(blob, length, opts) {
  6876. var def = {area:false};
  6877. if(opts.biff != 5) { blob.l += length; return def; }
  6878. var d = blob.read_shift(1); blob.l += 3;
  6879. if((d & 0x10)) def.area = true;
  6880. return def;
  6881. }
  6882. /* [MS-XLS] 2.4.241 */
  6883. function write_RRTabId(n) {
  6884. var out = new_buf(2 * n);
  6885. for(var i = 0; i < n; ++i) out.write_shift(2, i+1);
  6886. return out;
  6887. }
  6888. var parse_Blank = parse_XLSCell; /* [MS-XLS] 2.4.20 Just the cell */
  6889. var parse_Scl = parseuint16a; /* [MS-XLS] 2.4.247 num, den */
  6890. var parse_String = parse_XLUnicodeString; /* [MS-XLS] 2.4.268 */
  6891. /* --- Specific to versions before BIFF8 --- */
  6892. function parse_ImData(blob) {
  6893. var cf = blob.read_shift(2);
  6894. var env = blob.read_shift(2);
  6895. var lcb = blob.read_shift(4);
  6896. var o = {fmt:cf, env:env, len:lcb, data:blob.slice(blob.l,blob.l+lcb)};
  6897. blob.l += lcb;
  6898. return o;
  6899. }
  6900. /* BIFF2_??? where ??? is the name from [XLS] */
  6901. function parse_BIFF2STR(blob, length, opts) {
  6902. if(opts.biffguess && opts.biff == 5) opts.biff = 2;
  6903. var cell = parse_XLSCell(blob, 6);
  6904. ++blob.l;
  6905. var str = parse_XLUnicodeString2(blob, length-7, opts);
  6906. cell.t = 'str';
  6907. cell.val = str;
  6908. return cell;
  6909. }
  6910. function parse_BIFF2NUM(blob) {
  6911. var cell = parse_XLSCell(blob, 6);
  6912. ++blob.l;
  6913. var num = parse_Xnum(blob, 8);
  6914. cell.t = 'n';
  6915. cell.val = num;
  6916. return cell;
  6917. }
  6918. function write_BIFF2NUM(r, c, val) {
  6919. var out = new_buf(15);
  6920. write_BIFF2Cell(out, r, c);
  6921. out.write_shift(8, val, 'f');
  6922. return out;
  6923. }
  6924. function parse_BIFF2INT(blob) {
  6925. var cell = parse_XLSCell(blob, 6);
  6926. ++blob.l;
  6927. var num = blob.read_shift(2);
  6928. cell.t = 'n';
  6929. cell.val = num;
  6930. return cell;
  6931. }
  6932. function write_BIFF2INT(r, c, val) {
  6933. var out = new_buf(9);
  6934. write_BIFF2Cell(out, r, c);
  6935. out.write_shift(2, val);
  6936. return out;
  6937. }
  6938. function parse_BIFF2STRING(blob) {
  6939. var cch = blob.read_shift(1);
  6940. if(cch === 0) { blob.l++; return ""; }
  6941. return blob.read_shift(cch, 'sbcs-cont');
  6942. }
  6943. /* TODO: convert to BIFF8 font struct */
  6944. function parse_BIFF2FONTXTRA(blob, length) {
  6945. blob.l += 6; // unknown
  6946. blob.l += 2; // font weight "bls"
  6947. blob.l += 1; // charset
  6948. blob.l += 3; // unknown
  6949. blob.l += 1; // font family
  6950. blob.l += length - 13;
  6951. }
  6952. /* TODO: parse rich text runs */
  6953. function parse_RString(blob, length, opts) {
  6954. var end = blob.l + length;
  6955. var cell = parse_XLSCell(blob, 6);
  6956. var cch = blob.read_shift(2);
  6957. var str = parse_XLUnicodeStringNoCch(blob, cch, opts);
  6958. blob.l = end;
  6959. cell.t = 'str';
  6960. cell.val = str;
  6961. return cell;
  6962. }
  6963. /* from js-harb (C) 2014-present SheetJS */
  6964. var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
  6965. var DBF = (function() {
  6966. var dbf_codepage_map = {
  6967. /* Code Pages Supported by Visual FoxPro */
  6968. 0x01: 437, 0x02: 850,
  6969. 0x03: 1252, 0x04: 10000,
  6970. 0x64: 852, 0x65: 866,
  6971. 0x66: 865, 0x67: 861,
  6972. 0x68: 895, 0x69: 620,
  6973. 0x6A: 737, 0x6B: 857,
  6974. 0x78: 950, 0x79: 949,
  6975. 0x7A: 936, 0x7B: 932,
  6976. 0x7C: 874, 0x7D: 1255,
  6977. 0x7E: 1256, 0x96: 10007,
  6978. 0x97: 10029, 0x98: 10006,
  6979. 0xC8: 1250, 0xC9: 1251,
  6980. 0xCA: 1254, 0xCB: 1253,
  6981. /* shapefile DBF extension */
  6982. 0x00: 20127, 0x08: 865,
  6983. 0x09: 437, 0x0A: 850,
  6984. 0x0B: 437, 0x0D: 437,
  6985. 0x0E: 850, 0x0F: 437,
  6986. 0x10: 850, 0x11: 437,
  6987. 0x12: 850, 0x13: 932,
  6988. 0x14: 850, 0x15: 437,
  6989. 0x16: 850, 0x17: 865,
  6990. 0x18: 437, 0x19: 437,
  6991. 0x1A: 850, 0x1B: 437,
  6992. 0x1C: 863, 0x1D: 850,
  6993. 0x1F: 852, 0x22: 852,
  6994. 0x23: 852, 0x24: 860,
  6995. 0x25: 850, 0x26: 866,
  6996. 0x37: 850, 0x40: 852,
  6997. 0x4D: 936, 0x4E: 949,
  6998. 0x4F: 950, 0x50: 874,
  6999. 0x57: 1252, 0x58: 1252,
  7000. 0x59: 1252, 0x6C: 863,
  7001. 0x86: 737, 0x87: 852,
  7002. 0x88: 857, 0xCC: 1257,
  7003. 0xFF: 16969
  7004. };
  7005. var dbf_reverse_map = evert({
  7006. 0x01: 437, 0x02: 850,
  7007. 0x03: 1252, 0x04: 10000,
  7008. 0x64: 852, 0x65: 866,
  7009. 0x66: 865, 0x67: 861,
  7010. 0x68: 895, 0x69: 620,
  7011. 0x6A: 737, 0x6B: 857,
  7012. 0x78: 950, 0x79: 949,
  7013. 0x7A: 936, 0x7B: 932,
  7014. 0x7C: 874, 0x7D: 1255,
  7015. 0x7E: 1256, 0x96: 10007,
  7016. 0x97: 10029, 0x98: 10006,
  7017. 0xC8: 1250, 0xC9: 1251,
  7018. 0xCA: 1254, 0xCB: 1253,
  7019. 0x00: 20127
  7020. });
  7021. /* TODO: find an actual specification */
  7022. function dbf_to_aoa(buf, opts) {
  7023. var out = [];
  7024. var d = (new_raw_buf(1));
  7025. switch(opts.type) {
  7026. case 'base64': d = s2a(Base64_decode(buf)); break;
  7027. case 'binary': d = s2a(buf); break;
  7028. case 'buffer':
  7029. case 'array': d = buf; break;
  7030. }
  7031. prep_blob(d, 0);
  7032. /* header */
  7033. var ft = d.read_shift(1);
  7034. var memo = !!(ft & 0x88);
  7035. var vfp = false, l7 = false;
  7036. switch(ft) {
  7037. case 0x02: break; // dBASE II
  7038. case 0x03: break; // dBASE III
  7039. case 0x30: vfp = true; memo = true; break; // VFP
  7040. case 0x31: vfp = true; memo = true; break; // VFP with autoincrement
  7041. // 0x43 dBASE IV SQL table files
  7042. // 0x63 dBASE IV SQL system files
  7043. case 0x83: break; // dBASE III with memo
  7044. case 0x8B: break; // dBASE IV with memo
  7045. case 0x8C: l7 = true; break; // dBASE Level 7 with memo
  7046. // case 0xCB dBASE IV SQL table files with memo
  7047. case 0xF5: break; // FoxPro 2.x with memo
  7048. // case 0xFB FoxBASE
  7049. default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
  7050. }
  7051. var nrow = 0, fpos = 0x0209;
  7052. if(ft == 0x02) nrow = d.read_shift(2);
  7053. d.l += 3; // dBASE II stores DDMMYY date, others use YYMMDD
  7054. if(ft != 0x02) nrow = d.read_shift(4);
  7055. if(nrow > 1048576) nrow = 1e6;
  7056. if(ft != 0x02) fpos = d.read_shift(2); // header length
  7057. var rlen = d.read_shift(2); // record length
  7058. var /*flags = 0,*/ current_cp = opts.codepage || 1252;
  7059. if(ft != 0x02) { // 20 reserved bytes
  7060. d.l+=16;
  7061. /*flags = */d.read_shift(1);
  7062. //if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));
  7063. /* codepage present in FoxPro and dBASE Level 7 */
  7064. if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
  7065. d.l+=1;
  7066. d.l+=2;
  7067. }
  7068. if(l7) d.l += 36; // Level 7: 32 byte "Language driver name", 4 byte reserved
  7069. var fields = [], field = ({});
  7070. var hend = Math.min(d.length, (ft == 0x02 ? 0x209 : (fpos - 10 - (vfp ? 264 : 0))));
  7071. var ww = l7 ? 32 : 11;
  7072. while(d.l < hend && d[d.l] != 0x0d) {
  7073. field = ({});
  7074. field.name = $cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)).replace(/[\u0000\r\n].*$/g,"");
  7075. d.l += ww;
  7076. field.type = String.fromCharCode(d.read_shift(1));
  7077. if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
  7078. field.len = d.read_shift(1);
  7079. if(ft == 0x02) field.offset = d.read_shift(2);
  7080. field.dec = d.read_shift(1);
  7081. if(field.name.length) fields.push(field);
  7082. if(ft != 0x02) d.l += l7 ? 13 : 14;
  7083. switch(field.type) {
  7084. case 'B': // Double (VFP) / Binary (dBASE L7)
  7085. if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  7086. break;
  7087. case 'G': // General (FoxPro and dBASE L7)
  7088. case 'P': // Picture (FoxPro and dBASE L7)
  7089. if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  7090. break;
  7091. case '+': // Autoincrement (dBASE L7 only)
  7092. case '0': // _NullFlags (VFP only)
  7093. case '@': // Timestamp (dBASE L7 only)
  7094. case 'C': // Character (dBASE II)
  7095. case 'D': // Date (dBASE III)
  7096. case 'F': // Float (dBASE IV)
  7097. case 'I': // Long (VFP and dBASE L7)
  7098. case 'L': // Logical (dBASE II)
  7099. case 'M': // Memo (dBASE III)
  7100. case 'N': // Number (dBASE II)
  7101. case 'O': // Double (dBASE L7 only)
  7102. case 'T': // Datetime (VFP only)
  7103. case 'Y': // Currency (VFP only)
  7104. break;
  7105. default: throw new Error('Unknown Field Type: ' + field.type);
  7106. }
  7107. }
  7108. if(d[d.l] !== 0x0D) d.l = fpos-1;
  7109. if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
  7110. d.l = fpos;
  7111. /* data */
  7112. var R = 0, C = 0;
  7113. out[0] = [];
  7114. for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
  7115. while(nrow-- > 0) {
  7116. if(d[d.l] === 0x2A) {
  7117. // TODO: record marked as deleted -- create a hidden row?
  7118. d.l+=rlen;
  7119. continue;
  7120. }
  7121. ++d.l;
  7122. out[++R] = []; C = 0;
  7123. for(C = 0; C != fields.length; ++C) {
  7124. var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
  7125. prep_blob(dd, 0);
  7126. var s = $cptable.utils.decode(current_cp, dd);
  7127. switch(fields[C].type) {
  7128. case 'C':
  7129. // NOTE: it is conventional to write ' / / ' for empty dates
  7130. if(s.trim().length) out[R][C] = s.replace(/\s+$/,"");
  7131. break;
  7132. case 'D':
  7133. if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
  7134. else out[R][C] = s;
  7135. break;
  7136. case 'F': out[R][C] = parseFloat(s.trim()); break;
  7137. case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
  7138. case 'L': switch(s.trim().toUpperCase()) {
  7139. case 'Y': case 'T': out[R][C] = true; break;
  7140. case 'N': case 'F': out[R][C] = false; break;
  7141. case '': case '?': break;
  7142. default: throw new Error("DBF Unrecognized L:|" + s + "|");
  7143. } break;
  7144. case 'M': /* TODO: handle memo files */
  7145. if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
  7146. out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
  7147. break;
  7148. case 'N':
  7149. s = s.replace(/\u0000/g,"").trim();
  7150. // NOTE: dBASE II interprets " . " as 0
  7151. if(s && s != ".") out[R][C] = +s || 0; break;
  7152. case '@':
  7153. // NOTE: dBASE specs appear to be incorrect
  7154. out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400);
  7155. break;
  7156. case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
  7157. case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4 + (dd.read_shift(4, 'i')/1e4)*Math.pow(2,32); break;
  7158. case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
  7159. case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
  7160. /* falls through */
  7161. case 'G': case 'P': dd.l += fields[C].len; break;
  7162. case '0':
  7163. if(fields[C].name === '_NullFlags') break;
  7164. /* falls through */
  7165. default: throw new Error("DBF Unsupported data type " + fields[C].type);
  7166. }
  7167. }
  7168. }
  7169. 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));
  7170. if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
  7171. opts.DBF = fields;
  7172. return out;
  7173. }
  7174. function dbf_to_sheet(buf, opts) {
  7175. var o = opts || {};
  7176. if(!o.dateNF) o.dateNF = "yyyymmdd";
  7177. var ws = aoa_to_sheet(dbf_to_aoa(buf, o), o);
  7178. ws["!cols"] = o.DBF.map(function(field) { return {
  7179. wch: field.len,
  7180. DBF: field
  7181. };});
  7182. delete o.DBF;
  7183. return ws;
  7184. }
  7185. function dbf_to_workbook(buf, opts) {
  7186. try { return sheet_to_workbook(dbf_to_sheet(buf, opts), opts); }
  7187. catch(e) { if(opts && opts.WTF) throw e; }
  7188. return ({SheetNames:[],Sheets:{}});
  7189. }
  7190. var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
  7191. function sheet_to_dbf(ws, opts) {
  7192. var o = opts || {};
  7193. if(+o.codepage >= 0) set_cp(+o.codepage);
  7194. if(o.type == "string") throw new Error("Cannot write DBF to JS string");
  7195. var ba = buf_array();
  7196. var aoa = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
  7197. var headers = aoa[0], data = aoa.slice(1), cols = ws["!cols"] || [];
  7198. var i = 0, j = 0, hcnt = 0, rlen = 1;
  7199. for(i = 0; i < headers.length; ++i) {
  7200. if(((cols[i]||{}).DBF||{}).name) { headers[i] = cols[i].DBF.name; ++hcnt; continue; }
  7201. if(headers[i] == null) continue;
  7202. ++hcnt;
  7203. if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
  7204. if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
  7205. if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
  7206. if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
  7207. }
  7208. var range = safe_decode_range(ws['!ref']);
  7209. var coltypes = [];
  7210. var colwidths = [];
  7211. var coldecimals = [];
  7212. for(i = 0; i <= range.e.c - range.s.c; ++i) {
  7213. var guess = '', _guess = '', maxlen = 0;
  7214. var col = [];
  7215. for(j=0; j < data.length; ++j) {
  7216. if(data[j][i] != null) col.push(data[j][i]);
  7217. }
  7218. if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
  7219. for(j = 0; j < col.length; ++j) {
  7220. switch(typeof col[j]) {
  7221. /* TODO: check if L2 compat is desired */
  7222. case 'number': _guess = 'B'; break;
  7223. case 'string': _guess = 'C'; break;
  7224. case 'boolean': _guess = 'L'; break;
  7225. case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
  7226. default: _guess = 'C';
  7227. }
  7228. maxlen = Math.max(maxlen, String(col[j]).length);
  7229. guess = guess && guess != _guess ? 'C' : _guess;
  7230. //if(guess == 'C') break;
  7231. }
  7232. if(maxlen > 250) maxlen = 250;
  7233. _guess = ((cols[i]||{}).DBF||{}).type;
  7234. /* TODO: more fine grained control over DBF type resolution */
  7235. if(_guess == 'C') {
  7236. if(cols[i].DBF.len > maxlen) maxlen = cols[i].DBF.len;
  7237. }
  7238. if(guess == 'B' && _guess == 'N') {
  7239. guess = 'N';
  7240. coldecimals[i] = cols[i].DBF.dec;
  7241. maxlen = cols[i].DBF.len;
  7242. }
  7243. colwidths[i] = guess == 'C' || _guess == 'N' ? maxlen : (_RLEN[guess] || 0);
  7244. rlen += colwidths[i];
  7245. coltypes[i] = guess;
  7246. }
  7247. var h = ba.next(32);
  7248. h.write_shift(4, 0x13021130);
  7249. h.write_shift(4, data.length);
  7250. h.write_shift(2, 296 + 32 * hcnt);
  7251. h.write_shift(2, rlen);
  7252. for(i=0; i < 4; ++i) h.write_shift(4, 0);
  7253. h.write_shift(4, 0x00000000 | ((+dbf_reverse_map[current_ansi] || 0x03)<<8));
  7254. for(i = 0, j = 0; i < headers.length; ++i) {
  7255. if(headers[i] == null) continue;
  7256. var hf = ba.next(32);
  7257. var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
  7258. hf.write_shift(1, _f, "sbcs");
  7259. hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
  7260. hf.write_shift(4, j);
  7261. hf.write_shift(1, colwidths[i] || _RLEN[coltypes[i]] || 0);
  7262. hf.write_shift(1, coldecimals[i] || 0);
  7263. hf.write_shift(1, 0x02);
  7264. hf.write_shift(4, 0);
  7265. hf.write_shift(1, 0);
  7266. hf.write_shift(4, 0);
  7267. hf.write_shift(4, 0);
  7268. j += (colwidths[i] || _RLEN[coltypes[i]] || 0);
  7269. }
  7270. var hb = ba.next(264);
  7271. hb.write_shift(4, 0x0000000D);
  7272. for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
  7273. for(i=0; i < data.length; ++i) {
  7274. var rout = ba.next(rlen);
  7275. rout.write_shift(1, 0);
  7276. for(j=0; j<headers.length; ++j) {
  7277. if(headers[j] == null) continue;
  7278. switch(coltypes[j]) {
  7279. case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
  7280. case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
  7281. case 'N':
  7282. var _n = "0";
  7283. if(typeof data[i][j] == "number") _n = data[i][j].toFixed(coldecimals[j]||0);
  7284. for(hcnt=0; hcnt < colwidths[j]-_n.length; ++hcnt) rout.write_shift(1, 0x20);
  7285. rout.write_shift(1, _n, "sbcs");
  7286. break;
  7287. case 'D':
  7288. if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
  7289. else {
  7290. rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
  7291. rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
  7292. rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
  7293. } break;
  7294. case 'C':
  7295. var _s = String(data[i][j] != null ? data[i][j] : "").slice(0, colwidths[j]);
  7296. rout.write_shift(1, _s, "sbcs");
  7297. for(hcnt=0; hcnt < colwidths[j]-_s.length; ++hcnt) rout.write_shift(1, 0x20); break;
  7298. }
  7299. }
  7300. // data
  7301. }
  7302. ba.next(1).write_shift(1, 0x1A);
  7303. return ba.end();
  7304. }
  7305. return {
  7306. to_workbook: dbf_to_workbook,
  7307. to_sheet: dbf_to_sheet,
  7308. from_sheet: sheet_to_dbf
  7309. };
  7310. })();
  7311. var SYLK = (function() {
  7312. /* TODO: stress test sequences */
  7313. var sylk_escapes = ({
  7314. AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
  7315. AE:'È', BE:'É', CE:'Ê', HE:'Ë',
  7316. AI:'Ì', BI:'Í', CI:'Î', HI:'Ï',
  7317. AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
  7318. AU:'Ù', BU:'Ú', CU:'Û', HU:'Ü',
  7319. Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
  7320. Ae:'è', Be:'é', Ce:'ê', He:'ë',
  7321. Ai:'ì', Bi:'í', Ci:'î', Hi:'ï',
  7322. Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
  7323. Au:'ù', Bu:'ú', Cu:'û', Hu:'ü',
  7324. KC:'Ç', Kc:'ç', q:'æ', z:'œ', a:'Æ', j:'Œ',
  7325. DN:209, Dn:241, Hy:255,
  7326. S:169, c:170, R:174, "B ":180,
  7327. 0:176, 1:177, 2:178,
  7328. 3:179, 5:181, 6:182,
  7329. 7:183, Q:185, k:186, b:208, i:216, l:222, s:240, y:248,
  7330. "!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
  7331. "+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
  7332. });
  7333. var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
  7334. var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
  7335. var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
  7336. sylk_escapes["|"] = 254;
  7337. /* TODO: find an actual specification */
  7338. function sylk_to_aoa(d, opts) {
  7339. switch(opts.type) {
  7340. case 'base64': return sylk_to_aoa_str(Base64_decode(d), opts);
  7341. case 'binary': return sylk_to_aoa_str(d, opts);
  7342. case 'buffer': return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  7343. case 'array': return sylk_to_aoa_str(cc2str(d), opts);
  7344. }
  7345. throw new Error("Unrecognized type " + opts.type);
  7346. }
  7347. function sylk_to_aoa_str(str, opts) {
  7348. var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr = [];
  7349. var formats = [];
  7350. var next_cell_format = null;
  7351. var sht = {}, rowinfo = [], colinfo = [], cw = [];
  7352. var Mval = 0, j;
  7353. if(+opts.codepage >= 0) set_cp(+opts.codepage);
  7354. for (; ri !== records.length; ++ri) {
  7355. Mval = 0;
  7356. var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
  7357. var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
  7358. var RT=record[0], val;
  7359. if(rstr.length > 0) switch(RT) {
  7360. case 'ID': break; /* header */
  7361. case 'E': break; /* EOF */
  7362. case 'B': break; /* dimensions */
  7363. case 'O': break; /* options? */
  7364. case 'W': break; /* window? */
  7365. case 'P':
  7366. if(record[1].charAt(0) == 'P')
  7367. formats.push(rstr.slice(3).replace(/;;/g, ";"));
  7368. break;
  7369. case 'C':
  7370. var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1;
  7371. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  7372. case 'A': break; // TODO: comment
  7373. case 'X': C = parseInt(record[rj].slice(1))-1; C_seen_X = true; break;
  7374. case 'Y':
  7375. R = parseInt(record[rj].slice(1))-1; if(!C_seen_X) C = 0;
  7376. for(j = arr.length; j <= R; ++j) arr[j] = [];
  7377. break;
  7378. case 'K':
  7379. val = record[rj].slice(1);
  7380. if(val.charAt(0) === '"') val = val.slice(1,val.length - 1);
  7381. else if(val === 'TRUE') val = true;
  7382. else if(val === 'FALSE') val = false;
  7383. else if(!isNaN(fuzzynum(val))) {
  7384. val = fuzzynum(val);
  7385. if(next_cell_format !== null && fmt_is_date(next_cell_format)) val = numdate(val);
  7386. } else if(!isNaN(fuzzydate(val).getDate())) {
  7387. val = parseDate(val);
  7388. }
  7389. if(typeof $cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = $cptable.utils.decode(opts.codepage, val);
  7390. C_seen_K = true;
  7391. break;
  7392. case 'E':
  7393. C_seen_E = true;
  7394. var formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
  7395. arr[R][C] = [arr[R][C], formula];
  7396. break;
  7397. case 'S':
  7398. C_seen_S = true;
  7399. arr[R][C] = [arr[R][C], "S5S"];
  7400. break;
  7401. case 'G': break; // unknown
  7402. case 'R': _R = parseInt(record[rj].slice(1))-1; break;
  7403. case 'C': _C = parseInt(record[rj].slice(1))-1; break;
  7404. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  7405. }
  7406. if(C_seen_K) {
  7407. if(arr[R][C] && arr[R][C].length == 2) arr[R][C][0] = val;
  7408. else arr[R][C] = val;
  7409. next_cell_format = null;
  7410. }
  7411. if(C_seen_S) {
  7412. if(C_seen_E) throw new Error("SYLK shared formula cannot have own formula");
  7413. var shrbase = _R > -1 && arr[_R][_C];
  7414. if(!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base");
  7415. arr[R][C][1] = shift_formula_str(shrbase[1], {r: R - _R, c: C - _C});
  7416. }
  7417. break;
  7418. case 'F':
  7419. var F_seen = 0;
  7420. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  7421. case 'X': C = parseInt(record[rj].slice(1))-1; ++F_seen; break;
  7422. case 'Y':
  7423. R = parseInt(record[rj].slice(1))-1; /*C = 0;*/
  7424. for(j = arr.length; j <= R; ++j) arr[j] = [];
  7425. break;
  7426. case 'M': Mval = parseInt(record[rj].slice(1)) / 20; break;
  7427. case 'F': break; /* ??? */
  7428. case 'G': break; /* hide grid */
  7429. case 'P':
  7430. next_cell_format = formats[parseInt(record[rj].slice(1))];
  7431. break;
  7432. case 'S': break; /* cell style */
  7433. case 'D': break; /* column */
  7434. case 'N': break; /* font */
  7435. case 'W':
  7436. cw = record[rj].slice(1).split(" ");
  7437. for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
  7438. Mval = parseInt(cw[2], 10);
  7439. colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval}; process_col(colinfo[j-1]);
  7440. } break;
  7441. case 'C': /* default column format */
  7442. C = parseInt(record[rj].slice(1))-1;
  7443. if(!colinfo[C]) colinfo[C] = {};
  7444. break;
  7445. case 'R': /* row properties */
  7446. R = parseInt(record[rj].slice(1))-1;
  7447. if(!rowinfo[R]) rowinfo[R] = {};
  7448. if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
  7449. else if(Mval === 0) rowinfo[R].hidden = true;
  7450. break;
  7451. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  7452. }
  7453. if(F_seen < 1) next_cell_format = null; break;
  7454. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  7455. }
  7456. }
  7457. if(rowinfo.length > 0) sht['!rows'] = rowinfo;
  7458. if(colinfo.length > 0) sht['!cols'] = colinfo;
  7459. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  7460. return [arr, sht];
  7461. }
  7462. function sylk_to_sheet(d, opts) {
  7463. var aoasht = sylk_to_aoa(d, opts);
  7464. var aoa = aoasht[0], ws = aoasht[1];
  7465. var o = aoa_to_sheet(aoa, opts);
  7466. keys(ws).forEach(function(k) { o[k] = ws[k]; });
  7467. return o;
  7468. }
  7469. function sylk_to_workbook(d, opts) { return sheet_to_workbook(sylk_to_sheet(d, opts), opts); }
  7470. function write_ws_cell_sylk(cell, ws, R, C) {
  7471. var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
  7472. switch(cell.t) {
  7473. case 'n':
  7474. o += (cell.v||0);
  7475. if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
  7476. case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
  7477. case 'e': o += cell.w || cell.v; break;
  7478. case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
  7479. case 's': o += '"' + cell.v.replace(/"/g,"").replace(/;/g, ";;") + '"'; break;
  7480. }
  7481. return o;
  7482. }
  7483. function write_ws_cols_sylk(out, cols) {
  7484. cols.forEach(function(col, i) {
  7485. var rec = "F;W" + (i+1) + " " + (i+1) + " ";
  7486. if(col.hidden) rec += "0";
  7487. else {
  7488. if(typeof col.width == 'number' && !col.wpx) col.wpx = width2px(col.width);
  7489. if(typeof col.wpx == 'number' && !col.wch) col.wch = px2char(col.wpx);
  7490. if(typeof col.wch == 'number') rec += Math.round(col.wch);
  7491. }
  7492. if(rec.charAt(rec.length - 1) != " ") out.push(rec);
  7493. });
  7494. }
  7495. function write_ws_rows_sylk(out, rows) {
  7496. rows.forEach(function(row, i) {
  7497. var rec = "F;";
  7498. if(row.hidden) rec += "M0;";
  7499. else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
  7500. else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
  7501. if(rec.length > 2) out.push(rec + "R" + (i+1));
  7502. });
  7503. }
  7504. function sheet_to_sylk(ws, opts) {
  7505. var preamble = ["ID;PWXL;N;E"], o = [];
  7506. var r = safe_decode_range(ws['!ref']), cell;
  7507. var dense = Array.isArray(ws);
  7508. var RS = "\r\n";
  7509. preamble.push("P;PGeneral");
  7510. preamble.push("F;P0;DG0G8;M255");
  7511. if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
  7512. if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);
  7513. 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(" "));
  7514. for(var R = r.s.r; R <= r.e.r; ++R) {
  7515. for(var C = r.s.c; C <= r.e.c; ++C) {
  7516. var coord = encode_cell({r:R,c:C});
  7517. cell = dense ? (ws[R]||[])[C]: ws[coord];
  7518. if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
  7519. o.push(write_ws_cell_sylk(cell, ws, R, C, opts));
  7520. }
  7521. }
  7522. return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
  7523. }
  7524. return {
  7525. to_workbook: sylk_to_workbook,
  7526. to_sheet: sylk_to_sheet,
  7527. from_sheet: sheet_to_sylk
  7528. };
  7529. })();
  7530. var DIF = (function() {
  7531. function dif_to_aoa(d, opts) {
  7532. switch(opts.type) {
  7533. case 'base64': return dif_to_aoa_str(Base64_decode(d), opts);
  7534. case 'binary': return dif_to_aoa_str(d, opts);
  7535. case 'buffer': return dif_to_aoa_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  7536. case 'array': return dif_to_aoa_str(cc2str(d), opts);
  7537. }
  7538. throw new Error("Unrecognized type " + opts.type);
  7539. }
  7540. function dif_to_aoa_str(str, opts) {
  7541. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  7542. for (; ri !== records.length; ++ri) {
  7543. if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
  7544. if (R < 0) continue;
  7545. var metadata = records[ri].trim().split(",");
  7546. var type = metadata[0], value = metadata[1];
  7547. ++ri;
  7548. var data = records[ri] || "";
  7549. while(((data.match(/["]/g)||[]).length & 1) && ri < records.length - 1) data += "\n" + records[++ri];
  7550. data = data.trim();
  7551. switch (+type) {
  7552. case -1:
  7553. if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
  7554. else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
  7555. break;
  7556. case 0:
  7557. if(data === 'TRUE') arr[R][C] = true;
  7558. else if(data === 'FALSE') arr[R][C] = false;
  7559. else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
  7560. else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
  7561. else arr[R][C] = value;
  7562. ++C; break;
  7563. case 1:
  7564. data = data.slice(1,data.length-1);
  7565. data = data.replace(/""/g, '"');
  7566. if(DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1);
  7567. arr[R][C++] = data !== '' ? data : null;
  7568. break;
  7569. }
  7570. if (data === 'EOD') break;
  7571. }
  7572. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  7573. return arr;
  7574. }
  7575. function dif_to_sheet(str, opts) { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
  7576. function dif_to_workbook(str, opts) { return sheet_to_workbook(dif_to_sheet(str, opts), opts); }
  7577. var sheet_to_dif = (function() {
  7578. var push_field = function pf(o, topic, v, n, s) {
  7579. o.push(topic);
  7580. o.push(v + "," + n);
  7581. o.push('"' + s.replace(/"/g,'""') + '"');
  7582. };
  7583. var push_value = function po(o, type, v, s) {
  7584. o.push(type + "," + v);
  7585. o.push(type == 1 ? '"' + s.replace(/"/g,'""') + '"' : s);
  7586. };
  7587. return function sheet_to_dif(ws) {
  7588. var o = [];
  7589. var r = safe_decode_range(ws['!ref']), cell;
  7590. var dense = Array.isArray(ws);
  7591. push_field(o, "TABLE", 0, 1, "sheetjs");
  7592. push_field(o, "VECTORS", 0, r.e.r - r.s.r + 1,"");
  7593. push_field(o, "TUPLES", 0, r.e.c - r.s.c + 1,"");
  7594. push_field(o, "DATA", 0, 0,"");
  7595. for(var R = r.s.r; R <= r.e.r; ++R) {
  7596. push_value(o, -1, 0, "BOT");
  7597. for(var C = r.s.c; C <= r.e.c; ++C) {
  7598. var coord = encode_cell({r:R,c:C});
  7599. cell = dense ? (ws[R]||[])[C] : ws[coord];
  7600. if(!cell) { push_value(o, 1, 0, ""); continue;}
  7601. switch(cell.t) {
  7602. case 'n':
  7603. var val = DIF_XL ? cell.w : cell.v;
  7604. if(!val && cell.v != null) val = cell.v;
  7605. if(val == null) {
  7606. if(DIF_XL && cell.f && !cell.F) push_value(o, 1, 0, "=" + cell.f);
  7607. else push_value(o, 1, 0, "");
  7608. }
  7609. else push_value(o, 0, val, "V");
  7610. break;
  7611. case 'b':
  7612. push_value(o, 0, cell.v ? 1 : 0, cell.v ? "TRUE" : "FALSE");
  7613. break;
  7614. case 's':
  7615. push_value(o, 1, 0, (!DIF_XL || isNaN(cell.v)) ? cell.v : '="' + cell.v + '"');
  7616. break;
  7617. case 'd':
  7618. if(!cell.w) cell.w = SSF_format(cell.z || table_fmt[14], datenum(parseDate(cell.v)));
  7619. if(DIF_XL) push_value(o, 0, cell.w, "V");
  7620. else push_value(o, 1, 0, cell.w);
  7621. break;
  7622. default: push_value(o, 1, 0, "");
  7623. }
  7624. }
  7625. }
  7626. push_value(o, -1, 0, "EOD");
  7627. var RS = "\r\n";
  7628. var oo = o.join(RS);
  7629. //while((oo.length & 0x7F) != 0) oo += "\0";
  7630. return oo;
  7631. };
  7632. })();
  7633. return {
  7634. to_workbook: dif_to_workbook,
  7635. to_sheet: dif_to_sheet,
  7636. from_sheet: sheet_to_dif
  7637. };
  7638. })();
  7639. var ETH = (function() {
  7640. function decode(s) { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
  7641. function encode(s) { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }
  7642. function eth_to_aoa(str, opts) {
  7643. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  7644. for (; ri !== records.length; ++ri) {
  7645. var record = records[ri].trim().split(":");
  7646. if(record[0] !== 'cell') continue;
  7647. var addr = decode_cell(record[1]);
  7648. if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
  7649. R = addr.r; C = addr.c;
  7650. switch(record[2]) {
  7651. case 't': arr[R][C] = decode(record[3]); break;
  7652. case 'v': arr[R][C] = +record[3]; break;
  7653. case 'vtf': var _f = record[record.length - 1];
  7654. /* falls through */
  7655. case 'vtc':
  7656. switch(record[3]) {
  7657. case 'nl': arr[R][C] = +record[4] ? true : false; break;
  7658. default: arr[R][C] = +record[4]; break;
  7659. }
  7660. if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
  7661. }
  7662. }
  7663. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  7664. return arr;
  7665. }
  7666. function eth_to_sheet(d, opts) { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
  7667. function eth_to_workbook(d, opts) { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }
  7668. var header = [
  7669. "socialcalc:version:1.5",
  7670. "MIME-Version: 1.0",
  7671. "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  7672. ].join("\n");
  7673. var sep = [
  7674. "--SocialCalcSpreadsheetControlSave",
  7675. "Content-type: text/plain; charset=UTF-8"
  7676. ].join("\n") + "\n";
  7677. /* TODO: the other parts */
  7678. var meta = [
  7679. "# SocialCalc Spreadsheet Control Save",
  7680. "part:sheet"
  7681. ].join("\n");
  7682. var end = "--SocialCalcSpreadsheetControlSave--";
  7683. function sheet_to_eth_data(ws) {
  7684. if(!ws || !ws['!ref']) return "";
  7685. var o = [], oo = [], cell, coord = "";
  7686. var r = decode_range(ws['!ref']);
  7687. var dense = Array.isArray(ws);
  7688. for(var R = r.s.r; R <= r.e.r; ++R) {
  7689. for(var C = r.s.c; C <= r.e.c; ++C) {
  7690. coord = encode_cell({r:R,c:C});
  7691. cell = dense ? (ws[R]||[])[C] : ws[coord];
  7692. if(!cell || cell.v == null || cell.t === 'z') continue;
  7693. oo = ["cell", coord, 't'];
  7694. switch(cell.t) {
  7695. case 's': case 'str': oo.push(encode(cell.v)); break;
  7696. case 'n':
  7697. if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
  7698. else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
  7699. break;
  7700. case 'b':
  7701. oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
  7702. oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
  7703. break;
  7704. case 'd':
  7705. var t = datenum(parseDate(cell.v));
  7706. oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
  7707. oo[5] = cell.w || SSF_format(cell.z || table_fmt[14], t);
  7708. break;
  7709. case 'e': continue;
  7710. }
  7711. o.push(oo.join(":"));
  7712. }
  7713. }
  7714. o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
  7715. o.push("valueformat:1:text-wiki");
  7716. //o.push("copiedfrom:" + ws['!ref']); // clipboard only
  7717. return o.join("\n");
  7718. }
  7719. function sheet_to_eth(ws) {
  7720. return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
  7721. // return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
  7722. }
  7723. return {
  7724. to_workbook: eth_to_workbook,
  7725. to_sheet: eth_to_sheet,
  7726. from_sheet: sheet_to_eth
  7727. };
  7728. })();
  7729. var PRN = (function() {
  7730. function set_text_arr(data, arr, R, C, o) {
  7731. if(o.raw) arr[R][C] = data;
  7732. else if(data === ""){/* empty */}
  7733. else if(data === 'TRUE') arr[R][C] = true;
  7734. else if(data === 'FALSE') arr[R][C] = false;
  7735. else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
  7736. else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
  7737. else arr[R][C] = data;
  7738. }
  7739. function prn_to_aoa_str(f, opts) {
  7740. var o = opts || {};
  7741. var arr = ([]);
  7742. if(!f || f.length === 0) return arr;
  7743. var lines = f.split(/[\r\n]/);
  7744. var L = lines.length - 1;
  7745. while(L >= 0 && lines[L].length === 0) --L;
  7746. var start = 10, idx = 0;
  7747. var R = 0;
  7748. for(; R <= L; ++R) {
  7749. idx = lines[R].indexOf(" ");
  7750. if(idx == -1) idx = lines[R].length; else idx++;
  7751. start = Math.max(start, idx);
  7752. }
  7753. for(R = 0; R <= L; ++R) {
  7754. arr[R] = [];
  7755. /* TODO: confirm that widths are always 10 */
  7756. var C = 0;
  7757. set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
  7758. for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
  7759. set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
  7760. }
  7761. if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
  7762. return arr;
  7763. }
  7764. // List of accepted CSV separators
  7765. var guess_seps = {
  7766. 0x2C: ',',
  7767. 0x09: "\t",
  7768. 0x3B: ';',
  7769. 0x7C: '|'
  7770. };
  7771. // CSV separator weights to be used in case of equal numbers
  7772. var guess_sep_weights = {
  7773. 0x2C: 3,
  7774. 0x09: 2,
  7775. 0x3B: 1,
  7776. 0x7C: 0
  7777. };
  7778. function guess_sep(str) {
  7779. var cnt = {}, instr = false, end = 0, cc = 0;
  7780. for(;end < str.length;++end) {
  7781. if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
  7782. else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
  7783. }
  7784. cc = [];
  7785. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  7786. cc.push([ cnt[end], end ]);
  7787. }
  7788. if ( !cc.length ) {
  7789. cnt = guess_sep_weights;
  7790. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  7791. cc.push([ cnt[end], end ]);
  7792. }
  7793. }
  7794. cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });
  7795. return guess_seps[cc.pop()[1]] || 0x2C;
  7796. }
  7797. function dsv_to_sheet_str(str, opts) {
  7798. var o = opts || {};
  7799. var sep = "";
  7800. if(DENSE != null && o.dense == null) o.dense = DENSE;
  7801. var ws = o.dense ? ([]) : ({});
  7802. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  7803. if(str.slice(0,4) == "sep=") {
  7804. // If the line ends in \r\n
  7805. if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
  7806. sep = str.charAt(4); str = str.slice(7);
  7807. }
  7808. // If line ends in \r OR \n
  7809. else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
  7810. sep = str.charAt(4); str = str.slice(6);
  7811. }
  7812. else sep = guess_sep(str.slice(0,1024));
  7813. }
  7814. else if(o && o.FS) sep = o.FS;
  7815. else sep = guess_sep(str.slice(0,1024));
  7816. var R = 0, C = 0, v = 0;
  7817. var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0, startcc=str.charCodeAt(0);
  7818. str = str.replace(/\r\n/mg, "\n");
  7819. var _re = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
  7820. function finish_cell() {
  7821. var s = str.slice(start, end);
  7822. var cell = ({});
  7823. if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
  7824. if(s.length === 0) cell.t = 'z';
  7825. else if(o.raw) { cell.t = 's'; cell.v = s; }
  7826. else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
  7827. else if(s.charCodeAt(0) == 0x3D) {
  7828. if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
  7829. else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
  7830. else { cell.t = 's'; cell.v = s; } }
  7831. else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
  7832. else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
  7833. else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
  7834. else if(!isNaN(fuzzydate(s).getDate()) || _re && s.match(_re)) {
  7835. cell.z = o.dateNF || table_fmt[14];
  7836. var k = 0;
  7837. if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; }
  7838. if(o.cellDates) { cell.t = 'd'; cell.v = parseDate(s, k); }
  7839. else { cell.t = 'n'; cell.v = datenum(parseDate(s, k)); }
  7840. if(o.cellText !== false) cell.w = SSF_format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
  7841. if(!o.cellNF) delete cell.z;
  7842. } else {
  7843. cell.t = 's';
  7844. cell.v = s;
  7845. }
  7846. if(cell.t == 'z'){}
  7847. else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
  7848. else ws[encode_cell({c:C,r:R})] = cell;
  7849. start = end+1; startcc = str.charCodeAt(start);
  7850. if(range.e.c < C) range.e.c = C;
  7851. if(range.e.r < R) range.e.r = R;
  7852. if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
  7853. }
  7854. outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
  7855. case 0x22: if(startcc === 0x22) instr = !instr; break;
  7856. case sepcc: case 0x0a: case 0x0d: if(!instr && finish_cell()) break outer; break;
  7857. default: break;
  7858. }
  7859. if(end - start > 0) finish_cell();
  7860. ws['!ref'] = encode_range(range);
  7861. return ws;
  7862. }
  7863. function prn_to_sheet_str(str, opts) {
  7864. if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
  7865. if(opts.FS) return dsv_to_sheet_str(str, opts);
  7866. if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
  7867. if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
  7868. return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
  7869. }
  7870. function prn_to_sheet(d, opts) {
  7871. var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
  7872. switch(opts.type) {
  7873. case 'base64': str = Base64_decode(d); break;
  7874. case 'binary': str = d; break;
  7875. case 'buffer':
  7876. if(opts.codepage == 65001) str = d.toString('utf8'); // TODO: test if buf
  7877. else if(opts.codepage && typeof $cptable !== 'undefined') str = $cptable.utils.decode(opts.codepage, d);
  7878. else str = has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d);
  7879. break;
  7880. case 'array': str = cc2str(d); break;
  7881. case 'string': str = d; break;
  7882. default: throw new Error("Unrecognized type " + opts.type);
  7883. }
  7884. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
  7885. else if(opts.type != 'string' && opts.type != 'buffer' && opts.codepage == 65001) str = utf8read(str);
  7886. else if((opts.type == 'binary') && typeof $cptable !== 'undefined' && opts.codepage) str = $cptable.utils.decode(opts.codepage, $cptable.utils.encode(28591,str));
  7887. if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
  7888. return prn_to_sheet_str(str, opts);
  7889. }
  7890. function prn_to_workbook(d, opts) { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }
  7891. function sheet_to_prn(ws) {
  7892. var o = [];
  7893. var r = safe_decode_range(ws['!ref']), cell;
  7894. var dense = Array.isArray(ws);
  7895. for(var R = r.s.r; R <= r.e.r; ++R) {
  7896. var oo = [];
  7897. for(var C = r.s.c; C <= r.e.c; ++C) {
  7898. var coord = encode_cell({r:R,c:C});
  7899. cell = dense ? (ws[R]||[])[C] : ws[coord];
  7900. if(!cell || cell.v == null) { oo.push(" "); continue; }
  7901. var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
  7902. while(w.length < 10) w += " ";
  7903. oo.push(w + (C === 0 ? " " : ""));
  7904. }
  7905. o.push(oo.join(""));
  7906. }
  7907. return o.join("\n");
  7908. }
  7909. return {
  7910. to_workbook: prn_to_workbook,
  7911. to_sheet: prn_to_sheet,
  7912. from_sheet: sheet_to_prn
  7913. };
  7914. })();
  7915. /* Excel defaults to SYLK but warns if data is not valid */
  7916. function read_wb_ID(d, opts) {
  7917. var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
  7918. try {
  7919. var out = SYLK.to_workbook(d, o);
  7920. o.WTF = OLD_WTF;
  7921. return out;
  7922. } catch(e) {
  7923. o.WTF = OLD_WTF;
  7924. if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
  7925. return PRN.to_workbook(d, opts);
  7926. }
  7927. }
  7928. var WK_ = (function() {
  7929. function lotushopper(data, cb, opts) {
  7930. if(!data) return;
  7931. prep_blob(data, data.l || 0);
  7932. var Enum = opts.Enum || WK1Enum;
  7933. while(data.l < data.length) {
  7934. var RT = data.read_shift(2);
  7935. var R = Enum[RT] || Enum[0xFFFF];
  7936. var length = data.read_shift(2);
  7937. var tgt = data.l + length;
  7938. var d = R.f && R.f(data, length, opts);
  7939. data.l = tgt;
  7940. if(cb(d, R, RT)) return;
  7941. }
  7942. }
  7943. function lotus_to_workbook(d, opts) {
  7944. switch(opts.type) {
  7945. case 'base64': return lotus_to_workbook_buf(s2a(Base64_decode(d)), opts);
  7946. case 'binary': return lotus_to_workbook_buf(s2a(d), opts);
  7947. case 'buffer':
  7948. case 'array': return lotus_to_workbook_buf(d, opts);
  7949. }
  7950. throw "Unsupported type " + opts.type;
  7951. }
  7952. function lotus_to_workbook_buf(d, opts) {
  7953. if(!d) return d;
  7954. var o = opts || {};
  7955. if(DENSE != null && o.dense == null) o.dense = DENSE;
  7956. var s = ((o.dense ? [] : {})), n = "Sheet1", next_n = "", sidx = 0;
  7957. var sheets = {}, snames = [], realnames = [];
  7958. var refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  7959. var sheetRows = o.sheetRows || 0;
  7960. if(d[2] == 0x00) {
  7961. if(d[3] == 0x08 || d[3] == 0x09) {
  7962. if(d.length >= 16 && d[14] == 0x05 && d[15] === 0x6c) throw new Error("Unsupported Works 3 for Mac file");
  7963. }
  7964. }
  7965. if(d[2] == 0x02) {
  7966. o.Enum = WK1Enum;
  7967. lotushopper(d, function(val, R, RT) { switch(RT) {
  7968. case 0x00: /* BOF */
  7969. o.vers = val;
  7970. if(val >= 0x1000) o.qpro = true;
  7971. break;
  7972. case 0x06: refguess = val; break; /* RANGE */
  7973. case 0xCC: if(val) next_n = val; break; /* SHEETNAMECS */
  7974. case 0xDE: next_n = val; break; /* SHEETNAMELP */
  7975. case 0x0F: /* LABEL */
  7976. case 0x33: /* STRING */
  7977. if(!o.qpro) val[1].v = val[1].v.slice(1);
  7978. /* falls through */
  7979. case 0x0D: /* INTEGER */
  7980. case 0x0E: /* NUMBER */
  7981. case 0x10: /* FORMULA */
  7982. /* TODO: actual translation of the format code */
  7983. if(RT == 0x0E && (val[2] & 0x70) == 0x70 && (val[2] & 0x0F) > 1 && (val[2] & 0x0F) < 15) {
  7984. val[1].z = o.dateNF || table_fmt[14];
  7985. if(o.cellDates) { val[1].t = 'd'; val[1].v = numdate(val[1].v); }
  7986. }
  7987. if(o.qpro) {
  7988. if(val[3] > sidx) {
  7989. s["!ref"] = encode_range(refguess);
  7990. sheets[n] = s;
  7991. snames.push(n);
  7992. s = (o.dense ? [] : {});
  7993. refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  7994. sidx = val[3]; n = next_n || "Sheet" + (sidx + 1); next_n = "";
  7995. }
  7996. }
  7997. var tmpcell = o.dense ? (s[val[0].r]||[])[val[0].c] : s[encode_cell(val[0])];
  7998. if(tmpcell) {
  7999. tmpcell.t = val[1].t; tmpcell.v = val[1].v;
  8000. if(val[1].z != null) tmpcell.z = val[1].z;
  8001. if(val[1].f != null) tmpcell.f = val[1].f;
  8002. break;
  8003. }
  8004. if(o.dense) {
  8005. if(!s[val[0].r]) s[val[0].r] = [];
  8006. s[val[0].r][val[0].c] = val[1];
  8007. } else s[encode_cell(val[0])] = val[1];
  8008. break;
  8009. default:
  8010. }}, o);
  8011. } else if(d[2] == 0x1A || d[2] == 0x0E) {
  8012. o.Enum = WK3Enum;
  8013. if(d[2] == 0x0E) { o.qpro = true; d.l = 0; }
  8014. lotushopper(d, function(val, R, RT) { switch(RT) {
  8015. case 0xCC: n = val; break; /* SHEETNAMECS */
  8016. case 0x16: /* LABEL16 */
  8017. val[1].v = val[1].v.slice(1);
  8018. /* falls through */
  8019. case 0x17: /* NUMBER17 */
  8020. case 0x18: /* NUMBER18 */
  8021. case 0x19: /* FORMULA19 */
  8022. case 0x25: /* NUMBER25 */
  8023. case 0x27: /* NUMBER27 */
  8024. case 0x28: /* FORMULA28 */
  8025. if(val[3] > sidx) {
  8026. s["!ref"] = encode_range(refguess);
  8027. sheets[n] = s;
  8028. snames.push(n);
  8029. s = (o.dense ? [] : {});
  8030. refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  8031. sidx = val[3]; n = "Sheet" + (sidx + 1);
  8032. }
  8033. if(sheetRows > 0 && val[0].r >= sheetRows) break;
  8034. if(o.dense) {
  8035. if(!s[val[0].r]) s[val[0].r] = [];
  8036. s[val[0].r][val[0].c] = val[1];
  8037. } else s[encode_cell(val[0])] = val[1];
  8038. if(refguess.e.c < val[0].c) refguess.e.c = val[0].c;
  8039. if(refguess.e.r < val[0].r) refguess.e.r = val[0].r;
  8040. break;
  8041. case 0x1B: /* XFORMAT */
  8042. if(val[0x36b0]) realnames[val[0x36b0][0]] = val[0x36b0][1];
  8043. break;
  8044. case 0x0601: /* SHEETINFOQP */
  8045. realnames[val[0]] = val[1]; if(val[0] == sidx) n = val[1]; break;
  8046. default: break;
  8047. }}, o);
  8048. } else throw new Error("Unrecognized LOTUS BOF " + d[2]);
  8049. s["!ref"] = encode_range(refguess);
  8050. sheets[next_n || n] = s;
  8051. snames.push(next_n || n);
  8052. if(!realnames.length) return { SheetNames: snames, Sheets: sheets };
  8053. var osheets = {}, rnames = [];
  8054. /* TODO: verify no collisions */
  8055. for(var i = 0; i < realnames.length; ++i) if(sheets[snames[i]]) {
  8056. rnames.push(realnames[i] || snames[i]);
  8057. osheets[realnames[i]] = sheets[realnames[i]] || sheets[snames[i]];
  8058. } else {
  8059. rnames.push(realnames[i]);
  8060. osheets[realnames[i]] = ({ "!ref": "A1" });
  8061. }
  8062. return { SheetNames: rnames, Sheets: osheets };
  8063. }
  8064. function sheet_to_wk1(ws, opts) {
  8065. var o = opts || {};
  8066. if(+o.codepage >= 0) set_cp(+o.codepage);
  8067. if(o.type == "string") throw new Error("Cannot write WK1 to JS string");
  8068. var ba = buf_array();
  8069. var range = safe_decode_range(ws["!ref"]);
  8070. var dense = Array.isArray(ws);
  8071. var cols = [];
  8072. write_biff_rec(ba, 0x00, write_BOF_WK1(0x0406));
  8073. write_biff_rec(ba, 0x06, write_RANGE(range));
  8074. var max_R = Math.min(range.e.r, 8191);
  8075. for(var R = range.s.r; R <= max_R; ++R) {
  8076. var rr = encode_row(R);
  8077. for(var C = range.s.c; C <= range.e.c; ++C) {
  8078. if(R === range.s.r) cols[C] = encode_col(C);
  8079. var ref = cols[C] + rr;
  8080. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  8081. if(!cell || cell.t == "z") continue;
  8082. /* TODO: formula records */
  8083. if(cell.t == "n") {
  8084. if((cell.v|0)==cell.v && cell.v >= -32768 && cell.v <= 32767) write_biff_rec(ba, 0x0d, write_INTEGER(R, C, cell.v));
  8085. else write_biff_rec(ba, 0x0e, write_NUMBER(R, C, cell.v));
  8086. } else {
  8087. var str = format_cell(cell);
  8088. write_biff_rec(ba, 0x0F, write_LABEL(R, C, str.slice(0, 239)));
  8089. }
  8090. }
  8091. }
  8092. write_biff_rec(ba, 0x01);
  8093. return ba.end();
  8094. }
  8095. function book_to_wk3(wb, opts) {
  8096. var o = opts || {};
  8097. if(+o.codepage >= 0) set_cp(+o.codepage);
  8098. if(o.type == "string") throw new Error("Cannot write WK3 to JS string");
  8099. var ba = buf_array();
  8100. write_biff_rec(ba, 0x00, write_BOF_WK3(wb));
  8101. 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++));
  8102. var wsidx = 0;
  8103. for(i = 0; i < wb.SheetNames.length; ++i) {
  8104. var ws = wb.Sheets[wb.SheetNames[i]];
  8105. if(!ws || !ws["!ref"]) continue;
  8106. var range = safe_decode_range(ws["!ref"]);
  8107. var dense = Array.isArray(ws);
  8108. var cols = [];
  8109. var max_R = Math.min(range.e.r, 8191);
  8110. for(var R = range.s.r; R <= max_R; ++R) {
  8111. var rr = encode_row(R);
  8112. for(var C = range.s.c; C <= range.e.c; ++C) {
  8113. if(R === range.s.r) cols[C] = encode_col(C);
  8114. var ref = cols[C] + rr;
  8115. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  8116. if(!cell || cell.t == "z") continue;
  8117. /* TODO: FORMULA19 NUMBER18 records */
  8118. if(cell.t == "n") {
  8119. write_biff_rec(ba, 0x17, write_NUMBER_17(R, C, wsidx, cell.v));
  8120. } else {
  8121. var str = format_cell(cell);
  8122. /* TODO: max len? */
  8123. write_biff_rec(ba, 0x16, write_LABEL_16(R, C, wsidx, str.slice(0, 239)));
  8124. }
  8125. }
  8126. }
  8127. ++wsidx;
  8128. }
  8129. write_biff_rec(ba, 0x01);
  8130. return ba.end();
  8131. }
  8132. function write_BOF_WK1(v) {
  8133. var out = new_buf(2);
  8134. out.write_shift(2, v);
  8135. return out;
  8136. }
  8137. function write_BOF_WK3(wb) {
  8138. var out = new_buf(26);
  8139. out.write_shift(2, 0x1000);
  8140. out.write_shift(2, 0x0004);
  8141. out.write_shift(4, 0x0000);
  8142. var rows = 0, cols = 0, wscnt = 0;
  8143. for(var i = 0; i < wb.SheetNames.length; ++i) {
  8144. var name = wb.SheetNames[i];
  8145. var ws = wb.Sheets[name];
  8146. if(!ws || !ws["!ref"]) continue;
  8147. ++wscnt;
  8148. var range = decode_range(ws["!ref"]);
  8149. if(rows < range.e.r) rows = range.e.r;
  8150. if(cols < range.e.c) cols = range.e.c;
  8151. }
  8152. if(rows > 8191) rows = 8191;
  8153. out.write_shift(2, rows);
  8154. out.write_shift(1, wscnt);
  8155. out.write_shift(1, cols);
  8156. out.write_shift(2, 0x00);
  8157. out.write_shift(2, 0x00);
  8158. out.write_shift(1, 0x01);
  8159. out.write_shift(1, 0x02);
  8160. out.write_shift(4, 0);
  8161. out.write_shift(4, 0);
  8162. return out;
  8163. }
  8164. function parse_RANGE(blob, length, opts) {
  8165. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  8166. if(length == 8 && opts.qpro) {
  8167. o.s.c = blob.read_shift(1);
  8168. blob.l++;
  8169. o.s.r = blob.read_shift(2);
  8170. o.e.c = blob.read_shift(1);
  8171. blob.l++;
  8172. o.e.r = blob.read_shift(2);
  8173. return o;
  8174. }
  8175. o.s.c = blob.read_shift(2);
  8176. o.s.r = blob.read_shift(2);
  8177. if(length == 12 && opts.qpro) blob.l += 2;
  8178. o.e.c = blob.read_shift(2);
  8179. o.e.r = blob.read_shift(2);
  8180. if(length == 12 && opts.qpro) blob.l += 2;
  8181. if(o.s.c == 0xFFFF) o.s.c = o.e.c = o.s.r = o.e.r = 0;
  8182. return o;
  8183. }
  8184. function write_RANGE(range) {
  8185. var out = new_buf(8);
  8186. out.write_shift(2, range.s.c);
  8187. out.write_shift(2, range.s.r);
  8188. out.write_shift(2, range.e.c);
  8189. out.write_shift(2, range.e.r);
  8190. return out;
  8191. }
  8192. function parse_cell(blob, length, opts) {
  8193. var o = [{c:0,r:0}, {t:'n',v:0}, 0, 0];
  8194. if(opts.qpro && opts.vers != 0x5120) {
  8195. o[0].c = blob.read_shift(1);
  8196. o[3] = blob.read_shift(1);
  8197. o[0].r = blob.read_shift(2);
  8198. blob.l+=2;
  8199. } else {
  8200. o[2] = blob.read_shift(1);
  8201. o[0].c = blob.read_shift(2); o[0].r = blob.read_shift(2);
  8202. }
  8203. return o;
  8204. }
  8205. function parse_LABEL(blob, length, opts) {
  8206. var tgt = blob.l + length;
  8207. var o = parse_cell(blob, length, opts);
  8208. o[1].t = 's';
  8209. if(opts.vers == 0x5120) {
  8210. blob.l++;
  8211. var len = blob.read_shift(1);
  8212. o[1].v = blob.read_shift(len, 'utf8');
  8213. return o;
  8214. }
  8215. if(opts.qpro) blob.l++;
  8216. o[1].v = blob.read_shift(tgt - blob.l, 'cstr');
  8217. return o;
  8218. }
  8219. function write_LABEL(R, C, s) {
  8220. /* TODO: encoding */
  8221. var o = new_buf(7 + s.length);
  8222. o.write_shift(1, 0xFF);
  8223. o.write_shift(2, C);
  8224. o.write_shift(2, R);
  8225. o.write_shift(1, 0x27); // ??
  8226. for(var i = 0; i < o.length; ++i) {
  8227. var cc = s.charCodeAt(i);
  8228. o.write_shift(1, cc >= 0x80 ? 0x5F : cc);
  8229. }
  8230. o.write_shift(1, 0);
  8231. return o;
  8232. }
  8233. function parse_INTEGER(blob, length, opts) {
  8234. var o = parse_cell(blob, length, opts);
  8235. o[1].v = blob.read_shift(2, 'i');
  8236. return o;
  8237. }
  8238. function write_INTEGER(R, C, v) {
  8239. var o = new_buf(7);
  8240. o.write_shift(1, 0xFF);
  8241. o.write_shift(2, C);
  8242. o.write_shift(2, R);
  8243. o.write_shift(2, v, 'i');
  8244. return o;
  8245. }
  8246. function parse_NUMBER(blob, length, opts) {
  8247. var o = parse_cell(blob, length, opts);
  8248. o[1].v = blob.read_shift(8, 'f');
  8249. return o;
  8250. }
  8251. function write_NUMBER(R, C, v) {
  8252. var o = new_buf(13);
  8253. o.write_shift(1, 0xFF);
  8254. o.write_shift(2, C);
  8255. o.write_shift(2, R);
  8256. o.write_shift(8, v, 'f');
  8257. return o;
  8258. }
  8259. function parse_FORMULA(blob, length, opts) {
  8260. var tgt = blob.l + length;
  8261. var o = parse_cell(blob, length, opts);
  8262. /* TODO: formula */
  8263. o[1].v = blob.read_shift(8, 'f');
  8264. if(opts.qpro) blob.l = tgt;
  8265. else {
  8266. var flen = blob.read_shift(2);
  8267. wk1_fmla_to_csf(blob.slice(blob.l, blob.l + flen), o);
  8268. blob.l += flen;
  8269. }
  8270. return o;
  8271. }
  8272. function wk1_parse_rc(B, V, col) {
  8273. var rel = V & 0x8000;
  8274. V &= ~0x8000;
  8275. V = (rel ? B : 0) + ((V >= 0x2000) ? V - 0x4000 : V);
  8276. return (rel ? "" : "$") + (col ? encode_col(V) : encode_row(V));
  8277. }
  8278. /* var oprec = [
  8279. 8, 8, 8, 8, 8, 8, 8, 8, 6, 4, 4, 5, 5, 7, 3, 3,
  8280. 3, 3, 3, 3, 1, 1, 2, 6, 8, 8, 8, 8, 8, 8, 8, 8
  8281. ]; */
  8282. /* TODO: flesh out */
  8283. var FuncTab = {
  8284. 0x33: ["FALSE", 0],
  8285. 0x34: ["TRUE", 0],
  8286. 0x46: ["LEN", 1],
  8287. 0x50: ["SUM", 69],
  8288. 0x51: ["AVERAGEA", 69],
  8289. 0x52: ["COUNTA", 69],
  8290. 0x53: ["MINA", 69],
  8291. 0x54: ["MAXA", 69],
  8292. 0x6F: ["T", 1]
  8293. };
  8294. var BinOpTab = [
  8295. "", "", "", "", "", "", "", "", // eslint-disable-line no-mixed-spaces-and-tabs
  8296. "", "+", "-", "*", "/", "^", "=", "<>", // eslint-disable-line no-mixed-spaces-and-tabs
  8297. "<=", ">=", "<", ">", "", "", "", "", // eslint-disable-line no-mixed-spaces-and-tabs
  8298. "&", "", "", "", "", "", "", "" // eslint-disable-line no-mixed-spaces-and-tabs
  8299. ];
  8300. function wk1_fmla_to_csf(blob, o) {
  8301. prep_blob(blob, 0);
  8302. var out = [], argc = 0, R = "", C = "", argL = "", argR = "";
  8303. while(blob.l < blob.length) {
  8304. var cc = blob[blob.l++];
  8305. switch(cc) {
  8306. case 0x00: out.push(blob.read_shift(8, 'f')); break;
  8307. case 0x01: {
  8308. C = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
  8309. R = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
  8310. out.push(C + R);
  8311. } break;
  8312. case 0x02: {
  8313. var c = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
  8314. var r = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
  8315. C = wk1_parse_rc(o[0].c, blob.read_shift(2), true);
  8316. R = wk1_parse_rc(o[0].r, blob.read_shift(2), false);
  8317. out.push(c + r + ":" + C + R);
  8318. } break;
  8319. case 0x03:
  8320. if(blob.l < blob.length) { console.error("WK1 premature formula end"); return; }
  8321. break;
  8322. case 0x04: out.push("(" + out.pop() + ")"); break;
  8323. case 0x05: out.push(blob.read_shift(2)); break;
  8324. case 0x06: {
  8325. /* TODO: text encoding */
  8326. var Z = ""; while((cc = blob[blob.l++])) Z += String.fromCharCode(cc);
  8327. out.push('"' + Z.replace(/"/g, '""') + '"');
  8328. } break;
  8329. case 0x08: out.push("-" + out.pop()); break;
  8330. case 0x17: out.push("+" + out.pop()); break;
  8331. case 0x16: out.push("NOT(" + out.pop() + ")"); break;
  8332. case 0x14: case 0x15: {
  8333. argR = out.pop(); argL = out.pop();
  8334. out.push(["AND", "OR"][cc - 0x14] + "(" + argL + "," + argR + ")");
  8335. } break;
  8336. default:
  8337. if(cc < 0x20 && BinOpTab[cc]) {
  8338. argR = out.pop(); argL = out.pop();
  8339. out.push(argL + BinOpTab[cc] + argR);
  8340. } else if(FuncTab[cc]) {
  8341. argc = FuncTab[cc][1];
  8342. if(argc == 69) argc = blob[blob.l++];
  8343. if(argc > out.length) { console.error("WK1 bad formula parse 0x" + cc.toString(16) + ":|" + out.join("|") + "|"); return; }
  8344. var args = out.slice(-argc);
  8345. out.length -= argc;
  8346. out.push(FuncTab[cc][0] + "(" + args.join(",") + ")");
  8347. }
  8348. else if(cc <= 0x07) return console.error("WK1 invalid opcode " + cc.toString(16));
  8349. else if(cc <= 0x18) return console.error("WK1 unsupported op " + cc.toString(16));
  8350. else if(cc <= 0x1E) return console.error("WK1 invalid opcode " + cc.toString(16));
  8351. else if(cc <= 0x73) return console.error("WK1 unsupported function opcode " + cc.toString(16));
  8352. // possible future functions ??
  8353. else return console.error("WK1 unrecognized opcode " + cc.toString(16));
  8354. }
  8355. }
  8356. if(out.length == 1) o[1].f = "" + out[0];
  8357. else console.error("WK1 bad formula parse |" + out.join("|") + "|");
  8358. }
  8359. function parse_cell_3(blob) {
  8360. var o = [{c:0,r:0}, {t:'n',v:0}, 0];
  8361. o[0].r = blob.read_shift(2); o[3] = blob[blob.l++]; o[0].c = blob[blob.l++];
  8362. return o;
  8363. }
  8364. function parse_LABEL_16(blob, length) {
  8365. var o = parse_cell_3(blob, length);
  8366. o[1].t = 's';
  8367. o[1].v = blob.read_shift(length - 4, 'cstr');
  8368. return o;
  8369. }
  8370. function write_LABEL_16(R, C, wsidx, s) {
  8371. /* TODO: encoding */
  8372. var o = new_buf(6 + s.length);
  8373. o.write_shift(2, R);
  8374. o.write_shift(1, wsidx);
  8375. o.write_shift(1, C);
  8376. o.write_shift(1, 0x27);
  8377. for(var i = 0; i < s.length; ++i) {
  8378. var cc = s.charCodeAt(i);
  8379. o.write_shift(1, cc >= 0x80 ? 0x5F : cc);
  8380. }
  8381. o.write_shift(1, 0);
  8382. return o;
  8383. }
  8384. function parse_NUMBER_18(blob, length) {
  8385. var o = parse_cell_3(blob, length);
  8386. o[1].v = blob.read_shift(2);
  8387. var v = o[1].v >> 1;
  8388. if(o[1].v & 0x1) {
  8389. switch(v & 0x07) {
  8390. case 0: v = (v >> 3) * 5000; break;
  8391. case 1: v = (v >> 3) * 500; break;
  8392. case 2: v = (v >> 3) / 20; break;
  8393. case 3: v = (v >> 3) / 200; break;
  8394. case 4: v = (v >> 3) / 2000; break;
  8395. case 5: v = (v >> 3) / 20000; break;
  8396. case 6: v = (v >> 3) / 16; break;
  8397. case 7: v = (v >> 3) / 64; break;
  8398. }
  8399. }
  8400. o[1].v = v;
  8401. return o;
  8402. }
  8403. function parse_NUMBER_17(blob, length) {
  8404. var o = parse_cell_3(blob, length);
  8405. var v1 = blob.read_shift(4);
  8406. var v2 = blob.read_shift(4);
  8407. var e = blob.read_shift(2);
  8408. if(e == 0xFFFF) {
  8409. if(v1 === 0 && v2 === 0xC0000000) { o[1].t = "e"; o[1].v = 0x0F; } // ERR -> #VALUE!
  8410. else if(v1 === 0 && v2 === 0xD0000000) { o[1].t = "e"; o[1].v = 0x2A; } // NA -> #N/A
  8411. else o[1].v = 0;
  8412. return o;
  8413. }
  8414. var s = e & 0x8000; e = (e&0x7FFF) - 16446;
  8415. o[1].v = (1 - s*2) * (v2 * Math.pow(2, e+32) + v1 * Math.pow(2, e));
  8416. return o;
  8417. }
  8418. function write_NUMBER_17(R, C, wsidx, v) {
  8419. var o = new_buf(14);
  8420. o.write_shift(2, R);
  8421. o.write_shift(1, wsidx);
  8422. o.write_shift(1, C);
  8423. if(v == 0) {
  8424. o.write_shift(4, 0);
  8425. o.write_shift(4, 0);
  8426. o.write_shift(2, 0xFFFF);
  8427. return o;
  8428. }
  8429. var s = 0, e = 0, v1 = 0, v2 = 0;
  8430. if(v < 0) { s = 1; v = -v; }
  8431. e = Math.log2(v) | 0;
  8432. v /= Math.pow(2, e-31);
  8433. v2 = (v)>>>0;
  8434. if((v2&0x80000000) == 0) { v/=2; ++e; v2 = v >>> 0; }
  8435. v -= v2;
  8436. v2 |= 0x80000000;
  8437. v2 >>>= 0;
  8438. v *= Math.pow(2, 32);
  8439. v1 = v>>>0;
  8440. o.write_shift(4, v1);
  8441. o.write_shift(4, v2);
  8442. e += 0x3FFF + (s ? 0x8000 : 0);
  8443. o.write_shift(2, e);
  8444. return o;
  8445. }
  8446. function parse_FORMULA_19(blob, length) {
  8447. var o = parse_NUMBER_17(blob, 14);
  8448. blob.l += length - 14; /* TODO: WK3 formula */
  8449. return o;
  8450. }
  8451. function parse_NUMBER_25(blob, length) {
  8452. var o = parse_cell_3(blob, length);
  8453. var v1 = blob.read_shift(4);
  8454. o[1].v = v1 >> 6;
  8455. return o;
  8456. }
  8457. function parse_NUMBER_27(blob, length) {
  8458. var o = parse_cell_3(blob, length);
  8459. var v1 = blob.read_shift(8,'f');
  8460. o[1].v = v1;
  8461. return o;
  8462. }
  8463. function parse_FORMULA_28(blob, length) {
  8464. var o = parse_NUMBER_27(blob, 14);
  8465. blob.l += length - 10; /* TODO: formula */
  8466. return o;
  8467. }
  8468. function parse_SHEETNAMECS(blob, length) {
  8469. return blob[blob.l + length - 1] == 0 ? blob.read_shift(length, 'cstr') : "";
  8470. }
  8471. function parse_SHEETNAMELP(blob, length) {
  8472. var len = blob[blob.l++];
  8473. if(len > length - 1) len = length - 1;
  8474. var o = ""; while(o.length < len) o += String.fromCharCode(blob[blob.l++]);
  8475. return o;
  8476. }
  8477. function parse_SHEETINFOQP(blob, length, opts) {
  8478. if(!opts.qpro || length < 21) return;
  8479. var id = blob.read_shift(1);
  8480. blob.l += 17;
  8481. blob.l += 1; //var len = blob.read_shift(1);
  8482. blob.l += 2;
  8483. var nm = blob.read_shift(length - 21, 'cstr');
  8484. return [id, nm];
  8485. }
  8486. function parse_XFORMAT(blob, length) {
  8487. var o = {}, tgt = blob.l + length;
  8488. while(blob.l < tgt) {
  8489. var dt = blob.read_shift(2);
  8490. if(dt == 0x36b0) {
  8491. o[dt] = [0, ""];
  8492. o[dt][0] = blob.read_shift(2);
  8493. while(blob[blob.l]) { o[dt][1] += String.fromCharCode(blob[blob.l]); blob.l++; } blob.l++;
  8494. }
  8495. // TODO: 0x3a99 ??
  8496. }
  8497. return o;
  8498. }
  8499. function write_XFORMAT_SHEETNAME(name, wsidx) {
  8500. var out = new_buf(5 + name.length);
  8501. out.write_shift(2, 0x36b0);
  8502. out.write_shift(2, wsidx);
  8503. for(var i = 0; i < name.length; ++i) {
  8504. var cc = name.charCodeAt(i);
  8505. out[out.l++] = cc > 0x7F ? 0x5F : cc;
  8506. }
  8507. out[out.l++] = 0;
  8508. return out;
  8509. }
  8510. var WK1Enum = {
  8511. 0x0000: { n:"BOF", f:parseuint16 },
  8512. 0x0001: { n:"EOF" },
  8513. 0x0002: { n:"CALCMODE" },
  8514. 0x0003: { n:"CALCORDER" },
  8515. 0x0004: { n:"SPLIT" },
  8516. 0x0005: { n:"SYNC" },
  8517. 0x0006: { n:"RANGE", f:parse_RANGE },
  8518. 0x0007: { n:"WINDOW1" },
  8519. 0x0008: { n:"COLW1" },
  8520. 0x0009: { n:"WINTWO" },
  8521. 0x000A: { n:"COLW2" },
  8522. 0x000B: { n:"NAME" },
  8523. 0x000C: { n:"BLANK" },
  8524. 0x000D: { n:"INTEGER", f:parse_INTEGER },
  8525. 0x000E: { n:"NUMBER", f:parse_NUMBER },
  8526. 0x000F: { n:"LABEL", f:parse_LABEL },
  8527. 0x0010: { n:"FORMULA", f:parse_FORMULA },
  8528. 0x0018: { n:"TABLE" },
  8529. 0x0019: { n:"ORANGE" },
  8530. 0x001A: { n:"PRANGE" },
  8531. 0x001B: { n:"SRANGE" },
  8532. 0x001C: { n:"FRANGE" },
  8533. 0x001D: { n:"KRANGE1" },
  8534. 0x0020: { n:"HRANGE" },
  8535. 0x0023: { n:"KRANGE2" },
  8536. 0x0024: { n:"PROTEC" },
  8537. 0x0025: { n:"FOOTER" },
  8538. 0x0026: { n:"HEADER" },
  8539. 0x0027: { n:"SETUP" },
  8540. 0x0028: { n:"MARGINS" },
  8541. 0x0029: { n:"LABELFMT" },
  8542. 0x002A: { n:"TITLES" },
  8543. 0x002B: { n:"SHEETJS" },
  8544. 0x002D: { n:"GRAPH" },
  8545. 0x002E: { n:"NGRAPH" },
  8546. 0x002F: { n:"CALCCOUNT" },
  8547. 0x0030: { n:"UNFORMATTED" },
  8548. 0x0031: { n:"CURSORW12" },
  8549. 0x0032: { n:"WINDOW" },
  8550. 0x0033: { n:"STRING", f:parse_LABEL },
  8551. 0x0037: { n:"PASSWORD" },
  8552. 0x0038: { n:"LOCKED" },
  8553. 0x003C: { n:"QUERY" },
  8554. 0x003D: { n:"QUERYNAME" },
  8555. 0x003E: { n:"PRINT" },
  8556. 0x003F: { n:"PRINTNAME" },
  8557. 0x0040: { n:"GRAPH2" },
  8558. 0x0041: { n:"GRAPHNAME" },
  8559. 0x0042: { n:"ZOOM" },
  8560. 0x0043: { n:"SYMSPLIT" },
  8561. 0x0044: { n:"NSROWS" },
  8562. 0x0045: { n:"NSCOLS" },
  8563. 0x0046: { n:"RULER" },
  8564. 0x0047: { n:"NNAME" },
  8565. 0x0048: { n:"ACOMM" },
  8566. 0x0049: { n:"AMACRO" },
  8567. 0x004A: { n:"PARSE" },
  8568. 0x0066: { n:"PRANGES??" },
  8569. 0x0067: { n:"RRANGES??" },
  8570. 0x0068: { n:"FNAME??" },
  8571. 0x0069: { n:"MRANGES??" },
  8572. 0x00CC: { n:"SHEETNAMECS", f:parse_SHEETNAMECS },
  8573. 0x00DE: { n:"SHEETNAMELP", f:parse_SHEETNAMELP },
  8574. 0xFFFF: { n:"" }
  8575. };
  8576. var WK3Enum = {
  8577. 0x0000: { n:"BOF" },
  8578. 0x0001: { n:"EOF" },
  8579. 0x0002: { n:"PASSWORD" },
  8580. 0x0003: { n:"CALCSET" },
  8581. 0x0004: { n:"WINDOWSET" },
  8582. 0x0005: { n:"SHEETCELLPTR" },
  8583. 0x0006: { n:"SHEETLAYOUT" },
  8584. 0x0007: { n:"COLUMNWIDTH" },
  8585. 0x0008: { n:"HIDDENCOLUMN" },
  8586. 0x0009: { n:"USERRANGE" },
  8587. 0x000A: { n:"SYSTEMRANGE" },
  8588. 0x000B: { n:"ZEROFORCE" },
  8589. 0x000C: { n:"SORTKEYDIR" },
  8590. 0x000D: { n:"FILESEAL" },
  8591. 0x000E: { n:"DATAFILLNUMS" },
  8592. 0x000F: { n:"PRINTMAIN" },
  8593. 0x0010: { n:"PRINTSTRING" },
  8594. 0x0011: { n:"GRAPHMAIN" },
  8595. 0x0012: { n:"GRAPHSTRING" },
  8596. 0x0013: { n:"??" },
  8597. 0x0014: { n:"ERRCELL" },
  8598. 0x0015: { n:"NACELL" },
  8599. 0x0016: { n:"LABEL16", f:parse_LABEL_16},
  8600. 0x0017: { n:"NUMBER17", f:parse_NUMBER_17 },
  8601. 0x0018: { n:"NUMBER18", f:parse_NUMBER_18 },
  8602. 0x0019: { n:"FORMULA19", f:parse_FORMULA_19},
  8603. 0x001A: { n:"FORMULA1A" },
  8604. 0x001B: { n:"XFORMAT", f:parse_XFORMAT },
  8605. 0x001C: { n:"DTLABELMISC" },
  8606. 0x001D: { n:"DTLABELCELL" },
  8607. 0x001E: { n:"GRAPHWINDOW" },
  8608. 0x001F: { n:"CPA" },
  8609. 0x0020: { n:"LPLAUTO" },
  8610. 0x0021: { n:"QUERY" },
  8611. 0x0022: { n:"HIDDENSHEET" },
  8612. 0x0023: { n:"??" },
  8613. 0x0025: { n:"NUMBER25", f:parse_NUMBER_25 },
  8614. 0x0026: { n:"??" },
  8615. 0x0027: { n:"NUMBER27", f:parse_NUMBER_27 },
  8616. 0x0028: { n:"FORMULA28", f:parse_FORMULA_28 },
  8617. 0x008E: { n:"??" },
  8618. 0x0093: { n:"??" },
  8619. 0x0096: { n:"??" },
  8620. 0x0097: { n:"??" },
  8621. 0x0098: { n:"??" },
  8622. 0x0099: { n:"??" },
  8623. 0x009A: { n:"??" },
  8624. 0x009B: { n:"??" },
  8625. 0x009C: { n:"??" },
  8626. 0x00A3: { n:"??" },
  8627. 0x00AE: { n:"??" },
  8628. 0x00AF: { n:"??" },
  8629. 0x00B0: { n:"??" },
  8630. 0x00B1: { n:"??" },
  8631. 0x00B8: { n:"??" },
  8632. 0x00B9: { n:"??" },
  8633. 0x00BA: { n:"??" },
  8634. 0x00BB: { n:"??" },
  8635. 0x00BC: { n:"??" },
  8636. 0x00C3: { n:"??" },
  8637. 0x00C9: { n:"??" },
  8638. 0x00CC: { n:"SHEETNAMECS", f:parse_SHEETNAMECS },
  8639. 0x00CD: { n:"??" },
  8640. 0x00CE: { n:"??" },
  8641. 0x00CF: { n:"??" },
  8642. 0x00D0: { n:"??" },
  8643. 0x0100: { n:"??" },
  8644. 0x0103: { n:"??" },
  8645. 0x0104: { n:"??" },
  8646. 0x0105: { n:"??" },
  8647. 0x0106: { n:"??" },
  8648. 0x0107: { n:"??" },
  8649. 0x0109: { n:"??" },
  8650. 0x010A: { n:"??" },
  8651. 0x010B: { n:"??" },
  8652. 0x010C: { n:"??" },
  8653. 0x010E: { n:"??" },
  8654. 0x010F: { n:"??" },
  8655. 0x0180: { n:"??" },
  8656. 0x0185: { n:"??" },
  8657. 0x0186: { n:"??" },
  8658. 0x0189: { n:"??" },
  8659. 0x018C: { n:"??" },
  8660. 0x0200: { n:"??" },
  8661. 0x0202: { n:"??" },
  8662. 0x0201: { n:"??" },
  8663. 0x0204: { n:"??" },
  8664. 0x0205: { n:"??" },
  8665. 0x0280: { n:"??" },
  8666. 0x0281: { n:"??" },
  8667. 0x0282: { n:"??" },
  8668. 0x0283: { n:"??" },
  8669. 0x0284: { n:"??" },
  8670. 0x0285: { n:"??" },
  8671. 0x0286: { n:"??" },
  8672. 0x0287: { n:"??" },
  8673. 0x0288: { n:"??" },
  8674. 0x0292: { n:"??" },
  8675. 0x0293: { n:"??" },
  8676. 0x0294: { n:"??" },
  8677. 0x0295: { n:"??" },
  8678. 0x0296: { n:"??" },
  8679. 0x0299: { n:"??" },
  8680. 0x029A: { n:"??" },
  8681. 0x0300: { n:"??" },
  8682. 0x0304: { n:"??" },
  8683. 0x0601: { n:"SHEETINFOQP", f:parse_SHEETINFOQP },
  8684. 0x0640: { n:"??" },
  8685. 0x0642: { n:"??" },
  8686. 0x0701: { n:"??" },
  8687. 0x0702: { n:"??" },
  8688. 0x0703: { n:"??" },
  8689. 0x0704: { n:"??" },
  8690. 0x0780: { n:"??" },
  8691. 0x0800: { n:"??" },
  8692. 0x0801: { n:"??" },
  8693. 0x0804: { n:"??" },
  8694. 0x0A80: { n:"??" },
  8695. 0x2AF6: { n:"??" },
  8696. 0x3231: { n:"??" },
  8697. 0x6E49: { n:"??" },
  8698. 0x6F44: { n:"??" },
  8699. 0xFFFF: { n:"" }
  8700. };
  8701. return {
  8702. sheet_to_wk1: sheet_to_wk1,
  8703. book_to_wk3: book_to_wk3,
  8704. to_workbook: lotus_to_workbook
  8705. };
  8706. })();
  8707. /* 18.4.7 rPr CT_RPrElt */
  8708. function parse_rpr(rpr) {
  8709. var font = {}, m = rpr.match(tagregex), i = 0;
  8710. var pass = false;
  8711. if(m) for(;i!=m.length; ++i) {
  8712. var y = parsexmltag(m[i]);
  8713. switch(y[0].replace(/\w*:/g,"")) {
  8714. /* 18.8.12 condense CT_BooleanProperty */
  8715. /* ** not required . */
  8716. case '<condense': break;
  8717. /* 18.8.17 extend CT_BooleanProperty */
  8718. /* ** not required . */
  8719. case '<extend': break;
  8720. /* 18.8.36 shadow CT_BooleanProperty */
  8721. /* ** not required . */
  8722. case '<shadow':
  8723. if(!y.val) break;
  8724. /* falls through */
  8725. case '<shadow>':
  8726. case '<shadow/>': font.shadow = 1; break;
  8727. case '</shadow>': break;
  8728. /* 18.4.1 charset CT_IntProperty TODO */
  8729. case '<charset':
  8730. if(y.val == '1') break;
  8731. font.cp = CS2CP[parseInt(y.val, 10)];
  8732. break;
  8733. /* 18.4.2 outline CT_BooleanProperty TODO */
  8734. case '<outline':
  8735. if(!y.val) break;
  8736. /* falls through */
  8737. case '<outline>':
  8738. case '<outline/>': font.outline = 1; break;
  8739. case '</outline>': break;
  8740. /* 18.4.5 rFont CT_FontName */
  8741. case '<rFont': font.name = y.val; break;
  8742. /* 18.4.11 sz CT_FontSize */
  8743. case '<sz': font.sz = y.val; break;
  8744. /* 18.4.10 strike CT_BooleanProperty */
  8745. case '<strike':
  8746. if(!y.val) break;
  8747. /* falls through */
  8748. case '<strike>':
  8749. case '<strike/>': font.strike = 1; break;
  8750. case '</strike>': break;
  8751. /* 18.4.13 u CT_UnderlineProperty */
  8752. case '<u':
  8753. if(!y.val) break;
  8754. switch(y.val) {
  8755. case 'double': font.uval = "double"; break;
  8756. case 'singleAccounting': font.uval = "single-accounting"; break;
  8757. case 'doubleAccounting': font.uval = "double-accounting"; break;
  8758. }
  8759. /* falls through */
  8760. case '<u>':
  8761. case '<u/>': font.u = 1; break;
  8762. case '</u>': break;
  8763. /* 18.8.2 b */
  8764. case '<b':
  8765. if(y.val == '0') break;
  8766. /* falls through */
  8767. case '<b>':
  8768. case '<b/>': font.b = 1; break;
  8769. case '</b>': break;
  8770. /* 18.8.26 i */
  8771. case '<i':
  8772. if(y.val == '0') break;
  8773. /* falls through */
  8774. case '<i>':
  8775. case '<i/>': font.i = 1; break;
  8776. case '</i>': break;
  8777. /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
  8778. case '<color':
  8779. if(y.rgb) font.color = y.rgb.slice(2,8);
  8780. break;
  8781. case '<color>': case '<color/>': case '</color>': break;
  8782. /* 18.8.18 family ST_FontFamily */
  8783. case '<family': font.family = y.val; break;
  8784. case '<family>': case '<family/>': case '</family>': break;
  8785. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
  8786. case '<vertAlign': font.valign = y.val; break;
  8787. case '<vertAlign>': case '<vertAlign/>': case '</vertAlign>': break;
  8788. /* 18.8.35 scheme CT_FontScheme TODO */
  8789. case '<scheme': break;
  8790. case '<scheme>': case '<scheme/>': case '</scheme>': break;
  8791. /* 18.2.10 extLst CT_ExtensionList ? */
  8792. case '<extLst': case '<extLst>': case '</extLst>': break;
  8793. case '<ext': pass = true; break;
  8794. case '</ext>': pass = false; break;
  8795. default:
  8796. if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
  8797. }
  8798. }
  8799. return font;
  8800. }
  8801. var parse_rs = (function() {
  8802. var tregex = matchtag("t"), rpregex = matchtag("rPr");
  8803. /* 18.4.4 r CT_RElt */
  8804. function parse_r(r) {
  8805. /* 18.4.12 t ST_Xstring */
  8806. var t = r.match(tregex)/*, cp = 65001*/;
  8807. if(!t) return {t:"s", v:""};
  8808. var o = ({t:'s', v:unescapexml(t[1])});
  8809. var rpr = r.match(rpregex);
  8810. if(rpr) o.s = parse_rpr(rpr[1]);
  8811. return o;
  8812. }
  8813. var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  8814. return function parse_rs(rs) {
  8815. return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
  8816. };
  8817. })();
  8818. /* Parse a list of <r> tags */
  8819. var rs_to_html = (function parse_rs_factory() {
  8820. var nlregex = /(\r\n|\n)/g;
  8821. function parse_rpr2(font, intro, outro) {
  8822. var style = [];
  8823. if(font.u) style.push("text-decoration: underline;");
  8824. if(font.uval) style.push("text-underline-style:" + font.uval + ";");
  8825. if(font.sz) style.push("font-size:" + font.sz + "pt;");
  8826. if(font.outline) style.push("text-effect: outline;");
  8827. if(font.shadow) style.push("text-shadow: auto;");
  8828. intro.push('<span style="' + style.join("") + '">');
  8829. if(font.b) { intro.push("<b>"); outro.push("</b>"); }
  8830. if(font.i) { intro.push("<i>"); outro.push("</i>"); }
  8831. if(font.strike) { intro.push("<s>"); outro.push("</s>"); }
  8832. var align = font.valign || "";
  8833. if(align == "superscript" || align == "super") align = "sup";
  8834. else if(align == "subscript") align = "sub";
  8835. if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }
  8836. outro.push("</span>");
  8837. return font;
  8838. }
  8839. /* 18.4.4 r CT_RElt */
  8840. function r_to_html(r) {
  8841. var terms = [[],r.v,[]];
  8842. if(!r.v) return "";
  8843. if(r.s) parse_rpr2(r.s, terms[0], terms[2]);
  8844. return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
  8845. }
  8846. return function parse_rs(rs) {
  8847. return rs.map(r_to_html).join("");
  8848. };
  8849. })();
  8850. /* 18.4.8 si CT_Rst */
  8851. var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
  8852. var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
  8853. function parse_si(x, opts) {
  8854. var html = opts ? opts.cellHTML : true;
  8855. var z = {};
  8856. if(!x) return { t: "" };
  8857. //var y;
  8858. /* 18.4.12 t ST_Xstring (Plaintext String) */
  8859. // TODO: is whitespace actually valid here?
  8860. if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
  8861. z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""));
  8862. z.r = utf8read(x);
  8863. if(html) z.h = escapehtml(z.t);
  8864. }
  8865. /* 18.4.4 r CT_RElt (Rich Text Run) */
  8866. else if((/*y = */x.match(sirregex))) {
  8867. z.r = utf8read(x);
  8868. z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")));
  8869. if(html) z.h = rs_to_html(parse_rs(z.r));
  8870. }
  8871. /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
  8872. /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
  8873. return z;
  8874. }
  8875. /* 18.4 Shared String Table */
  8876. var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
  8877. var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
  8878. var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
  8879. function parse_sst_xml(data, opts) {
  8880. var s = ([]), ss = "";
  8881. if(!data) return s;
  8882. /* 18.4.9 sst CT_Sst */
  8883. var sst = data.match(sstr0);
  8884. if(sst) {
  8885. ss = sst[2].replace(sstr1,"").split(sstr2);
  8886. for(var i = 0; i != ss.length; ++i) {
  8887. var o = parse_si(ss[i].trim(), opts);
  8888. if(o != null) s[s.length] = o;
  8889. }
  8890. sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
  8891. }
  8892. return s;
  8893. }
  8894. var straywsregex = /^\s|\s$|[\t\n\r]/;
  8895. function write_sst_xml(sst, opts) {
  8896. if(!opts.bookSST) return "";
  8897. var o = [XML_HEADER];
  8898. o[o.length] = (writextag('sst', null, {
  8899. xmlns: XMLNS_main[0],
  8900. count: sst.Count,
  8901. uniqueCount: sst.Unique
  8902. }));
  8903. for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
  8904. var s = sst[i];
  8905. var sitag = "<si>";
  8906. if(s.r) sitag += s.r;
  8907. else {
  8908. sitag += "<t";
  8909. if(!s.t) s.t = "";
  8910. if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
  8911. sitag += ">" + escapexml(s.t) + "</t>";
  8912. }
  8913. sitag += "</si>";
  8914. o[o.length] = (sitag);
  8915. }
  8916. if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
  8917. return o.join("");
  8918. }
  8919. /* [MS-XLSB] 2.4.221 BrtBeginSst */
  8920. function parse_BrtBeginSst(data) {
  8921. return [data.read_shift(4), data.read_shift(4)];
  8922. }
  8923. /* [MS-XLSB] 2.1.7.45 Shared Strings */
  8924. function parse_sst_bin(data, opts) {
  8925. var s = ([]);
  8926. var pass = false;
  8927. recordhopper(data, function hopper_sst(val, R, RT) {
  8928. switch(RT) {
  8929. case 0x009F: /* BrtBeginSst */
  8930. s.Count = val[0]; s.Unique = val[1]; break;
  8931. case 0x0013: /* BrtSSTItem */
  8932. s.push(val); break;
  8933. case 0x00A0: /* BrtEndSst */
  8934. return true;
  8935. case 0x0023: /* BrtFRTBegin */
  8936. pass = true; break;
  8937. case 0x0024: /* BrtFRTEnd */
  8938. pass = false; break;
  8939. default:
  8940. if(R.T){}
  8941. if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  8942. }
  8943. });
  8944. return s;
  8945. }
  8946. function write_BrtBeginSst(sst, o) {
  8947. if(!o) o = new_buf(8);
  8948. o.write_shift(4, sst.Count);
  8949. o.write_shift(4, sst.Unique);
  8950. return o;
  8951. }
  8952. var write_BrtSSTItem = write_RichStr;
  8953. function write_sst_bin(sst) {
  8954. var ba = buf_array();
  8955. write_record(ba, 0x009F /* BrtBeginSst */, write_BrtBeginSst(sst));
  8956. for(var i = 0; i < sst.length; ++i) write_record(ba, 0x0013 /* BrtSSTItem */, write_BrtSSTItem(sst[i]));
  8957. /* FRTSST */
  8958. write_record(ba, 0x00A0 /* BrtEndSst */);
  8959. return ba.end();
  8960. }
  8961. function _JS2ANSI(str) {
  8962. if(typeof $cptable !== 'undefined') return $cptable.utils.encode(current_ansi, str);
  8963. var o = [], oo = str.split("");
  8964. for(var i = 0; i < oo.length; ++i) o[i] = oo[i].charCodeAt(0);
  8965. return o;
  8966. }
  8967. /* [MS-OFFCRYPTO] 2.1.4 Version */
  8968. function parse_CRYPTOVersion(blob, length) {
  8969. var o = {};
  8970. o.Major = blob.read_shift(2);
  8971. o.Minor = blob.read_shift(2);
  8972. if(length >= 4) blob.l += length - 4;
  8973. return o;
  8974. }
  8975. /* [MS-OFFCRYPTO] 2.1.5 DataSpaceVersionInfo */
  8976. function parse_DataSpaceVersionInfo(blob) {
  8977. var o = {};
  8978. o.id = blob.read_shift(0, 'lpp4');
  8979. o.R = parse_CRYPTOVersion(blob, 4);
  8980. o.U = parse_CRYPTOVersion(blob, 4);
  8981. o.W = parse_CRYPTOVersion(blob, 4);
  8982. return o;
  8983. }
  8984. /* [MS-OFFCRYPTO] 2.1.6.1 DataSpaceMapEntry Structure */
  8985. function parse_DataSpaceMapEntry(blob) {
  8986. var len = blob.read_shift(4);
  8987. var end = blob.l + len - 4;
  8988. var o = {};
  8989. var cnt = blob.read_shift(4);
  8990. var comps = [];
  8991. /* [MS-OFFCRYPTO] 2.1.6.2 DataSpaceReferenceComponent Structure */
  8992. while(cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, 'lpp4') });
  8993. o.name = blob.read_shift(0, 'lpp4');
  8994. o.comps = comps;
  8995. if(blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
  8996. return o;
  8997. }
  8998. /* [MS-OFFCRYPTO] 2.1.6 DataSpaceMap */
  8999. function parse_DataSpaceMap(blob) {
  9000. var o = [];
  9001. blob.l += 4; // must be 0x8
  9002. var cnt = blob.read_shift(4);
  9003. while(cnt-- > 0) o.push(parse_DataSpaceMapEntry(blob));
  9004. return o;
  9005. }
  9006. /* [MS-OFFCRYPTO] 2.1.7 DataSpaceDefinition */
  9007. function parse_DataSpaceDefinition(blob) {
  9008. var o = [];
  9009. blob.l += 4; // must be 0x8
  9010. var cnt = blob.read_shift(4);
  9011. while(cnt-- > 0) o.push(blob.read_shift(0, 'lpp4'));
  9012. return o;
  9013. }
  9014. /* [MS-OFFCRYPTO] 2.1.8 DataSpaceDefinition */
  9015. function parse_TransformInfoHeader(blob) {
  9016. var o = {};
  9017. /*var len = */blob.read_shift(4);
  9018. blob.l += 4; // must be 0x1
  9019. o.id = blob.read_shift(0, 'lpp4');
  9020. o.name = blob.read_shift(0, 'lpp4');
  9021. o.R = parse_CRYPTOVersion(blob, 4);
  9022. o.U = parse_CRYPTOVersion(blob, 4);
  9023. o.W = parse_CRYPTOVersion(blob, 4);
  9024. return o;
  9025. }
  9026. function parse_Primary(blob) {
  9027. /* [MS-OFFCRYPTO] 2.2.6 IRMDSTransformInfo */
  9028. var hdr = parse_TransformInfoHeader(blob);
  9029. /* [MS-OFFCRYPTO] 2.1.9 EncryptionTransformInfo */
  9030. hdr.ename = blob.read_shift(0, '8lpp4');
  9031. hdr.blksz = blob.read_shift(4);
  9032. hdr.cmode = blob.read_shift(4);
  9033. if(blob.read_shift(4) != 0x04) throw new Error("Bad !Primary record");
  9034. return hdr;
  9035. }
  9036. /* [MS-OFFCRYPTO] 2.3.2 Encryption Header */
  9037. function parse_EncryptionHeader(blob, length) {
  9038. var tgt = blob.l + length;
  9039. var o = {};
  9040. o.Flags = (blob.read_shift(4) & 0x3F);
  9041. blob.l += 4;
  9042. o.AlgID = blob.read_shift(4);
  9043. var valid = false;
  9044. switch(o.AlgID) {
  9045. case 0x660E: case 0x660F: case 0x6610: valid = (o.Flags == 0x24); break;
  9046. case 0x6801: valid = (o.Flags == 0x04); break;
  9047. case 0: valid = (o.Flags == 0x10 || o.Flags == 0x04 || o.Flags == 0x24); break;
  9048. default: throw 'Unrecognized encryption algorithm: ' + o.AlgID;
  9049. }
  9050. if(!valid) throw new Error("Encryption Flags/AlgID mismatch");
  9051. o.AlgIDHash = blob.read_shift(4);
  9052. o.KeySize = blob.read_shift(4);
  9053. o.ProviderType = blob.read_shift(4);
  9054. blob.l += 8;
  9055. o.CSPName = blob.read_shift((tgt-blob.l)>>1, 'utf16le');
  9056. blob.l = tgt;
  9057. return o;
  9058. }
  9059. /* [MS-OFFCRYPTO] 2.3.3 Encryption Verifier */
  9060. function parse_EncryptionVerifier(blob, length) {
  9061. var o = {}, tgt = blob.l + length;
  9062. blob.l += 4; // SaltSize must be 0x10
  9063. o.Salt = blob.slice(blob.l, blob.l+16); blob.l += 16;
  9064. o.Verifier = blob.slice(blob.l, blob.l+16); blob.l += 16;
  9065. /*var sz = */blob.read_shift(4);
  9066. o.VerifierHash = blob.slice(blob.l, tgt); blob.l = tgt;
  9067. return o;
  9068. }
  9069. /* [MS-OFFCRYPTO] 2.3.4.* EncryptionInfo Stream */
  9070. function parse_EncryptionInfo(blob) {
  9071. var vers = parse_CRYPTOVersion(blob);
  9072. switch(vers.Minor) {
  9073. case 0x02: return [vers.Minor, parse_EncInfoStd(blob, vers)];
  9074. case 0x03: return [vers.Minor, parse_EncInfoExt(blob, vers)];
  9075. case 0x04: return [vers.Minor, parse_EncInfoAgl(blob, vers)];
  9076. }
  9077. throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
  9078. }
  9079. /* [MS-OFFCRYPTO] 2.3.4.5 EncryptionInfo Stream (Standard Encryption) */
  9080. function parse_EncInfoStd(blob) {
  9081. var flags = blob.read_shift(4);
  9082. if((flags & 0x3F) != 0x24) throw new Error("EncryptionInfo mismatch");
  9083. var sz = blob.read_shift(4);
  9084. //var tgt = blob.l + sz;
  9085. var hdr = parse_EncryptionHeader(blob, sz);
  9086. var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
  9087. return { t:"Std", h:hdr, v:verifier };
  9088. }
  9089. /* [MS-OFFCRYPTO] 2.3.4.6 EncryptionInfo Stream (Extensible Encryption) */
  9090. function parse_EncInfoExt() { throw new Error("File is password-protected: ECMA-376 Extensible"); }
  9091. /* [MS-OFFCRYPTO] 2.3.4.10 EncryptionInfo Stream (Agile Encryption) */
  9092. function parse_EncInfoAgl(blob) {
  9093. var KeyData = ["saltSize","blockSize","keyBits","hashSize","cipherAlgorithm","cipherChaining","hashAlgorithm","saltValue"];
  9094. blob.l+=4;
  9095. var xml = blob.read_shift(blob.length - blob.l, 'utf8');
  9096. var o = {};
  9097. xml.replace(tagregex, function xml_agile(x) {
  9098. var y = parsexmltag(x);
  9099. switch(strip_ns(y[0])) {
  9100. case '<?xml': break;
  9101. case '<encryption': case '</encryption>': break;
  9102. case '<keyData': KeyData.forEach(function(k) { o[k] = y[k]; }); break;
  9103. case '<dataIntegrity': o.encryptedHmacKey = y.encryptedHmacKey; o.encryptedHmacValue = y.encryptedHmacValue; break;
  9104. case '<keyEncryptors>': case '<keyEncryptors': o.encs = []; break;
  9105. case '</keyEncryptors>': break;
  9106. case '<keyEncryptor': o.uri = y.uri; break;
  9107. case '</keyEncryptor>': break;
  9108. case '<encryptedKey': o.encs.push(y); break;
  9109. default: throw y[0];
  9110. }
  9111. });
  9112. return o;
  9113. }
  9114. /* [MS-OFFCRYPTO] 2.3.5.1 RC4 CryptoAPI Encryption Header */
  9115. function parse_RC4CryptoHeader(blob, length) {
  9116. var o = {};
  9117. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); length -= 4;
  9118. if(vers.Minor != 2) throw new Error('unrecognized minor version code: ' + vers.Minor);
  9119. if(vers.Major > 4 || vers.Major < 2) throw new Error('unrecognized major version code: ' + vers.Major);
  9120. o.Flags = blob.read_shift(4); length -= 4;
  9121. var sz = blob.read_shift(4); length -= 4;
  9122. o.EncryptionHeader = parse_EncryptionHeader(blob, sz); length -= sz;
  9123. o.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
  9124. return o;
  9125. }
  9126. /* [MS-OFFCRYPTO] 2.3.6.1 RC4 Encryption Header */
  9127. function parse_RC4Header(blob) {
  9128. var o = {};
  9129. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
  9130. if(vers.Major != 1 || vers.Minor != 1) throw 'unrecognized version code ' + vers.Major + ' : ' + vers.Minor;
  9131. o.Salt = blob.read_shift(16);
  9132. o.EncryptedVerifier = blob.read_shift(16);
  9133. o.EncryptedVerifierHash = blob.read_shift(16);
  9134. return o;
  9135. }
  9136. /* [MS-OFFCRYPTO] 2.3.7.1 Binary Document Password Verifier Derivation */
  9137. function crypto_CreatePasswordVerifier_Method1(Password) {
  9138. var Verifier = 0x0000, PasswordArray;
  9139. var PasswordDecoded = _JS2ANSI(Password);
  9140. var len = PasswordDecoded.length + 1, i, PasswordByte;
  9141. var Intermediate1, Intermediate2, Intermediate3;
  9142. PasswordArray = new_raw_buf(len);
  9143. PasswordArray[0] = PasswordDecoded.length;
  9144. for(i = 1; i != len; ++i) PasswordArray[i] = PasswordDecoded[i-1];
  9145. for(i = len-1; i >= 0; --i) {
  9146. PasswordByte = PasswordArray[i];
  9147. Intermediate1 = ((Verifier & 0x4000) === 0x0000) ? 0 : 1;
  9148. Intermediate2 = (Verifier << 1) & 0x7FFF;
  9149. Intermediate3 = Intermediate1 | Intermediate2;
  9150. Verifier = Intermediate3 ^ PasswordByte;
  9151. }
  9152. return Verifier ^ 0xCE4B;
  9153. }
  9154. /* [MS-OFFCRYPTO] 2.3.7.2 Binary Document XOR Array Initialization */
  9155. var crypto_CreateXorArray_Method1 = (function() {
  9156. var PadArray = [0xBB, 0xFF, 0xFF, 0xBA, 0xFF, 0xFF, 0xB9, 0x80, 0x00, 0xBE, 0x0F, 0x00, 0xBF, 0x0F, 0x00];
  9157. var InitialCode = [0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3];
  9158. 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];
  9159. var Ror = function(Byte) { return ((Byte/2) | (Byte*128)) & 0xFF; };
  9160. var XorRor = function(byte1, byte2) { return Ror(byte1 ^ byte2); };
  9161. var CreateXorKey_Method1 = function(Password) {
  9162. var XorKey = InitialCode[Password.length - 1];
  9163. var CurrentElement = 0x68;
  9164. for(var i = Password.length-1; i >= 0; --i) {
  9165. var Char = Password[i];
  9166. for(var j = 0; j != 7; ++j) {
  9167. if(Char & 0x40) XorKey ^= XorMatrix[CurrentElement];
  9168. Char *= 2; --CurrentElement;
  9169. }
  9170. }
  9171. return XorKey;
  9172. };
  9173. return function(password) {
  9174. var Password = _JS2ANSI(password);
  9175. var XorKey = CreateXorKey_Method1(Password);
  9176. var Index = Password.length;
  9177. var ObfuscationArray = new_raw_buf(16);
  9178. for(var i = 0; i != 16; ++i) ObfuscationArray[i] = 0x00;
  9179. var Temp, PasswordLastChar, PadIndex;
  9180. if((Index & 1) === 1) {
  9181. Temp = XorKey >> 8;
  9182. ObfuscationArray[Index] = XorRor(PadArray[0], Temp);
  9183. --Index;
  9184. Temp = XorKey & 0xFF;
  9185. PasswordLastChar = Password[Password.length - 1];
  9186. ObfuscationArray[Index] = XorRor(PasswordLastChar, Temp);
  9187. }
  9188. while(Index > 0) {
  9189. --Index;
  9190. Temp = XorKey >> 8;
  9191. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  9192. --Index;
  9193. Temp = XorKey & 0xFF;
  9194. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  9195. }
  9196. Index = 15;
  9197. PadIndex = 15 - Password.length;
  9198. while(PadIndex > 0) {
  9199. Temp = XorKey >> 8;
  9200. ObfuscationArray[Index] = XorRor(PadArray[PadIndex], Temp);
  9201. --Index;
  9202. --PadIndex;
  9203. Temp = XorKey & 0xFF;
  9204. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  9205. --Index;
  9206. --PadIndex;
  9207. }
  9208. return ObfuscationArray;
  9209. };
  9210. })();
  9211. /* [MS-OFFCRYPTO] 2.3.7.3 Binary Document XOR Data Transformation Method 1 */
  9212. var crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O) {
  9213. /* If XorArray is set, use it; if O is not set, make changes in-place */
  9214. if(!O) O = Data;
  9215. if(!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
  9216. var Index, Value;
  9217. for(Index = 0; Index != Data.length; ++Index) {
  9218. Value = Data[Index];
  9219. Value ^= XorArray[XorArrayIndex];
  9220. Value = ((Value>>5) | (Value<<3)) & 0xFF;
  9221. O[Index] = Value;
  9222. ++XorArrayIndex;
  9223. }
  9224. return [O, XorArrayIndex, XorArray];
  9225. };
  9226. var crypto_MakeXorDecryptor = function(password) {
  9227. var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
  9228. return function(Data) {
  9229. var O = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
  9230. XorArrayIndex = O[1];
  9231. return O[0];
  9232. };
  9233. };
  9234. /* 2.5.343 */
  9235. function parse_XORObfuscation(blob, length, opts, out) {
  9236. var o = ({ key: parseuint16(blob), verificationBytes: parseuint16(blob) });
  9237. if(opts.password) o.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
  9238. out.valid = o.verificationBytes === o.verifier;
  9239. if(out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
  9240. return o;
  9241. }
  9242. /* 2.4.117 */
  9243. function parse_FilePassHeader(blob, length, oo) {
  9244. var o = oo || {}; o.Info = blob.read_shift(2); blob.l -= 2;
  9245. if(o.Info === 1) o.Data = parse_RC4Header(blob, length);
  9246. else o.Data = parse_RC4CryptoHeader(blob, length);
  9247. return o;
  9248. }
  9249. function parse_FilePass(blob, length, opts) {
  9250. var o = ({ Type: opts.biff >= 8 ? blob.read_shift(2) : 0 }); /* wEncryptionType */
  9251. if(o.Type) parse_FilePassHeader(blob, length-2, o);
  9252. else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o);
  9253. return o;
  9254. }
  9255. var RTF = (function() {
  9256. function rtf_to_sheet(d, opts) {
  9257. switch(opts.type) {
  9258. case 'base64': return rtf_to_sheet_str(Base64_decode(d), opts);
  9259. case 'binary': return rtf_to_sheet_str(d, opts);
  9260. case 'buffer': return rtf_to_sheet_str(has_buf && Buffer.isBuffer(d) ? d.toString('binary') : a2s(d), opts);
  9261. case 'array': return rtf_to_sheet_str(cc2str(d), opts);
  9262. }
  9263. throw new Error("Unrecognized type " + opts.type);
  9264. }
  9265. /* TODO: this is a stub */
  9266. function rtf_to_sheet_str(str, opts) {
  9267. var o = opts || {};
  9268. var ws = o.dense ? ([]) : ({});
  9269. var rows = str.match(/\\trowd.*?\\row\b/g);
  9270. if(!rows.length) throw new Error("RTF missing table");
  9271. var range = ({s: {c:0, r:0}, e: {c:0, r:rows.length - 1}});
  9272. rows.forEach(function(rowtf, R) {
  9273. if(Array.isArray(ws)) ws[R] = [];
  9274. var rtfre = /\\\w+\b/g;
  9275. var last_index = 0;
  9276. var res;
  9277. var C = -1;
  9278. while((res = rtfre.exec(rowtf))) {
  9279. switch(res[0]) {
  9280. case "\\cell":
  9281. var data = rowtf.slice(last_index, rtfre.lastIndex - res[0].length);
  9282. if(data[0] == " ") data = data.slice(1);
  9283. ++C;
  9284. if(data.length) {
  9285. // TODO: value parsing, including codepage adjustments
  9286. var cell = {v: data, t:"s"};
  9287. if(Array.isArray(ws)) ws[R][C] = cell;
  9288. else ws[encode_cell({r:R, c:C})] = cell;
  9289. }
  9290. break;
  9291. }
  9292. last_index = rtfre.lastIndex;
  9293. }
  9294. if(C > range.e.c) range.e.c = C;
  9295. });
  9296. ws['!ref'] = encode_range(range);
  9297. return ws;
  9298. }
  9299. function rtf_to_workbook(d, opts) { return sheet_to_workbook(rtf_to_sheet(d, opts), opts); }
  9300. /* TODO: this is a stub */
  9301. function sheet_to_rtf(ws) {
  9302. var o = ["{\\rtf1\\ansi"];
  9303. var r = safe_decode_range(ws['!ref']), cell;
  9304. var dense = Array.isArray(ws);
  9305. for(var R = r.s.r; R <= r.e.r; ++R) {
  9306. o.push("\\trowd\\trautofit1");
  9307. for(var C = r.s.c; C <= r.e.c; ++C) o.push("\\cellx" + (C+1));
  9308. o.push("\\pard\\intbl");
  9309. for(C = r.s.c; C <= r.e.c; ++C) {
  9310. var coord = encode_cell({r:R,c:C});
  9311. cell = dense ? (ws[R]||[])[C]: ws[coord];
  9312. if(!cell || cell.v == null && (!cell.f || cell.F)) continue;
  9313. o.push(" " + (cell.w || (format_cell(cell), cell.w)));
  9314. o.push("\\cell");
  9315. }
  9316. o.push("\\pard\\intbl\\row");
  9317. }
  9318. return o.join("") + "}";
  9319. }
  9320. return {
  9321. to_workbook: rtf_to_workbook,
  9322. to_sheet: rtf_to_sheet,
  9323. from_sheet: sheet_to_rtf
  9324. };
  9325. })();
  9326. function hex2RGB(h) {
  9327. var o = h.slice(h[0]==="#"?1:0).slice(0,6);
  9328. return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
  9329. }
  9330. function rgb2Hex(rgb) {
  9331. for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
  9332. return o.toString(16).toUpperCase().slice(1);
  9333. }
  9334. function rgb2HSL(rgb) {
  9335. var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
  9336. var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
  9337. if(C === 0) return [0, 0, R];
  9338. var H6 = 0, S = 0, L2 = (M + m);
  9339. S = C / (L2 > 1 ? 2 - L2 : L2);
  9340. switch(M){
  9341. case R: H6 = ((G - B) / C + 6)%6; break;
  9342. case G: H6 = ((B - R) / C + 2); break;
  9343. case B: H6 = ((R - G) / C + 4); break;
  9344. }
  9345. return [H6 / 6, S, L2 / 2];
  9346. }
  9347. function hsl2RGB(hsl){
  9348. var H = hsl[0], S = hsl[1], L = hsl[2];
  9349. var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
  9350. var rgb = [m,m,m], h6 = 6*H;
  9351. var X;
  9352. if(S !== 0) switch(h6|0) {
  9353. case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
  9354. case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
  9355. case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
  9356. case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
  9357. case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
  9358. case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
  9359. }
  9360. for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
  9361. return rgb;
  9362. }
  9363. /* 18.8.3 bgColor tint algorithm */
  9364. function rgb_tint(hex, tint) {
  9365. if(tint === 0) return hex;
  9366. var hsl = rgb2HSL(hex2RGB(hex));
  9367. if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  9368. else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  9369. return rgb2Hex(hsl2RGB(hsl));
  9370. }
  9371. /* 18.3.1.13 width calculations */
  9372. /* [MS-OI29500] 2.1.595 Column Width & Formatting */
  9373. var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
  9374. function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
  9375. function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
  9376. function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
  9377. //function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
  9378. //function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
  9379. function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
  9380. /* XLSX/XLSB/XLS specify width in units of MDW */
  9381. function find_mdw_colw(collw) {
  9382. var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  9383. 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; }
  9384. MDW = _MDW;
  9385. }
  9386. /* XLML specifies width in terms of pixels */
  9387. /*function find_mdw_wpx(wpx) {
  9388. var delta = Infinity, guess = 0, _MDW = MIN_MDW;
  9389. for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
  9390. guess = char2width_(px2char_(wpx))*256;
  9391. guess = (guess) % 1;
  9392. if(guess > 0.5) guess--;
  9393. if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
  9394. }
  9395. MDW = _MDW;
  9396. }*/
  9397. function process_col(coll) {
  9398. if(coll.width) {
  9399. coll.wpx = width2px(coll.width);
  9400. coll.wch = px2char(coll.wpx);
  9401. coll.MDW = MDW;
  9402. } else if(coll.wpx) {
  9403. coll.wch = px2char(coll.wpx);
  9404. coll.width = char2width(coll.wch);
  9405. coll.MDW = MDW;
  9406. } else if(typeof coll.wch == 'number') {
  9407. coll.width = char2width(coll.wch);
  9408. coll.wpx = width2px(coll.width);
  9409. coll.MDW = MDW;
  9410. }
  9411. if(coll.customWidth) delete coll.customWidth;
  9412. }
  9413. var DEF_PPI = 96, PPI = DEF_PPI;
  9414. function px2pt(px) { return px * 96 / PPI; }
  9415. function pt2px(pt) { return pt * PPI / 96; }
  9416. /* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
  9417. var XLMLPatternTypeMap = {
  9418. "None": "none",
  9419. "Solid": "solid",
  9420. "Gray50": "mediumGray",
  9421. "Gray75": "darkGray",
  9422. "Gray25": "lightGray",
  9423. "HorzStripe": "darkHorizontal",
  9424. "VertStripe": "darkVertical",
  9425. "ReverseDiagStripe": "darkDown",
  9426. "DiagStripe": "darkUp",
  9427. "DiagCross": "darkGrid",
  9428. "ThickDiagCross": "darkTrellis",
  9429. "ThinHorzStripe": "lightHorizontal",
  9430. "ThinVertStripe": "lightVertical",
  9431. "ThinReverseDiagStripe": "lightDown",
  9432. "ThinHorzCross": "lightGrid"
  9433. };
  9434. /* 18.8.5 borders CT_Borders */
  9435. function parse_borders(t, styles, themes, opts) {
  9436. styles.Borders = [];
  9437. var border = {};
  9438. var pass = false;
  9439. (t[0].match(tagregex)||[]).forEach(function(x) {
  9440. var y = parsexmltag(x);
  9441. switch(strip_ns(y[0])) {
  9442. case '<borders': case '<borders>': case '</borders>': break;
  9443. /* 18.8.4 border CT_Border */
  9444. case '<border': case '<border>': case '<border/>':
  9445. border = {};
  9446. if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
  9447. if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
  9448. styles.Borders.push(border);
  9449. break;
  9450. case '</border>': break;
  9451. /* note: not in spec, appears to be CT_BorderPr */
  9452. case '<left/>': break;
  9453. case '<left': case '<left>': break;
  9454. case '</left>': break;
  9455. /* note: not in spec, appears to be CT_BorderPr */
  9456. case '<right/>': break;
  9457. case '<right': case '<right>': break;
  9458. case '</right>': break;
  9459. /* 18.8.43 top CT_BorderPr */
  9460. case '<top/>': break;
  9461. case '<top': case '<top>': break;
  9462. case '</top>': break;
  9463. /* 18.8.6 bottom CT_BorderPr */
  9464. case '<bottom/>': break;
  9465. case '<bottom': case '<bottom>': break;
  9466. case '</bottom>': break;
  9467. /* 18.8.13 diagonal CT_BorderPr */
  9468. case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
  9469. case '</diagonal>': break;
  9470. /* 18.8.25 horizontal CT_BorderPr */
  9471. case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
  9472. case '</horizontal>': break;
  9473. /* 18.8.44 vertical CT_BorderPr */
  9474. case '<vertical': case '<vertical>': case '<vertical/>': break;
  9475. case '</vertical>': break;
  9476. /* 18.8.37 start CT_BorderPr */
  9477. case '<start': case '<start>': case '<start/>': break;
  9478. case '</start>': break;
  9479. /* 18.8.16 end CT_BorderPr */
  9480. case '<end': case '<end>': case '<end/>': break;
  9481. case '</end>': break;
  9482. /* 18.8.? color CT_Color */
  9483. case '<color': case '<color>':
  9484. break;
  9485. case '<color/>': case '</color>': break;
  9486. /* 18.2.10 extLst CT_ExtensionList ? */
  9487. case '<extLst': case '<extLst>': case '</extLst>': break;
  9488. case '<ext': pass = true; break;
  9489. case '</ext>': pass = false; break;
  9490. default: if(opts && opts.WTF) {
  9491. if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
  9492. }
  9493. }
  9494. });
  9495. }
  9496. /* 18.8.21 fills CT_Fills */
  9497. function parse_fills(t, styles, themes, opts) {
  9498. styles.Fills = [];
  9499. var fill = {};
  9500. var pass = false;
  9501. (t[0].match(tagregex)||[]).forEach(function(x) {
  9502. var y = parsexmltag(x);
  9503. switch(strip_ns(y[0])) {
  9504. case '<fills': case '<fills>': case '</fills>': break;
  9505. /* 18.8.20 fill CT_Fill */
  9506. case '<fill>': case '<fill': case '<fill/>':
  9507. fill = {}; styles.Fills.push(fill); break;
  9508. case '</fill>': break;
  9509. /* 18.8.24 gradientFill CT_GradientFill */
  9510. case '<gradientFill>': break;
  9511. case '<gradientFill':
  9512. case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;
  9513. /* 18.8.32 patternFill CT_PatternFill */
  9514. case '<patternFill': case '<patternFill>':
  9515. if(y.patternType) fill.patternType = y.patternType;
  9516. break;
  9517. case '<patternFill/>': case '</patternFill>': break;
  9518. /* 18.8.3 bgColor CT_Color */
  9519. case '<bgColor':
  9520. if(!fill.bgColor) fill.bgColor = {};
  9521. if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
  9522. if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
  9523. if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
  9524. /* Excel uses ARGB strings */
  9525. if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
  9526. break;
  9527. case '<bgColor/>': case '</bgColor>': break;
  9528. /* 18.8.19 fgColor CT_Color */
  9529. case '<fgColor':
  9530. if(!fill.fgColor) fill.fgColor = {};
  9531. if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
  9532. if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
  9533. /* Excel uses ARGB strings */
  9534. if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
  9535. break;
  9536. case '<fgColor/>': case '</fgColor>': break;
  9537. /* 18.8.38 stop CT_GradientStop */
  9538. case '<stop': case '<stop/>': break;
  9539. case '</stop>': break;
  9540. /* 18.8.? color CT_Color */
  9541. case '<color': case '<color/>': break;
  9542. case '</color>': break;
  9543. /* 18.2.10 extLst CT_ExtensionList ? */
  9544. case '<extLst': case '<extLst>': case '</extLst>': break;
  9545. case '<ext': pass = true; break;
  9546. case '</ext>': pass = false; break;
  9547. default: if(opts && opts.WTF) {
  9548. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
  9549. }
  9550. }
  9551. });
  9552. }
  9553. /* 18.8.23 fonts CT_Fonts */
  9554. function parse_fonts(t, styles, themes, opts) {
  9555. styles.Fonts = [];
  9556. var font = {};
  9557. var pass = false;
  9558. (t[0].match(tagregex)||[]).forEach(function(x) {
  9559. var y = parsexmltag(x);
  9560. switch(strip_ns(y[0])) {
  9561. case '<fonts': case '<fonts>': case '</fonts>': break;
  9562. /* 18.8.22 font CT_Font */
  9563. case '<font': case '<font>': break;
  9564. case '</font>': case '<font/>':
  9565. styles.Fonts.push(font);
  9566. font = {};
  9567. break;
  9568. /* 18.8.29 name CT_FontName */
  9569. case '<name': if(y.val) font.name = utf8read(y.val); break;
  9570. case '<name/>': case '</name>': break;
  9571. /* 18.8.2 b CT_BooleanProperty */
  9572. case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
  9573. case '<b/>': font.bold = 1; break;
  9574. /* 18.8.26 i CT_BooleanProperty */
  9575. case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
  9576. case '<i/>': font.italic = 1; break;
  9577. /* 18.4.13 u CT_UnderlineProperty */
  9578. case '<u':
  9579. switch(y.val) {
  9580. case "none": font.underline = 0x00; break;
  9581. case "single": font.underline = 0x01; break;
  9582. case "double": font.underline = 0x02; break;
  9583. case "singleAccounting": font.underline = 0x21; break;
  9584. case "doubleAccounting": font.underline = 0x22; break;
  9585. } break;
  9586. case '<u/>': font.underline = 1; break;
  9587. /* 18.4.10 strike CT_BooleanProperty */
  9588. case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
  9589. case '<strike/>': font.strike = 1; break;
  9590. /* 18.4.2 outline CT_BooleanProperty */
  9591. case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
  9592. case '<outline/>': font.outline = 1; break;
  9593. /* 18.8.36 shadow CT_BooleanProperty */
  9594. case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
  9595. case '<shadow/>': font.shadow = 1; break;
  9596. /* 18.8.12 condense CT_BooleanProperty */
  9597. case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
  9598. case '<condense/>': font.condense = 1; break;
  9599. /* 18.8.17 extend CT_BooleanProperty */
  9600. case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
  9601. case '<extend/>': font.extend = 1; break;
  9602. /* 18.4.11 sz CT_FontSize */
  9603. case '<sz': if(y.val) font.sz = +y.val; break;
  9604. case '<sz/>': case '</sz>': break;
  9605. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
  9606. case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
  9607. case '<vertAlign/>': case '</vertAlign>': break;
  9608. /* 18.8.18 family CT_FontFamily */
  9609. case '<family': if(y.val) font.family = parseInt(y.val,10); break;
  9610. case '<family/>': case '</family>': break;
  9611. /* 18.8.35 scheme CT_FontScheme */
  9612. case '<scheme': if(y.val) font.scheme = y.val; break;
  9613. case '<scheme/>': case '</scheme>': break;
  9614. /* 18.4.1 charset CT_IntProperty */
  9615. case '<charset':
  9616. if(y.val == '1') break;
  9617. y.codepage = CS2CP[parseInt(y.val, 10)];
  9618. break;
  9619. /* 18.?.? color CT_Color */
  9620. case '<color':
  9621. if(!font.color) font.color = {};
  9622. if(y.auto) font.color.auto = parsexmlbool(y.auto);
  9623. if(y.rgb) font.color.rgb = y.rgb.slice(-6);
  9624. else if(y.indexed) {
  9625. font.color.index = parseInt(y.indexed, 10);
  9626. var icv = XLSIcv[font.color.index];
  9627. if(font.color.index == 81) icv = XLSIcv[1];
  9628. if(!icv) icv = XLSIcv[1]; //throw new Error(x); // note: 206 is valid
  9629. font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
  9630. } else if(y.theme) {
  9631. font.color.theme = parseInt(y.theme, 10);
  9632. if(y.tint) font.color.tint = parseFloat(y.tint);
  9633. if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
  9634. font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
  9635. }
  9636. }
  9637. break;
  9638. case '<color/>': case '</color>': break;
  9639. /* note: sometimes mc:AlternateContent appears bare */
  9640. case '<AlternateContent': pass = true; break;
  9641. case '</AlternateContent>': pass = false; break;
  9642. /* 18.2.10 extLst CT_ExtensionList ? */
  9643. case '<extLst': case '<extLst>': case '</extLst>': break;
  9644. case '<ext': pass = true; break;
  9645. case '</ext>': pass = false; break;
  9646. default: if(opts && opts.WTF) {
  9647. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
  9648. }
  9649. }
  9650. });
  9651. }
  9652. /* 18.8.31 numFmts CT_NumFmts */
  9653. function parse_numFmts(t, styles, opts) {
  9654. styles.NumberFmt = [];
  9655. var k/*Array<number>*/ = (keys(table_fmt));
  9656. for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = table_fmt[k[i]];
  9657. var m = t[0].match(tagregex);
  9658. if(!m) return;
  9659. for(i=0; i < m.length; ++i) {
  9660. var y = parsexmltag(m[i]);
  9661. switch(strip_ns(y[0])) {
  9662. case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
  9663. case '<numFmt': {
  9664. var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
  9665. styles.NumberFmt[j] = f;
  9666. if(j>0) {
  9667. if(j > 0x188) {
  9668. for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
  9669. styles.NumberFmt[j] = f;
  9670. }
  9671. SSF_load(f,j);
  9672. }
  9673. } break;
  9674. case '</numFmt>': break;
  9675. default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
  9676. }
  9677. }
  9678. }
  9679. function write_numFmts(NF) {
  9680. var o = ["<numFmts>"];
  9681. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  9682. 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])}));
  9683. });
  9684. if(o.length === 1) return "";
  9685. o[o.length] = ("</numFmts>");
  9686. o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
  9687. return o.join("");
  9688. }
  9689. /* 18.8.10 cellXfs CT_CellXfs */
  9690. var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
  9691. var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
  9692. function parse_cellXfs(t, styles, opts) {
  9693. styles.CellXf = [];
  9694. var xf;
  9695. var pass = false;
  9696. (t[0].match(tagregex)||[]).forEach(function(x) {
  9697. var y = parsexmltag(x), i = 0;
  9698. switch(strip_ns(y[0])) {
  9699. case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
  9700. /* 18.8.45 xf CT_Xf */
  9701. case '<xf': case '<xf/>':
  9702. xf = y;
  9703. delete xf[0];
  9704. for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
  9705. xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
  9706. for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
  9707. xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
  9708. if(styles.NumberFmt && xf.numFmtId > 0x188) {
  9709. for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
  9710. }
  9711. styles.CellXf.push(xf); break;
  9712. case '</xf>': break;
  9713. /* 18.8.1 alignment CT_CellAlignment */
  9714. case '<alignment': case '<alignment/>':
  9715. var alignment = {};
  9716. if(y.vertical) alignment.vertical = y.vertical;
  9717. if(y.horizontal) alignment.horizontal = y.horizontal;
  9718. if(y.textRotation != null) alignment.textRotation = y.textRotation;
  9719. if(y.indent) alignment.indent = y.indent;
  9720. if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
  9721. xf.alignment = alignment;
  9722. break;
  9723. case '</alignment>': break;
  9724. /* 18.8.33 protection CT_CellProtection */
  9725. case '<protection':
  9726. break;
  9727. case '</protection>': case '<protection/>': break;
  9728. /* note: sometimes mc:AlternateContent appears bare */
  9729. case '<AlternateContent': pass = true; break;
  9730. case '</AlternateContent>': pass = false; break;
  9731. /* 18.2.10 extLst CT_ExtensionList ? */
  9732. case '<extLst': case '<extLst>': case '</extLst>': break;
  9733. case '<ext': pass = true; break;
  9734. case '</ext>': pass = false; break;
  9735. default: if(opts && opts.WTF) {
  9736. if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
  9737. }
  9738. }
  9739. });
  9740. }
  9741. function write_cellXfs(cellXfs) {
  9742. var o = [];
  9743. o[o.length] = (writextag('cellXfs',null));
  9744. cellXfs.forEach(function(c) {
  9745. o[o.length] = (writextag('xf', null, c));
  9746. });
  9747. o[o.length] = ("</cellXfs>");
  9748. if(o.length === 2) return "";
  9749. o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
  9750. return o.join("");
  9751. }
  9752. /* 18.8 Styles CT_Stylesheet*/
  9753. var parse_sty_xml= (function make_pstyx() {
  9754. var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
  9755. var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
  9756. var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
  9757. var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
  9758. var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;
  9759. return function parse_sty_xml(data, themes, opts) {
  9760. var styles = {};
  9761. if(!data) return styles;
  9762. data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  9763. /* 18.8.39 styleSheet CT_Stylesheet */
  9764. var t;
  9765. /* 18.8.31 numFmts CT_NumFmts ? */
  9766. if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);
  9767. /* 18.8.23 fonts CT_Fonts ? */
  9768. if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);
  9769. /* 18.8.21 fills CT_Fills ? */
  9770. if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);
  9771. /* 18.8.5 borders CT_Borders ? */
  9772. if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);
  9773. /* 18.8.9 cellStyleXfs CT_CellStyleXfs ? */
  9774. /* 18.8.8 cellStyles CT_CellStyles ? */
  9775. /* 18.8.10 cellXfs CT_CellXfs ? */
  9776. if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);
  9777. /* 18.8.15 dxfs CT_Dxfs ? */
  9778. /* 18.8.42 tableStyles CT_TableStyles ? */
  9779. /* 18.8.11 colors CT_Colors ? */
  9780. /* 18.2.10 extLst CT_ExtensionList ? */
  9781. return styles;
  9782. };
  9783. })();
  9784. function write_sty_xml(wb, opts) {
  9785. var o = [XML_HEADER, writextag('styleSheet', null, {
  9786. 'xmlns': XMLNS_main[0],
  9787. 'xmlns:vt': XMLNS.vt
  9788. })], w;
  9789. if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
  9790. o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
  9791. o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  9792. o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
  9793. o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
  9794. if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
  9795. o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
  9796. o[o.length] = ('<dxfs count="0"/>');
  9797. o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
  9798. if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
  9799. return o.join("");
  9800. }
  9801. /* [MS-XLSB] 2.4.657 BrtFmt */
  9802. function parse_BrtFmt(data, length) {
  9803. var numFmtId = data.read_shift(2);
  9804. var stFmtCode = parse_XLWideString(data,length-2);
  9805. return [numFmtId, stFmtCode];
  9806. }
  9807. function write_BrtFmt(i, f, o) {
  9808. if(!o) o = new_buf(6 + 4 * f.length);
  9809. o.write_shift(2, i);
  9810. write_XLWideString(f, o);
  9811. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  9812. if(o.l == null) o.l = o.length;
  9813. return out;
  9814. }
  9815. /* [MS-XLSB] 2.4.659 BrtFont TODO */
  9816. function parse_BrtFont(data, length, opts) {
  9817. var out = ({});
  9818. out.sz = data.read_shift(2) / 20;
  9819. var grbit = parse_FontFlags(data, 2, opts);
  9820. if(grbit.fItalic) out.italic = 1;
  9821. if(grbit.fCondense) out.condense = 1;
  9822. if(grbit.fExtend) out.extend = 1;
  9823. if(grbit.fShadow) out.shadow = 1;
  9824. if(grbit.fOutline) out.outline = 1;
  9825. if(grbit.fStrikeout) out.strike = 1;
  9826. var bls = data.read_shift(2);
  9827. if(bls === 0x02BC) out.bold = 1;
  9828. switch(data.read_shift(2)) {
  9829. /* case 0: out.vertAlign = "baseline"; break; */
  9830. case 1: out.vertAlign = "superscript"; break;
  9831. case 2: out.vertAlign = "subscript"; break;
  9832. }
  9833. var underline = data.read_shift(1);
  9834. if(underline != 0) out.underline = underline;
  9835. var family = data.read_shift(1);
  9836. if(family > 0) out.family = family;
  9837. var bCharSet = data.read_shift(1);
  9838. if(bCharSet > 0) out.charset = bCharSet;
  9839. data.l++;
  9840. out.color = parse_BrtColor(data, 8);
  9841. switch(data.read_shift(1)) {
  9842. /* case 0: out.scheme = "none": break; */
  9843. case 1: out.scheme = "major"; break;
  9844. case 2: out.scheme = "minor"; break;
  9845. }
  9846. out.name = parse_XLWideString(data, length - 21);
  9847. return out;
  9848. }
  9849. function write_BrtFont(font, o) {
  9850. if(!o) o = new_buf(25+4*32);
  9851. o.write_shift(2, font.sz * 20);
  9852. write_FontFlags(font, o);
  9853. o.write_shift(2, font.bold ? 0x02BC : 0x0190);
  9854. var sss = 0;
  9855. if(font.vertAlign == "superscript") sss = 1;
  9856. else if(font.vertAlign == "subscript") sss = 2;
  9857. o.write_shift(2, sss);
  9858. o.write_shift(1, font.underline || 0);
  9859. o.write_shift(1, font.family || 0);
  9860. o.write_shift(1, font.charset || 0);
  9861. o.write_shift(1, 0);
  9862. write_BrtColor(font.color, o);
  9863. var scheme = 0;
  9864. if(font.scheme == "major") scheme = 1;
  9865. if(font.scheme == "minor") scheme = 2;
  9866. o.write_shift(1, scheme);
  9867. write_XLWideString(font.name, o);
  9868. return o.length > o.l ? o.slice(0, o.l) : o;
  9869. }
  9870. /* [MS-XLSB] 2.4.650 BrtFill */
  9871. var XLSBFillPTNames = [
  9872. "none",
  9873. "solid",
  9874. "mediumGray",
  9875. "darkGray",
  9876. "lightGray",
  9877. "darkHorizontal",
  9878. "darkVertical",
  9879. "darkDown",
  9880. "darkUp",
  9881. "darkGrid",
  9882. "darkTrellis",
  9883. "lightHorizontal",
  9884. "lightVertical",
  9885. "lightDown",
  9886. "lightUp",
  9887. "lightGrid",
  9888. "lightTrellis",
  9889. "gray125",
  9890. "gray0625"
  9891. ];
  9892. var rev_XLSBFillPTNames;
  9893. /* TODO: gradient fill representation */
  9894. var parse_BrtFill = parsenoop;
  9895. function write_BrtFill(fill, o) {
  9896. if(!o) o = new_buf(4*3 + 8*7 + 16*1);
  9897. if(!rev_XLSBFillPTNames) rev_XLSBFillPTNames = (evert(XLSBFillPTNames));
  9898. var fls = rev_XLSBFillPTNames[fill.patternType];
  9899. if(fls == null) fls = 0x28;
  9900. o.write_shift(4, fls);
  9901. var j = 0;
  9902. if(fls != 0x28) {
  9903. /* TODO: custom FG Color */
  9904. write_BrtColor({auto:1}, o);
  9905. /* TODO: custom BG Color */
  9906. write_BrtColor({auto:1}, o);
  9907. for(; j < 12; ++j) o.write_shift(4, 0);
  9908. } else {
  9909. for(; j < 4; ++j) o.write_shift(4, 0);
  9910. for(; j < 12; ++j) o.write_shift(4, 0); /* TODO */
  9911. /* iGradientType */
  9912. /* xnumDegree */
  9913. /* xnumFillToLeft */
  9914. /* xnumFillToRight */
  9915. /* xnumFillToTop */
  9916. /* xnumFillToBottom */
  9917. /* cNumStop */
  9918. /* xfillGradientStop */
  9919. }
  9920. return o.length > o.l ? o.slice(0, o.l) : o;
  9921. }
  9922. /* [MS-XLSB] 2.4.824 BrtXF */
  9923. function parse_BrtXF(data, length) {
  9924. var tgt = data.l + length;
  9925. var ixfeParent = data.read_shift(2);
  9926. var ifmt = data.read_shift(2);
  9927. data.l = tgt;
  9928. return {ixfe:ixfeParent, numFmtId:ifmt };
  9929. }
  9930. function write_BrtXF(data, ixfeP, o) {
  9931. if(!o) o = new_buf(16);
  9932. o.write_shift(2, ixfeP||0);
  9933. o.write_shift(2, data.numFmtId||0);
  9934. o.write_shift(2, 0); /* iFont */
  9935. o.write_shift(2, 0); /* iFill */
  9936. o.write_shift(2, 0); /* ixBorder */
  9937. o.write_shift(1, 0); /* trot */
  9938. o.write_shift(1, 0); /* indent */
  9939. var flow = 0;
  9940. o.write_shift(1, flow); /* flags */
  9941. o.write_shift(1, 0); /* flags */
  9942. o.write_shift(1, 0); /* xfGrbitAtr */
  9943. o.write_shift(1, 0);
  9944. return o;
  9945. }
  9946. /* [MS-XLSB] 2.5.4 Blxf TODO */
  9947. function write_Blxf(data, o) {
  9948. if(!o) o = new_buf(10);
  9949. o.write_shift(1, 0); /* dg */
  9950. o.write_shift(1, 0);
  9951. o.write_shift(4, 0); /* color */
  9952. o.write_shift(4, 0); /* color */
  9953. return o;
  9954. }
  9955. /* [MS-XLSB] 2.4.302 BrtBorder TODO */
  9956. var parse_BrtBorder = parsenoop;
  9957. function write_BrtBorder(border, o) {
  9958. if(!o) o = new_buf(51);
  9959. o.write_shift(1, 0); /* diagonal */
  9960. write_Blxf(null, o); /* top */
  9961. write_Blxf(null, o); /* bottom */
  9962. write_Blxf(null, o); /* left */
  9963. write_Blxf(null, o); /* right */
  9964. write_Blxf(null, o); /* diag */
  9965. return o.length > o.l ? o.slice(0, o.l) : o;
  9966. }
  9967. /* [MS-XLSB] 2.4.763 BrtStyle TODO */
  9968. function write_BrtStyle(style, o) {
  9969. if(!o) o = new_buf(12+4*10);
  9970. o.write_shift(4, style.xfId);
  9971. o.write_shift(2, 1);
  9972. o.write_shift(1, +style.builtinId);
  9973. o.write_shift(1, 0); /* iLevel */
  9974. write_XLNullableWideString(style.name || "", o);
  9975. return o.length > o.l ? o.slice(0, o.l) : o;
  9976. }
  9977. /* [MS-XLSB] 2.4.272 BrtBeginTableStyles */
  9978. function write_BrtBeginTableStyles(cnt, defTableStyle, defPivotStyle) {
  9979. var o = new_buf(4+256*2*4);
  9980. o.write_shift(4, cnt);
  9981. write_XLNullableWideString(defTableStyle, o);
  9982. write_XLNullableWideString(defPivotStyle, o);
  9983. return o.length > o.l ? o.slice(0, o.l) : o;
  9984. }
  9985. /* [MS-XLSB] 2.1.7.50 Styles */
  9986. function parse_sty_bin(data, themes, opts) {
  9987. var styles = {};
  9988. styles.NumberFmt = ([]);
  9989. for(var y in table_fmt) styles.NumberFmt[y] = table_fmt[y];
  9990. styles.CellXf = [];
  9991. styles.Fonts = [];
  9992. var state = [];
  9993. var pass = false;
  9994. recordhopper(data, function hopper_sty(val, R, RT) {
  9995. switch(RT) {
  9996. case 0x002C: /* BrtFmt */
  9997. styles.NumberFmt[val[0]] = val[1]; SSF_load(val[1], val[0]);
  9998. break;
  9999. case 0x002B: /* BrtFont */
  10000. styles.Fonts.push(val);
  10001. if(val.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
  10002. val.color.rgb = rgb_tint(themes.themeElements.clrScheme[val.color.theme].rgb, val.color.tint || 0);
  10003. }
  10004. break;
  10005. case 0x0401: /* BrtKnownFonts */ break;
  10006. case 0x002D: /* BrtFill */
  10007. break;
  10008. case 0x002E: /* BrtBorder */
  10009. break;
  10010. case 0x002F: /* BrtXF */
  10011. if(state[state.length - 1] == 0x0269 /* BrtBeginCellXFs */) {
  10012. styles.CellXf.push(val);
  10013. }
  10014. break;
  10015. case 0x0030: /* BrtStyle */
  10016. case 0x01FB: /* BrtDXF */
  10017. case 0x023C: /* BrtMRUColor */
  10018. case 0x01DB: /* BrtIndexedColor */
  10019. break;
  10020. case 0x0493: /* BrtDXF14 */
  10021. case 0x0836: /* BrtDXF15 */
  10022. case 0x046A: /* BrtSlicerStyleElement */
  10023. case 0x0200: /* BrtTableStyleElement */
  10024. case 0x082F: /* BrtTimelineStyleElement */
  10025. case 0x0C00: /* BrtUid */
  10026. break;
  10027. case 0x0023: /* BrtFRTBegin */
  10028. pass = true; break;
  10029. case 0x0024: /* BrtFRTEnd */
  10030. pass = false; break;
  10031. case 0x0025: /* BrtACBegin */
  10032. state.push(RT); pass = true; break;
  10033. case 0x0026: /* BrtACEnd */
  10034. state.pop(); pass = false; break;
  10035. default:
  10036. if(R.T > 0) state.push(RT);
  10037. else if(R.T < 0) state.pop();
  10038. else if(!pass || (opts.WTF && state[state.length-1] != 0x0025 /* BrtACBegin */)) throw new Error("Unexpected record 0x" + RT.toString(16));
  10039. }
  10040. });
  10041. return styles;
  10042. }
  10043. function write_FMTS_bin(ba, NF) {
  10044. if(!NF) return;
  10045. var cnt = 0;
  10046. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  10047. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) ++cnt;
  10048. });
  10049. if(cnt == 0) return;
  10050. write_record(ba, 0x0267 /* BrtBeginFmts */, write_UInt32LE(cnt));
  10051. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  10052. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_record(ba, 0x002C /* BrtFmt */, write_BrtFmt(i, NF[i]));
  10053. });
  10054. write_record(ba, 0x0268 /* BrtEndFmts */);
  10055. }
  10056. function write_FONTS_bin(ba) {
  10057. var cnt = 1;
  10058. if(cnt == 0) return;
  10059. write_record(ba, 0x0263 /* BrtBeginFonts */, write_UInt32LE(cnt));
  10060. write_record(ba, 0x002B /* BrtFont */, write_BrtFont({
  10061. sz:12,
  10062. color: {theme:1},
  10063. name: "Calibri",
  10064. family: 2,
  10065. scheme: "minor"
  10066. }));
  10067. /* 1*65491BrtFont [ACFONTS] */
  10068. write_record(ba, 0x0264 /* BrtEndFonts */);
  10069. }
  10070. function write_FILLS_bin(ba) {
  10071. var cnt = 2;
  10072. if(cnt == 0) return;
  10073. write_record(ba, 0x025B /* BrtBeginFills */, write_UInt32LE(cnt));
  10074. write_record(ba, 0x002D /* BrtFill */, write_BrtFill({patternType:"none"}));
  10075. write_record(ba, 0x002D /* BrtFill */, write_BrtFill({patternType:"gray125"}));
  10076. /* 1*65431BrtFill */
  10077. write_record(ba, 0x025C /* BrtEndFills */);
  10078. }
  10079. function write_BORDERS_bin(ba) {
  10080. var cnt = 1;
  10081. if(cnt == 0) return;
  10082. write_record(ba, 0x0265 /* BrtBeginBorders */, write_UInt32LE(cnt));
  10083. write_record(ba, 0x002E /* BrtBorder */, write_BrtBorder({}));
  10084. /* 1*65430BrtBorder */
  10085. write_record(ba, 0x0266 /* BrtEndBorders */);
  10086. }
  10087. function write_CELLSTYLEXFS_bin(ba) {
  10088. var cnt = 1;
  10089. write_record(ba, 0x0272 /* BrtBeginCellStyleXFs */, write_UInt32LE(cnt));
  10090. write_record(ba, 0x002F /* BrtXF */, write_BrtXF({
  10091. numFmtId: 0,
  10092. fontId: 0,
  10093. fillId: 0,
  10094. borderId: 0
  10095. }, 0xFFFF));
  10096. /* 1*65430(BrtXF *FRT) */
  10097. write_record(ba, 0x0273 /* BrtEndCellStyleXFs */);
  10098. }
  10099. function write_CELLXFS_bin(ba, data) {
  10100. write_record(ba, 0x0269 /* BrtBeginCellXFs */, write_UInt32LE(data.length));
  10101. data.forEach(function(c) { write_record(ba, 0x002F /* BrtXF */, write_BrtXF(c,0)); });
  10102. /* 1*65430(BrtXF *FRT) */
  10103. write_record(ba, 0x026A /* BrtEndCellXFs */);
  10104. }
  10105. function write_STYLES_bin(ba) {
  10106. var cnt = 1;
  10107. write_record(ba, 0x026B /* BrtBeginStyles */, write_UInt32LE(cnt));
  10108. write_record(ba, 0x0030 /* BrtStyle */, write_BrtStyle({
  10109. xfId:0,
  10110. builtinId:0,
  10111. name:"Normal"
  10112. }));
  10113. /* 1*65430(BrtStyle *FRT) */
  10114. write_record(ba, 0x026C /* BrtEndStyles */);
  10115. }
  10116. function write_DXFS_bin(ba) {
  10117. var cnt = 0;
  10118. write_record(ba, 0x01F9 /* BrtBeginDXFs */, write_UInt32LE(cnt));
  10119. /* *2147483647(BrtDXF *FRT) */
  10120. write_record(ba, 0x01FA /* BrtEndDXFs */);
  10121. }
  10122. function write_TABLESTYLES_bin(ba) {
  10123. var cnt = 0;
  10124. write_record(ba, 0x01FC /* BrtBeginTableStyles */, write_BrtBeginTableStyles(cnt, "TableStyleMedium9", "PivotStyleMedium4"));
  10125. /* *TABLESTYLE */
  10126. write_record(ba, 0x01FD /* BrtEndTableStyles */);
  10127. }
  10128. function write_COLORPALETTE_bin() {
  10129. return;
  10130. /* BrtBeginColorPalette [INDEXEDCOLORS] [MRUCOLORS] BrtEndColorPalette */
  10131. }
  10132. /* [MS-XLSB] 2.1.7.50 Styles */
  10133. function write_sty_bin(wb, opts) {
  10134. var ba = buf_array();
  10135. write_record(ba, 0x0116 /* BrtBeginStyleSheet */);
  10136. write_FMTS_bin(ba, wb.SSF);
  10137. write_FONTS_bin(ba, wb);
  10138. write_FILLS_bin(ba, wb);
  10139. write_BORDERS_bin(ba, wb);
  10140. write_CELLSTYLEXFS_bin(ba, wb);
  10141. write_CELLXFS_bin(ba, opts.cellXfs);
  10142. write_STYLES_bin(ba, wb);
  10143. write_DXFS_bin(ba, wb);
  10144. write_TABLESTYLES_bin(ba, wb);
  10145. write_COLORPALETTE_bin(ba, wb);
  10146. /* FRTSTYLESHEET*/
  10147. write_record(ba, 0x0117 /* BrtEndStyleSheet */);
  10148. return ba.end();
  10149. }
  10150. /* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
  10151. var XLSXThemeClrScheme = [
  10152. '</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
  10153. '</a:accent1>', '</a:accent2>', '</a:accent3>',
  10154. '</a:accent4>', '</a:accent5>', '</a:accent6>',
  10155. '</a:hlink>', '</a:folHlink>'
  10156. ];
  10157. /* 20.1.6.2 clrScheme CT_ColorScheme */
  10158. function parse_clrScheme(t, themes, opts) {
  10159. themes.themeElements.clrScheme = [];
  10160. var color = {};
  10161. (t[0].match(tagregex)||[]).forEach(function(x) {
  10162. var y = parsexmltag(x);
  10163. switch(y[0]) {
  10164. /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
  10165. case '<a:clrScheme': case '</a:clrScheme>': break;
  10166. /* 20.1.2.3.32 srgbClr CT_SRgbColor */
  10167. case '<a:srgbClr':
  10168. color.rgb = y.val; break;
  10169. /* 20.1.2.3.33 sysClr CT_SystemColor */
  10170. case '<a:sysClr':
  10171. color.rgb = y.lastClr; break;
  10172. /* 20.1.4.1.1 accent1 (Accent 1) */
  10173. /* 20.1.4.1.2 accent2 (Accent 2) */
  10174. /* 20.1.4.1.3 accent3 (Accent 3) */
  10175. /* 20.1.4.1.4 accent4 (Accent 4) */
  10176. /* 20.1.4.1.5 accent5 (Accent 5) */
  10177. /* 20.1.4.1.6 accent6 (Accent 6) */
  10178. /* 20.1.4.1.9 dk1 (Dark 1) */
  10179. /* 20.1.4.1.10 dk2 (Dark 2) */
  10180. /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
  10181. /* 20.1.4.1.19 hlink (Hyperlink) */
  10182. /* 20.1.4.1.22 lt1 (Light 1) */
  10183. /* 20.1.4.1.23 lt2 (Light 2) */
  10184. case '<a:dk1>': case '</a:dk1>':
  10185. case '<a:lt1>': case '</a:lt1>':
  10186. case '<a:dk2>': case '</a:dk2>':
  10187. case '<a:lt2>': case '</a:lt2>':
  10188. case '<a:accent1>': case '</a:accent1>':
  10189. case '<a:accent2>': case '</a:accent2>':
  10190. case '<a:accent3>': case '</a:accent3>':
  10191. case '<a:accent4>': case '</a:accent4>':
  10192. case '<a:accent5>': case '</a:accent5>':
  10193. case '<a:accent6>': case '</a:accent6>':
  10194. case '<a:hlink>': case '</a:hlink>':
  10195. case '<a:folHlink>': case '</a:folHlink>':
  10196. if (y[0].charAt(1) === '/') {
  10197. themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
  10198. color = {};
  10199. } else {
  10200. color.name = y[0].slice(3, y[0].length - 1);
  10201. }
  10202. break;
  10203. default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
  10204. }
  10205. });
  10206. }
  10207. /* 20.1.4.1.18 fontScheme CT_FontScheme */
  10208. function parse_fontScheme() { }
  10209. /* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
  10210. function parse_fmtScheme() { }
  10211. var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
  10212. var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
  10213. var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;
  10214. /* 20.1.6.10 themeElements CT_BaseStyles */
  10215. function parse_themeElements(data, themes, opts) {
  10216. themes.themeElements = {};
  10217. var t;
  10218. [
  10219. /* clrScheme CT_ColorScheme */
  10220. ['clrScheme', clrsregex, parse_clrScheme],
  10221. /* fontScheme CT_FontScheme */
  10222. ['fontScheme', fntsregex, parse_fontScheme],
  10223. /* fmtScheme CT_StyleMatrix */
  10224. ['fmtScheme', fmtsregex, parse_fmtScheme]
  10225. ].forEach(function(m) {
  10226. if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
  10227. m[2](t, themes, opts);
  10228. });
  10229. }
  10230. var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;
  10231. /* 14.2.7 Theme Part */
  10232. function parse_theme_xml(data, opts) {
  10233. /* 20.1.6.9 theme CT_OfficeStyleSheet */
  10234. if(!data || data.length === 0) data = write_theme();
  10235. var t;
  10236. var themes = {};
  10237. /* themeElements CT_BaseStyles */
  10238. if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
  10239. parse_themeElements(t[0], themes, opts);
  10240. themes.raw = data;
  10241. return themes;
  10242. }
  10243. function write_theme(Themes, opts) {
  10244. if(opts && opts.themeXLSX) return opts.themeXLSX;
  10245. if(Themes && typeof Themes.raw == "string") return Themes.raw;
  10246. var o = [XML_HEADER];
  10247. o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  10248. o[o.length] = '<a:themeElements>';
  10249. o[o.length] = '<a:clrScheme name="Office">';
  10250. o[o.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  10251. o[o.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  10252. o[o.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  10253. o[o.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  10254. o[o.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  10255. o[o.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  10256. o[o.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  10257. o[o.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  10258. o[o.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  10259. o[o.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  10260. o[o.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  10261. o[o.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  10262. o[o.length] = '</a:clrScheme>';
  10263. o[o.length] = '<a:fontScheme name="Office">';
  10264. o[o.length] = '<a:majorFont>';
  10265. o[o.length] = '<a:latin typeface="Cambria"/>';
  10266. o[o.length] = '<a:ea typeface=""/>';
  10267. o[o.length] = '<a:cs typeface=""/>';
  10268. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  10269. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  10270. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  10271. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  10272. o[o.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  10273. o[o.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  10274. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  10275. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  10276. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  10277. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  10278. o[o.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  10279. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  10280. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  10281. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  10282. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  10283. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  10284. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  10285. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  10286. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  10287. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  10288. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  10289. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  10290. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  10291. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  10292. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  10293. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  10294. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  10295. o[o.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  10296. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  10297. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  10298. o[o.length] = '</a:majorFont>';
  10299. o[o.length] = '<a:minorFont>';
  10300. o[o.length] = '<a:latin typeface="Calibri"/>';
  10301. o[o.length] = '<a:ea typeface=""/>';
  10302. o[o.length] = '<a:cs typeface=""/>';
  10303. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  10304. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  10305. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  10306. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  10307. o[o.length] = '<a:font script="Arab" typeface="Arial"/>';
  10308. o[o.length] = '<a:font script="Hebr" typeface="Arial"/>';
  10309. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  10310. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  10311. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  10312. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  10313. o[o.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  10314. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  10315. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  10316. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  10317. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  10318. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  10319. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  10320. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  10321. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  10322. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  10323. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  10324. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  10325. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  10326. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  10327. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  10328. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  10329. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  10330. o[o.length] = '<a:font script="Viet" typeface="Arial"/>';
  10331. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  10332. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  10333. o[o.length] = '</a:minorFont>';
  10334. o[o.length] = '</a:fontScheme>';
  10335. o[o.length] = '<a:fmtScheme name="Office">';
  10336. o[o.length] = '<a:fillStyleLst>';
  10337. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  10338. o[o.length] = '<a:gradFill rotWithShape="1">';
  10339. o[o.length] = '<a:gsLst>';
  10340. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  10341. o[o.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  10342. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  10343. o[o.length] = '</a:gsLst>';
  10344. o[o.length] = '<a:lin ang="16200000" scaled="1"/>';
  10345. o[o.length] = '</a:gradFill>';
  10346. o[o.length] = '<a:gradFill rotWithShape="1">';
  10347. o[o.length] = '<a:gsLst>';
  10348. 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>';
  10349. 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>';
  10350. o[o.length] = '</a:gsLst>';
  10351. o[o.length] = '<a:lin ang="16200000" scaled="0"/>';
  10352. o[o.length] = '</a:gradFill>';
  10353. o[o.length] = '</a:fillStyleLst>';
  10354. o[o.length] = '<a:lnStyleLst>';
  10355. 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>';
  10356. 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>';
  10357. 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>';
  10358. o[o.length] = '</a:lnStyleLst>';
  10359. o[o.length] = '<a:effectStyleLst>';
  10360. o[o.length] = '<a:effectStyle>';
  10361. o[o.length] = '<a:effectLst>';
  10362. 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>';
  10363. o[o.length] = '</a:effectLst>';
  10364. o[o.length] = '</a:effectStyle>';
  10365. o[o.length] = '<a:effectStyle>';
  10366. o[o.length] = '<a:effectLst>';
  10367. 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>';
  10368. o[o.length] = '</a:effectLst>';
  10369. o[o.length] = '</a:effectStyle>';
  10370. o[o.length] = '<a:effectStyle>';
  10371. o[o.length] = '<a:effectLst>';
  10372. 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>';
  10373. o[o.length] = '</a:effectLst>';
  10374. 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>';
  10375. o[o.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  10376. o[o.length] = '</a:effectStyle>';
  10377. o[o.length] = '</a:effectStyleLst>';
  10378. o[o.length] = '<a:bgFillStyleLst>';
  10379. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  10380. o[o.length] = '<a:gradFill rotWithShape="1">';
  10381. o[o.length] = '<a:gsLst>';
  10382. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  10383. 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>';
  10384. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  10385. o[o.length] = '</a:gsLst>';
  10386. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  10387. o[o.length] = '</a:gradFill>';
  10388. o[o.length] = '<a:gradFill rotWithShape="1">';
  10389. o[o.length] = '<a:gsLst>';
  10390. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  10391. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  10392. o[o.length] = '</a:gsLst>';
  10393. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  10394. o[o.length] = '</a:gradFill>';
  10395. o[o.length] = '</a:bgFillStyleLst>';
  10396. o[o.length] = '</a:fmtScheme>';
  10397. o[o.length] = '</a:themeElements>';
  10398. o[o.length] = '<a:objectDefaults>';
  10399. o[o.length] = '<a:spDef>';
  10400. 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>';
  10401. o[o.length] = '</a:spDef>';
  10402. o[o.length] = '<a:lnDef>';
  10403. 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>';
  10404. o[o.length] = '</a:lnDef>';
  10405. o[o.length] = '</a:objectDefaults>';
  10406. o[o.length] = '<a:extraClrSchemeLst/>';
  10407. o[o.length] = '</a:theme>';
  10408. return o.join("");
  10409. }
  10410. /* [MS-XLS] 2.4.326 TODO: payload is a zip file */
  10411. function parse_Theme(blob, length, opts) {
  10412. var end = blob.l + length;
  10413. var dwThemeVersion = blob.read_shift(4);
  10414. if(dwThemeVersion === 124226) return;
  10415. if(!opts.cellStyles) { blob.l = end; return; }
  10416. var data = blob.slice(blob.l);
  10417. blob.l = end;
  10418. var zip; try { zip = zip_read(data, {type: "array"}); } catch(e) { return; }
  10419. var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
  10420. if(!themeXML) return;
  10421. return parse_theme_xml(themeXML, opts);
  10422. }
  10423. /* 2.5.49 */
  10424. function parse_ColorTheme(blob) { return blob.read_shift(4); }
  10425. /* 2.5.155 */
  10426. function parse_FullColorExt(blob) {
  10427. var o = {};
  10428. o.xclrType = blob.read_shift(2);
  10429. o.nTintShade = blob.read_shift(2);
  10430. switch(o.xclrType) {
  10431. case 0: blob.l += 4; break;
  10432. case 1: o.xclrValue = parse_IcvXF(blob, 4); break;
  10433. case 2: o.xclrValue = parse_LongRGBA(blob, 4); break;
  10434. case 3: o.xclrValue = parse_ColorTheme(blob, 4); break;
  10435. case 4: blob.l += 4; break;
  10436. }
  10437. blob.l += 8;
  10438. return o;
  10439. }
  10440. /* 2.5.164 TODO: read 7 bits*/
  10441. function parse_IcvXF(blob, length) {
  10442. return parsenoop(blob, length);
  10443. }
  10444. /* 2.5.280 */
  10445. function parse_XFExtGradient(blob, length) {
  10446. return parsenoop(blob, length);
  10447. }
  10448. /* [MS-XLS] 2.5.108 */
  10449. function parse_ExtProp(blob) {
  10450. var extType = blob.read_shift(2);
  10451. var cb = blob.read_shift(2) - 4;
  10452. var o = [extType];
  10453. switch(extType) {
  10454. case 0x04: case 0x05: case 0x07: case 0x08:
  10455. case 0x09: case 0x0A: case 0x0B: case 0x0D:
  10456. o[1] = parse_FullColorExt(blob, cb); break;
  10457. case 0x06: o[1] = parse_XFExtGradient(blob, cb); break;
  10458. case 0x0E: case 0x0F: o[1] = blob.read_shift(cb === 1 ? 1 : 2); break;
  10459. default: throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
  10460. }
  10461. return o;
  10462. }
  10463. /* 2.4.355 */
  10464. function parse_XFExt(blob, length) {
  10465. var end = blob.l + length;
  10466. blob.l += 2;
  10467. var ixfe = blob.read_shift(2);
  10468. blob.l += 2;
  10469. var cexts = blob.read_shift(2);
  10470. var ext = [];
  10471. while(cexts-- > 0) ext.push(parse_ExtProp(blob, end-blob.l));
  10472. return {ixfe:ixfe, ext:ext};
  10473. }
  10474. /* xf is an XF, see parse_XFExt for xfext */
  10475. function update_xfext(xf, xfext) {
  10476. xfext.forEach(function(xfe) {
  10477. switch(xfe[0]) { /* 2.5.108 extPropData */
  10478. case 0x04: break; /* foreground color */
  10479. case 0x05: break; /* background color */
  10480. case 0x06: break; /* gradient fill */
  10481. case 0x07: break; /* top cell border color */
  10482. case 0x08: break; /* bottom cell border color */
  10483. case 0x09: break; /* left cell border color */
  10484. case 0x0a: break; /* right cell border color */
  10485. case 0x0b: break; /* diagonal cell border color */
  10486. case 0x0d: /* text color */
  10487. break;
  10488. case 0x0e: break; /* font scheme */
  10489. case 0x0f: break; /* indentation level */
  10490. }
  10491. });
  10492. }
  10493. function parse_BrtMdtinfo(data, length) {
  10494. return {
  10495. flags: data.read_shift(4),
  10496. version: data.read_shift(4),
  10497. name: parse_XLWideString(data, length - 8)
  10498. };
  10499. }
  10500. function write_BrtMdtinfo(data) {
  10501. var o = new_buf(12 + 2 * data.name.length);
  10502. o.write_shift(4, data.flags);
  10503. o.write_shift(4, data.version);
  10504. write_XLWideString(data.name, o);
  10505. return o.slice(0, o.l);
  10506. }
  10507. function parse_BrtMdb(data) {
  10508. var out = [];
  10509. var cnt = data.read_shift(4);
  10510. while (cnt-- > 0)
  10511. out.push([data.read_shift(4), data.read_shift(4)]);
  10512. return out;
  10513. }
  10514. function write_BrtMdb(mdb) {
  10515. var o = new_buf(4 + 8 * mdb.length);
  10516. o.write_shift(4, mdb.length);
  10517. for (var i = 0; i < mdb.length; ++i) {
  10518. o.write_shift(4, mdb[i][0]);
  10519. o.write_shift(4, mdb[i][1]);
  10520. }
  10521. return o;
  10522. }
  10523. function write_BrtBeginEsfmd(cnt, name) {
  10524. var o = new_buf(8 + 2 * name.length);
  10525. o.write_shift(4, cnt);
  10526. write_XLWideString(name, o);
  10527. return o.slice(0, o.l);
  10528. }
  10529. function parse_BrtBeginEsmdb(data) {
  10530. data.l += 4;
  10531. return data.read_shift(4) != 0;
  10532. }
  10533. function write_BrtBeginEsmdb(cnt, cm) {
  10534. var o = new_buf(8);
  10535. o.write_shift(4, cnt);
  10536. o.write_shift(4, cm ? 1 : 0);
  10537. return o;
  10538. }
  10539. function parse_xlmeta_bin(data, name, _opts) {
  10540. var out = { Types: [], Cell: [], Value: [] };
  10541. var opts = _opts || {};
  10542. var state = [];
  10543. var pass = false;
  10544. var metatype = 2;
  10545. recordhopper(data, function(val, R, RT) {
  10546. switch (RT) {
  10547. case 335:
  10548. out.Types.push({ name: val.name });
  10549. break;
  10550. case 51:
  10551. val.forEach(function(r) {
  10552. if (metatype == 1)
  10553. out.Cell.push({ type: out.Types[r[0] - 1].name, index: r[1] });
  10554. else if (metatype == 0)
  10555. out.Value.push({ type: out.Types[r[0] - 1].name, index: r[1] });
  10556. });
  10557. break;
  10558. case 337:
  10559. metatype = val ? 1 : 0;
  10560. break;
  10561. case 338:
  10562. metatype = 2;
  10563. break;
  10564. case 35:
  10565. state.push(RT);
  10566. pass = true;
  10567. break;
  10568. case 36:
  10569. state.pop();
  10570. pass = false;
  10571. break;
  10572. default:
  10573. if (R.T) {
  10574. } else if (!pass || opts.WTF && state[state.length - 1] != 35)
  10575. throw new Error("Unexpected record 0x" + RT.toString(16));
  10576. }
  10577. });
  10578. return out;
  10579. }
  10580. function write_xlmeta_bin() {
  10581. var ba = buf_array();
  10582. write_record(ba, 332);
  10583. write_record(ba, 334, write_UInt32LE(1));
  10584. write_record(ba, 335, write_BrtMdtinfo({
  10585. name: "XLDAPR",
  10586. version: 12e4,
  10587. flags: 3496657072
  10588. }));
  10589. write_record(ba, 336);
  10590. write_record(ba, 339, write_BrtBeginEsfmd(1, "XLDAPR"));
  10591. write_record(ba, 52);
  10592. write_record(ba, 35, write_UInt32LE(514));
  10593. write_record(ba, 4096, write_UInt32LE(0));
  10594. write_record(ba, 4097, writeuint16(1));
  10595. write_record(ba, 36);
  10596. write_record(ba, 53);
  10597. write_record(ba, 340);
  10598. write_record(ba, 337, write_BrtBeginEsmdb(1, true));
  10599. write_record(ba, 51, write_BrtMdb([[1, 0]]));
  10600. write_record(ba, 338);
  10601. write_record(ba, 333);
  10602. return ba.end();
  10603. }
  10604. function parse_xlmeta_xml(data, name, opts) {
  10605. var out = { Types: [], Cell: [], Value: [] };
  10606. if (!data)
  10607. return out;
  10608. var pass = false;
  10609. var metatype = 2;
  10610. var lastmeta;
  10611. data.replace(tagregex, function(x) {
  10612. var y = parsexmltag(x);
  10613. switch (strip_ns(y[0])) {
  10614. case "<?xml":
  10615. break;
  10616. case "<metadata":
  10617. case "</metadata>":
  10618. break;
  10619. case "<metadataTypes":
  10620. case "</metadataTypes>":
  10621. break;
  10622. case "<metadataType":
  10623. out.Types.push({ name: y.name });
  10624. break;
  10625. case "</metadataType>":
  10626. break;
  10627. case "<futureMetadata":
  10628. for (var j = 0; j < out.Types.length; ++j)
  10629. if (out.Types[j].name == y.name)
  10630. lastmeta = out.Types[j];
  10631. break;
  10632. case "</futureMetadata>":
  10633. break;
  10634. case "<bk>":
  10635. break;
  10636. case "</bk>":
  10637. break;
  10638. case "<rc":
  10639. if (metatype == 1)
  10640. out.Cell.push({ type: out.Types[y.t - 1].name, index: +y.v });
  10641. else if (metatype == 0)
  10642. out.Value.push({ type: out.Types[y.t - 1].name, index: +y.v });
  10643. break;
  10644. case "</rc>":
  10645. break;
  10646. case "<cellMetadata":
  10647. metatype = 1;
  10648. break;
  10649. case "</cellMetadata>":
  10650. metatype = 2;
  10651. break;
  10652. case "<valueMetadata":
  10653. metatype = 0;
  10654. break;
  10655. case "</valueMetadata>":
  10656. metatype = 2;
  10657. break;
  10658. case "<extLst":
  10659. case "<extLst>":
  10660. case "</extLst>":
  10661. case "<extLst/>":
  10662. break;
  10663. case "<ext":
  10664. pass = true;
  10665. break;
  10666. case "</ext>":
  10667. pass = false;
  10668. break;
  10669. case "<rvb":
  10670. if (!lastmeta)
  10671. break;
  10672. if (!lastmeta.offsets)
  10673. lastmeta.offsets = [];
  10674. lastmeta.offsets.push(+y.i);
  10675. break;
  10676. default:
  10677. if (!pass && opts.WTF)
  10678. throw new Error("unrecognized " + y[0] + " in metadata");
  10679. }
  10680. return x;
  10681. });
  10682. return out;
  10683. }
  10684. function write_xlmeta_xml() {
  10685. var o = [XML_HEADER];
  10686. 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>');
  10687. return o.join("");
  10688. }
  10689. /* 18.6 Calculation Chain */
  10690. function parse_cc_xml(data) {
  10691. var d = [];
  10692. if(!data) return d;
  10693. var i = 1;
  10694. (data.match(tagregex)||[]).forEach(function(x) {
  10695. var y = parsexmltag(x);
  10696. switch(y[0]) {
  10697. case '<?xml': break;
  10698. /* 18.6.2 calcChain CT_CalcChain 1 */
  10699. case '<calcChain': case '<calcChain>': case '</calcChain>': break;
  10700. /* 18.6.1 c CT_CalcCell 1 */
  10701. case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
  10702. }
  10703. });
  10704. return d;
  10705. }
  10706. //function write_cc_xml(data, opts) { }
  10707. /* [MS-XLSB] 2.6.4.1 */
  10708. function parse_BrtCalcChainItem$(data) {
  10709. var out = {};
  10710. out.i = data.read_shift(4);
  10711. var cell = {};
  10712. cell.r = data.read_shift(4);
  10713. cell.c = data.read_shift(4);
  10714. out.r = encode_cell(cell);
  10715. var flags = data.read_shift(1);
  10716. if(flags & 0x2) out.l = '1';
  10717. if(flags & 0x8) out.a = '1';
  10718. return out;
  10719. }
  10720. /* 18.6 Calculation Chain */
  10721. function parse_cc_bin(data, name, opts) {
  10722. var out = [];
  10723. var pass = false;
  10724. recordhopper(data, function hopper_cc(val, R, RT) {
  10725. switch(RT) {
  10726. case 0x003F: /* 'BrtCalcChainItem$' */
  10727. out.push(val); break;
  10728. default:
  10729. if(R.T){/* empty */}
  10730. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  10731. }
  10732. });
  10733. return out;
  10734. }
  10735. //function write_cc_bin(data, opts) { }
  10736. /* 18.14 Supplementary Workbook Data */
  10737. function parse_xlink_xml() {
  10738. //var opts = _opts || {};
  10739. //if(opts.WTF) throw "XLSX External Link";
  10740. }
  10741. /* [MS-XLSB] 2.1.7.25 External Link */
  10742. function parse_xlink_bin(data, rel, name, _opts) {
  10743. if(!data) return data;
  10744. var opts = _opts || {};
  10745. var pass = false, end = false;
  10746. recordhopper(data, function xlink_parse(val, R, RT) {
  10747. if(end) return;
  10748. switch(RT) {
  10749. case 0x0167: /* 'BrtSupTabs' */
  10750. case 0x016B: /* 'BrtExternTableStart' */
  10751. case 0x016C: /* 'BrtExternTableEnd' */
  10752. case 0x016E: /* 'BrtExternRowHdr' */
  10753. case 0x016F: /* 'BrtExternCellBlank' */
  10754. case 0x0170: /* 'BrtExternCellReal' */
  10755. case 0x0171: /* 'BrtExternCellBool' */
  10756. case 0x0172: /* 'BrtExternCellError' */
  10757. case 0x0173: /* 'BrtExternCellString' */
  10758. case 0x01D8: /* 'BrtExternValueMeta' */
  10759. case 0x0241: /* 'BrtSupNameStart' */
  10760. case 0x0242: /* 'BrtSupNameValueStart' */
  10761. case 0x0243: /* 'BrtSupNameValueEnd' */
  10762. case 0x0244: /* 'BrtSupNameNum' */
  10763. case 0x0245: /* 'BrtSupNameErr' */
  10764. case 0x0246: /* 'BrtSupNameSt' */
  10765. case 0x0247: /* 'BrtSupNameNil' */
  10766. case 0x0248: /* 'BrtSupNameBool' */
  10767. case 0x0249: /* 'BrtSupNameFmla' */
  10768. case 0x024A: /* 'BrtSupNameBits' */
  10769. case 0x024B: /* 'BrtSupNameEnd' */
  10770. break;
  10771. case 0x0023: /* 'BrtFRTBegin' */
  10772. pass = true; break;
  10773. case 0x0024: /* 'BrtFRTEnd' */
  10774. pass = false; break;
  10775. default:
  10776. if(R.T){/* empty */}
  10777. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  10778. }
  10779. }, opts);
  10780. }
  10781. /* 20.5 DrawingML - SpreadsheetML Drawing */
  10782. /* 20.5.2.35 wsDr CT_Drawing */
  10783. function parse_drawing(data, rels) {
  10784. if(!data) return "??";
  10785. /*
  10786. Chartsheet Drawing:
  10787. - 20.5.2.35 wsDr CT_Drawing
  10788. - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor
  10789. - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
  10790. - 20.1.2.2.16 graphic CT_GraphicalObject
  10791. - 20.1.2.2.17 graphicData CT_GraphicalObjectData
  10792. - chart reference
  10793. the actual type is based on the URI of the graphicData
  10794. TODO: handle embedded charts and other types of graphics
  10795. */
  10796. var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];
  10797. return rels['!id'][id].Target;
  10798. }
  10799. /* L.5.5.2 SpreadsheetML Comments + VML Schema */
  10800. var _shapeid = 1024;
  10801. function write_comments_vml(rId, comments) {
  10802. var csize = [21600, 21600];
  10803. /* L.5.2.1.2 Path Attribute */
  10804. var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
  10805. var o = [
  10806. writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
  10807. writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"}),
  10808. writextag("v:shapetype", [
  10809. writextag("v:stroke", null, {joinstyle:"miter"}),
  10810. writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
  10811. ].join(""), {id:"_x0000_t202", 'o:spt':202, coordsize:csize.join(","),path:bbox})
  10812. ];
  10813. while(_shapeid < rId * 1000) _shapeid += 1000;
  10814. comments.forEach(function(x) {
  10815. var c = decode_cell(x[0]);
  10816. var fillopts = {'color2':"#BEFF82", 'type':"gradient"};
  10817. if(fillopts.type == "gradient") fillopts.angle = "-180";
  10818. var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
  10819. var fillxml = writextag('v:fill', fillparm, fillopts);
  10820. var shadata = ({on:"t", 'obscured':"t"});
  10821. ++_shapeid;
  10822. o = o.concat([
  10823. '<v:shape' + wxt_helper({
  10824. id:'_x0000_s' + _shapeid,
  10825. type:"#_x0000_t202",
  10826. style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
  10827. fillcolor:"#ECFAD4",
  10828. strokecolor:"#edeaa1"
  10829. }) + '>',
  10830. fillxml,
  10831. writextag("v:shadow", null, shadata),
  10832. writextag("v:path", null, {'o:connecttype':"none"}),
  10833. '<v:textbox><div style="text-align:left"></div></v:textbox>',
  10834. '<x:ClientData ObjectType="Note">',
  10835. '<x:MoveWithCells/>',
  10836. '<x:SizeWithCells/>',
  10837. /* Part 4 19.4.2.3 Anchor (Anchor) */
  10838. writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
  10839. writetag('x:AutoFill', "False"),
  10840. writetag('x:Row', String(c.r)),
  10841. writetag('x:Column', String(c.c)),
  10842. x[1].hidden ? '' : '<x:Visible/>',
  10843. '</x:ClientData>',
  10844. '</v:shape>'
  10845. ]); });
  10846. o.push('</xml>');
  10847. return o.join("");
  10848. }
  10849. function sheet_insert_comments(sheet, comments, threaded, people) {
  10850. var dense = Array.isArray(sheet);
  10851. var cell;
  10852. comments.forEach(function(comment) {
  10853. var r = decode_cell(comment.ref);
  10854. if(dense) {
  10855. if(!sheet[r.r]) sheet[r.r] = [];
  10856. cell = sheet[r.r][r.c];
  10857. } else cell = sheet[comment.ref];
  10858. if (!cell) {
  10859. cell = ({t:"z"});
  10860. if(dense) sheet[r.r][r.c] = cell;
  10861. else sheet[comment.ref] = cell;
  10862. var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
  10863. if(range.s.r > r.r) range.s.r = r.r;
  10864. if(range.e.r < r.r) range.e.r = r.r;
  10865. if(range.s.c > r.c) range.s.c = r.c;
  10866. if(range.e.c < r.c) range.e.c = r.c;
  10867. var encoded = encode_range(range);
  10868. if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
  10869. }
  10870. if (!cell.c) cell.c = [];
  10871. var o = ({a: comment.author, t: comment.t, r: comment.r, T: threaded});
  10872. if(comment.h) o.h = comment.h;
  10873. /* threaded comments always override */
  10874. for(var i = cell.c.length - 1; i >= 0; --i) {
  10875. if(!threaded && cell.c[i].T) return;
  10876. if(threaded && !cell.c[i].T) cell.c.splice(i, 1);
  10877. }
  10878. if(threaded && people) for(i = 0; i < people.length; ++i) {
  10879. if(o.a == people[i].id) { o.a = people[i].name || o.a; break; }
  10880. }
  10881. cell.c.push(o);
  10882. });
  10883. }
  10884. /* 18.7 Comments */
  10885. function parse_comments_xml(data, opts) {
  10886. /* 18.7.6 CT_Comments */
  10887. if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
  10888. var authors = [];
  10889. var commentList = [];
  10890. var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
  10891. if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
  10892. if(x === "" || x.trim() === "") return;
  10893. var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
  10894. if(a) authors.push(a[1]);
  10895. });
  10896. var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
  10897. if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
  10898. if(x === "" || x.trim() === "") return;
  10899. var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
  10900. if(!cm) return;
  10901. var y = parsexmltag(cm[0]);
  10902. var comment = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid });
  10903. var cell = decode_cell(y.ref);
  10904. if(opts.sheetRows && opts.sheetRows <= cell.r) return;
  10905. var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
  10906. var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
  10907. comment.r = rt.r;
  10908. if(rt.r == "<t></t>") rt.t = rt.h = "";
  10909. comment.t = (rt.t||"").replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  10910. if(opts.cellHTML) comment.h = rt.h;
  10911. commentList.push(comment);
  10912. });
  10913. return commentList;
  10914. }
  10915. function write_comments_xml(data) {
  10916. var o = [XML_HEADER, writextag('comments', null, { 'xmlns': XMLNS_main[0] })];
  10917. var iauthor = [];
  10918. o.push("<authors>");
  10919. data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
  10920. if(iauthor.indexOf(a) == -1) {
  10921. iauthor.push(a);
  10922. o.push("<author>" + a + "</author>");
  10923. }
  10924. if(w.T && w.ID && iauthor.indexOf("tc=" + w.ID) == -1) {
  10925. iauthor.push("tc=" + w.ID);
  10926. o.push("<author>" + "tc=" + w.ID + "</author>");
  10927. }
  10928. }); });
  10929. if(iauthor.length == 0) { iauthor.push("SheetJ5"); o.push("<author>SheetJ5</author>"); }
  10930. o.push("</authors>");
  10931. o.push("<commentList>");
  10932. data.forEach(function(d) {
  10933. /* 18.7.3 CT_Comment */
  10934. var lastauthor = 0, ts = [];
  10935. if(d[1][0] && d[1][0].T && d[1][0].ID) lastauthor = iauthor.indexOf("tc=" + d[1][0].ID);
  10936. else d[1].forEach(function(c) {
  10937. if(c.a) lastauthor = iauthor.indexOf(escapexml(c.a));
  10938. ts.push(c.t||"");
  10939. });
  10940. o.push('<comment ref="' + d[0] + '" authorId="' + lastauthor + '"><text>');
  10941. if(ts.length <= 1) o.push(writetag("t", escapexml(ts[0]||"")));
  10942. else {
  10943. /* based on Threaded Comments -> Comments projection */
  10944. var t = "Comment:\n " + (ts[0]) + "\n";
  10945. for(var i = 1; i < ts.length; ++i) t += "Reply:\n " + ts[i] + "\n";
  10946. o.push(writetag("t", escapexml(t)));
  10947. }
  10948. o.push('</text></comment>');
  10949. });
  10950. o.push("</commentList>");
  10951. if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
  10952. return o.join("");
  10953. }
  10954. /* [MS-XLSX] 2.1.17 */
  10955. function parse_tcmnt_xml(data, opts) {
  10956. var out = [];
  10957. var pass = false, comment = {}, tidx = 0;
  10958. data.replace(tagregex, function xml_tcmnt(x, idx) {
  10959. var y = parsexmltag(x);
  10960. switch(strip_ns(y[0])) {
  10961. case '<?xml': break;
  10962. /* 2.6.207 ThreadedComments CT_ThreadedComments */
  10963. case '<ThreadedComments': break;
  10964. case '</ThreadedComments>': break;
  10965. /* 2.6.205 threadedComment CT_ThreadedComment */
  10966. case '<threadedComment': comment = {author: y.personId, guid: y.id, ref: y.ref, T: 1}; break;
  10967. case '</threadedComment>': if(comment.t != null) out.push(comment); break;
  10968. case '<text>': case '<text': tidx = idx + x.length; break;
  10969. case '</text>': comment.t = data.slice(tidx, idx).replace(/\r\n/g, "\n").replace(/\r/g, "\n"); break;
  10970. /* 2.6.206 mentions CT_ThreadedCommentMentions TODO */
  10971. case '<mentions': case '<mentions>': pass = true; break;
  10972. case '</mentions>': pass = false; break;
  10973. /* 2.6.202 mention CT_Mention TODO */
  10974. /* 18.2.10 extLst CT_ExtensionList ? */
  10975. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  10976. /* 18.2.7 ext CT_Extension + */
  10977. case '<ext': pass=true; break;
  10978. case '</ext>': pass=false; break;
  10979. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in threaded comments');
  10980. }
  10981. return x;
  10982. });
  10983. return out;
  10984. }
  10985. function write_tcmnt_xml(comments, people, opts) {
  10986. var o = [XML_HEADER, writextag('ThreadedComments', null, { 'xmlns': XMLNS.TCMNT }).replace(/[\/]>/, ">")];
  10987. comments.forEach(function(carr) {
  10988. var rootid = "";
  10989. (carr[1] || []).forEach(function(c, idx) {
  10990. if(!c.T) { delete c.ID; return; }
  10991. if(c.a && people.indexOf(c.a) == -1) people.push(c.a);
  10992. var tcopts = {
  10993. ref: carr[0],
  10994. id: "{54EE7951-7262-4200-6969-" + ("000000000000" + opts.tcid++).slice(-12) + "}"
  10995. };
  10996. if(idx == 0) rootid = tcopts.id;
  10997. else tcopts.parentId = rootid;
  10998. c.ID = tcopts.id;
  10999. if(c.a) tcopts.personId = "{54EE7950-7262-4200-6969-" + ("000000000000" + people.indexOf(c.a)).slice(-12) + "}";
  11000. o.push(writextag('threadedComment', writetag('text', c.t||""), tcopts));
  11001. });
  11002. });
  11003. o.push('</ThreadedComments>');
  11004. return o.join("");
  11005. }
  11006. /* [MS-XLSX] 2.1.18 */
  11007. function parse_people_xml(data, opts) {
  11008. var out = [];
  11009. var pass = false;
  11010. data.replace(tagregex, function xml_tcmnt(x) {
  11011. var y = parsexmltag(x);
  11012. switch(strip_ns(y[0])) {
  11013. case '<?xml': break;
  11014. /* 2.4.85 personList CT_PersonList */
  11015. case '<personList': break;
  11016. case '</personList>': break;
  11017. /* 2.6.203 person CT_Person TODO: providers */
  11018. case '<person': out.push({name: y.displayname, id: y.id }); break;
  11019. case '</person>': break;
  11020. /* 18.2.10 extLst CT_ExtensionList ? */
  11021. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  11022. /* 18.2.7 ext CT_Extension + */
  11023. case '<ext': pass=true; break;
  11024. case '</ext>': pass=false; break;
  11025. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in threaded comments');
  11026. }
  11027. return x;
  11028. });
  11029. return out;
  11030. }
  11031. function write_people_xml(people/*, opts*/) {
  11032. var o = [XML_HEADER, writextag('personList', null, {
  11033. 'xmlns': XMLNS.TCMNT,
  11034. 'xmlns:x': XMLNS_main[0]
  11035. }).replace(/[\/]>/, ">")];
  11036. people.forEach(function(person, idx) {
  11037. o.push(writextag('person', null, {
  11038. displayName: person,
  11039. id: "{54EE7950-7262-4200-6969-" + ("000000000000" + idx).slice(-12) + "}",
  11040. userId: person,
  11041. providerId: "None"
  11042. }));
  11043. });
  11044. o.push("</personList>");
  11045. return o.join("");
  11046. }
  11047. /* [MS-XLSB] 2.4.28 BrtBeginComment */
  11048. function parse_BrtBeginComment(data) {
  11049. var out = {};
  11050. out.iauthor = data.read_shift(4);
  11051. var rfx = parse_UncheckedRfX(data, 16);
  11052. out.rfx = rfx.s;
  11053. out.ref = encode_cell(rfx.s);
  11054. data.l += 16; /*var guid = parse_GUID(data); */
  11055. return out;
  11056. }
  11057. function write_BrtBeginComment(data, o) {
  11058. if(o == null) o = new_buf(36);
  11059. o.write_shift(4, data[1].iauthor);
  11060. write_UncheckedRfX((data[0]), o);
  11061. o.write_shift(4, 0);
  11062. o.write_shift(4, 0);
  11063. o.write_shift(4, 0);
  11064. o.write_shift(4, 0);
  11065. return o;
  11066. }
  11067. /* [MS-XLSB] 2.4.327 BrtCommentAuthor */
  11068. var parse_BrtCommentAuthor = parse_XLWideString;
  11069. function write_BrtCommentAuthor(data) { return write_XLWideString(data.slice(0, 54)); }
  11070. /* [MS-XLSB] 2.1.7.8 Comments */
  11071. function parse_comments_bin(data, opts) {
  11072. var out = [];
  11073. var authors = [];
  11074. var c = {};
  11075. var pass = false;
  11076. recordhopper(data, function hopper_cmnt(val, R, RT) {
  11077. switch(RT) {
  11078. case 0x0278: /* 'BrtCommentAuthor' */
  11079. authors.push(val); break;
  11080. case 0x027B: /* 'BrtBeginComment' */
  11081. c = val; break;
  11082. case 0x027D: /* 'BrtCommentText' */
  11083. c.t = val.t; c.h = val.h; c.r = val.r; break;
  11084. case 0x027C: /* 'BrtEndComment' */
  11085. c.author = authors[c.iauthor];
  11086. delete (c).iauthor;
  11087. if(opts.sheetRows && c.rfx && opts.sheetRows <= c.rfx.r) break;
  11088. if(!c.t) c.t = "";
  11089. delete c.rfx; out.push(c); break;
  11090. case 0x0C00: /* 'BrtUid' */
  11091. break;
  11092. case 0x0023: /* 'BrtFRTBegin' */
  11093. pass = true; break;
  11094. case 0x0024: /* 'BrtFRTEnd' */
  11095. pass = false; break;
  11096. case 0x0025: /* 'BrtACBegin' */ break;
  11097. case 0x0026: /* 'BrtACEnd' */ break;
  11098. default:
  11099. if(R.T){/* empty */}
  11100. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  11101. }
  11102. });
  11103. return out;
  11104. }
  11105. function write_comments_bin(data) {
  11106. var ba = buf_array();
  11107. var iauthor = [];
  11108. write_record(ba, 0x0274 /* BrtBeginComments */);
  11109. write_record(ba, 0x0276 /* BrtBeginCommentAuthors */);
  11110. data.forEach(function(comment) {
  11111. comment[1].forEach(function(c) {
  11112. if(iauthor.indexOf(c.a) > -1) return;
  11113. iauthor.push(c.a.slice(0,54));
  11114. write_record(ba, 0x0278 /* BrtCommentAuthor */, write_BrtCommentAuthor(c.a));
  11115. });
  11116. });
  11117. write_record(ba, 0x0277 /* BrtEndCommentAuthors */);
  11118. write_record(ba, 0x0279 /* BrtBeginCommentList */);
  11119. data.forEach(function(comment) {
  11120. comment[1].forEach(function(c) {
  11121. c.iauthor = iauthor.indexOf(c.a);
  11122. var range = {s:decode_cell(comment[0]),e:decode_cell(comment[0])};
  11123. write_record(ba, 0x027B /* BrtBeginComment */, write_BrtBeginComment([range, c]));
  11124. if(c.t && c.t.length > 0) write_record(ba, 0x027D /* BrtCommentText */, write_BrtCommentText(c));
  11125. write_record(ba, 0x027C /* BrtEndComment */);
  11126. delete c.iauthor;
  11127. });
  11128. });
  11129. write_record(ba, 0x027A /* BrtEndCommentList */);
  11130. write_record(ba, 0x0275 /* BrtEndComments */);
  11131. return ba.end();
  11132. }
  11133. var CT_VBA = "application/vnd.ms-office.vbaProject";
  11134. function make_vba_xls(cfb) {
  11135. var newcfb = CFB.utils.cfb_new({ root: "R" });
  11136. cfb.FullPaths.forEach(function(p, i) {
  11137. if (p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/))
  11138. return;
  11139. var newpath = p.replace(/^[^\/]*/, "R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
  11140. CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  11141. });
  11142. return CFB.write(newcfb);
  11143. }
  11144. function fill_vba_xls(cfb, vba) {
  11145. vba.FullPaths.forEach(function(p, i) {
  11146. if (i == 0)
  11147. return;
  11148. var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
  11149. if (newpath.slice(-1) !== "/")
  11150. CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  11151. });
  11152. }
  11153. var VBAFMTS = ["xlsb", "xlsm", "xlam", "biff8", "xla"];
  11154. /* macro and dialog sheet stubs */
  11155. function parse_ds_bin() { return {'!type':'dialog'}; }
  11156. function parse_ds_xml() { return {'!type':'dialog'}; }
  11157. function parse_ms_bin() { return {'!type':'macro'}; }
  11158. function parse_ms_xml() { return {'!type':'macro'}; }
  11159. /* TODO: it will be useful to parse the function str */
  11160. var rc_to_a1 = (function(){
  11161. var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  11162. var rcbase = ({r:0,c:0});
  11163. function rcfunc($$,$1,$2,$3) {
  11164. var cRel = false, rRel = false;
  11165. if($2.length == 0) rRel = true;
  11166. else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }
  11167. if($3.length == 0) cRel = true;
  11168. else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }
  11169. var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;
  11170. if(cRel) C += rcbase.c; else --C;
  11171. if(rRel) R += rcbase.r; else --R;
  11172. return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
  11173. }
  11174. return function rc_to_a1(fstr, base) {
  11175. rcbase = base;
  11176. return fstr.replace(rcregex, rcfunc);
  11177. };
  11178. })();
  11179. 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;
  11180. var a1_to_rc = (function(){
  11181. return function a1_to_rc(fstr, base) {
  11182. return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  11183. var c = decode_col($3) - ($2 ? 0 : base.c);
  11184. var r = decode_row($5) - ($4 ? 0 : base.r);
  11185. var R = (r == 0 ? "" : !$4 ? "[" + r + "]" : (r+1));
  11186. var C = (c == 0 ? "" : !$2 ? "[" + c + "]" : (c+1));
  11187. return $1 + "R" + R + "C" + C;
  11188. });
  11189. };
  11190. })();
  11191. /* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
  11192. function shift_formula_str(f, delta) {
  11193. return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  11194. return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
  11195. });
  11196. }
  11197. function shift_formula_xlsx(f, range, cell) {
  11198. var r = decode_range(range), s = r.s, c = decode_cell(cell);
  11199. var delta = {r:c.r - s.r, c:c.c - s.c};
  11200. return shift_formula_str(f, delta);
  11201. }
  11202. /* TODO: parse formula */
  11203. function fuzzyfmla(f) {
  11204. if(f.length == 1) return false;
  11205. return true;
  11206. }
  11207. function _xlfn(f) {
  11208. return f.replace(/_xlfn\./g,"");
  11209. }
  11210. function parseread1(blob) { blob.l+=1; return; }
  11211. /* [MS-XLS] 2.5.51 */
  11212. function parse_ColRelU(blob, length) {
  11213. var c = blob.read_shift(length == 1 ? 1 : 2);
  11214. return [c & 0x3FFF, (c >> 14) & 1, (c >> 15) & 1];
  11215. }
  11216. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.89 */
  11217. function parse_RgceArea(blob, length, opts) {
  11218. var w = 2;
  11219. if(opts) {
  11220. if(opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
  11221. else if(opts.biff == 12) w = 4;
  11222. }
  11223. var r=blob.read_shift(w), R=blob.read_shift(w);
  11224. var c=parse_ColRelU(blob, 2);
  11225. var C=parse_ColRelU(blob, 2);
  11226. 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]} };
  11227. }
  11228. /* BIFF 2-5 encodes flags in the row field */
  11229. function parse_RgceArea_BIFF2(blob) {
  11230. var r=parse_ColRelU(blob, 2), R=parse_ColRelU(blob, 2);
  11231. var c=blob.read_shift(1);
  11232. var C=blob.read_shift(1);
  11233. 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]} };
  11234. }
  11235. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.90 */
  11236. function parse_RgceAreaRel(blob, length, opts) {
  11237. if(opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
  11238. var r=blob.read_shift(opts.biff == 12 ? 4 : 2), R=blob.read_shift(opts.biff == 12 ? 4 : 2);
  11239. var c=parse_ColRelU(blob, 2);
  11240. var C=parse_ColRelU(blob, 2);
  11241. 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]} };
  11242. }
  11243. /* [MS-XLS] 2.5.198.109 ; [MS-XLSB] 2.5.97.91 */
  11244. function parse_RgceLoc(blob, length, opts) {
  11245. if(opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
  11246. var r = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
  11247. var c = parse_ColRelU(blob, 2);
  11248. return {r:r, c:c[0], cRel:c[1], rRel:c[2]};
  11249. }
  11250. function parse_RgceLoc_BIFF2(blob) {
  11251. var r = parse_ColRelU(blob, 2);
  11252. var c = blob.read_shift(1);
  11253. return {r:r[0], c:c, cRel:r[1], rRel:r[2]};
  11254. }
  11255. /* [MS-XLS] 2.5.198.107, 2.5.47 */
  11256. function parse_RgceElfLoc(blob) {
  11257. var r = blob.read_shift(2);
  11258. var c = blob.read_shift(2);
  11259. return {r:r, c:c & 0xFF, fQuoted:!!(c & 0x4000), cRel:c>>15, rRel:c>>15 };
  11260. }
  11261. /* [MS-XLS] 2.5.198.111 ; [MS-XLSB] 2.5.97.92 TODO */
  11262. function parse_RgceLocRel(blob, length, opts) {
  11263. var biff = opts && opts.biff ? opts.biff : 8;
  11264. if(biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
  11265. var r = blob.read_shift(biff >= 12 ? 4 : 2);
  11266. var cl = blob.read_shift(2);
  11267. var cRel = (cl & 0x4000) >> 14, rRel = (cl & 0x8000) >> 15;
  11268. cl &= 0x3FFF;
  11269. if(rRel == 1) while(r > 0x7FFFF) r -= 0x100000;
  11270. if(cRel == 1) while(cl > 0x1FFF) cl = cl - 0x4000;
  11271. return {r:r,c:cl,cRel:cRel,rRel:rRel};
  11272. }
  11273. function parse_RgceLocRel_BIFF2(blob) {
  11274. var rl = blob.read_shift(2);
  11275. var c = blob.read_shift(1);
  11276. var rRel = (rl & 0x8000) >> 15, cRel = (rl & 0x4000) >> 14;
  11277. rl &= 0x3FFF;
  11278. if(rRel == 1 && rl >= 0x2000) rl = rl - 0x4000;
  11279. if(cRel == 1 && c >= 0x80) c = c - 0x100;
  11280. return {r:rl,c:c,cRel:cRel,rRel:rRel};
  11281. }
  11282. /* [MS-XLS] 2.5.198.27 ; [MS-XLSB] 2.5.97.18 */
  11283. function parse_PtgArea(blob, length, opts) {
  11284. var type = (blob[blob.l++] & 0x60) >> 5;
  11285. var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
  11286. return [type, area];
  11287. }
  11288. /* [MS-XLS] 2.5.198.28 ; [MS-XLSB] 2.5.97.19 */
  11289. function parse_PtgArea3d(blob, length, opts) {
  11290. var type = (blob[blob.l++] & 0x60) >> 5;
  11291. var ixti = blob.read_shift(2, 'i');
  11292. var w = 8;
  11293. if(opts) switch(opts.biff) {
  11294. case 5: blob.l += 12; w = 6; break;
  11295. case 12: w = 12; break;
  11296. }
  11297. var area = parse_RgceArea(blob, w, opts);
  11298. return [type, ixti, area];
  11299. }
  11300. /* [MS-XLS] 2.5.198.29 ; [MS-XLSB] 2.5.97.20 */
  11301. function parse_PtgAreaErr(blob, length, opts) {
  11302. var type = (blob[blob.l++] & 0x60) >> 5;
  11303. blob.l += opts && (opts.biff > 8) ? 12 : (opts.biff < 8 ? 6 : 8);
  11304. return [type];
  11305. }
  11306. /* [MS-XLS] 2.5.198.30 ; [MS-XLSB] 2.5.97.21 */
  11307. function parse_PtgAreaErr3d(blob, length, opts) {
  11308. var type = (blob[blob.l++] & 0x60) >> 5;
  11309. var ixti = blob.read_shift(2);
  11310. var w = 8;
  11311. if(opts) switch(opts.biff) {
  11312. case 5: blob.l += 12; w = 6; break;
  11313. case 12: w = 12; break;
  11314. }
  11315. blob.l += w;
  11316. return [type, ixti];
  11317. }
  11318. /* [MS-XLS] 2.5.198.31 ; [MS-XLSB] 2.5.97.22 */
  11319. function parse_PtgAreaN(blob, length, opts) {
  11320. var type = (blob[blob.l++] & 0x60) >> 5;
  11321. var area = parse_RgceAreaRel(blob, length - 1, opts);
  11322. return [type, area];
  11323. }
  11324. /* [MS-XLS] 2.5.198.32 ; [MS-XLSB] 2.5.97.23 */
  11325. function parse_PtgArray(blob, length, opts) {
  11326. var type = (blob[blob.l++] & 0x60) >> 5;
  11327. blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
  11328. return [type];
  11329. }
  11330. /* [MS-XLS] 2.5.198.33 ; [MS-XLSB] 2.5.97.24 */
  11331. function parse_PtgAttrBaxcel(blob) {
  11332. var bitSemi = blob[blob.l+1] & 0x01; /* 1 = volatile */
  11333. var bitBaxcel = 1;
  11334. blob.l += 4;
  11335. return [bitSemi, bitBaxcel];
  11336. }
  11337. /* [MS-XLS] 2.5.198.34 ; [MS-XLSB] 2.5.97.25 */
  11338. function parse_PtgAttrChoose(blob, length, opts) {
  11339. blob.l +=2;
  11340. var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11341. var o = [];
  11342. /* offset is 1 less than the number of elements */
  11343. for(var i = 0; i <= offset; ++i) o.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
  11344. return o;
  11345. }
  11346. /* [MS-XLS] 2.5.198.35 ; [MS-XLSB] 2.5.97.26 */
  11347. function parse_PtgAttrGoto(blob, length, opts) {
  11348. var bitGoto = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11349. blob.l += 2;
  11350. return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  11351. }
  11352. /* [MS-XLS] 2.5.198.36 ; [MS-XLSB] 2.5.97.27 */
  11353. function parse_PtgAttrIf(blob, length, opts) {
  11354. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11355. blob.l += 2;
  11356. return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  11357. }
  11358. /* [MS-XLSB] 2.5.97.28 */
  11359. function parse_PtgAttrIfError(blob) {
  11360. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11361. blob.l += 2;
  11362. return [bitIf, blob.read_shift(2)];
  11363. }
  11364. /* [MS-XLS] 2.5.198.37 ; [MS-XLSB] 2.5.97.29 */
  11365. function parse_PtgAttrSemi(blob, length, opts) {
  11366. var bitSemi = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  11367. blob.l += opts && opts.biff == 2 ? 3 : 4;
  11368. return [bitSemi];
  11369. }
  11370. /* [MS-XLS] 2.5.198.40 ; [MS-XLSB] 2.5.97.32 */
  11371. function parse_PtgAttrSpaceType(blob) {
  11372. var type = blob.read_shift(1), cch = blob.read_shift(1);
  11373. return [type, cch];
  11374. }
  11375. /* [MS-XLS] 2.5.198.38 ; [MS-XLSB] 2.5.97.30 */
  11376. function parse_PtgAttrSpace(blob) {
  11377. blob.read_shift(2);
  11378. return parse_PtgAttrSpaceType(blob, 2);
  11379. }
  11380. /* [MS-XLS] 2.5.198.39 ; [MS-XLSB] 2.5.97.31 */
  11381. function parse_PtgAttrSpaceSemi(blob) {
  11382. blob.read_shift(2);
  11383. return parse_PtgAttrSpaceType(blob, 2);
  11384. }
  11385. /* [MS-XLS] 2.5.198.84 ; [MS-XLSB] 2.5.97.68 TODO */
  11386. function parse_PtgRef(blob, length, opts) {
  11387. //var ptg = blob[blob.l] & 0x1F;
  11388. var type = (blob[blob.l] & 0x60)>>5;
  11389. blob.l += 1;
  11390. var loc = parse_RgceLoc(blob, 0, opts);
  11391. return [type, loc];
  11392. }
  11393. /* [MS-XLS] 2.5.198.88 ; [MS-XLSB] 2.5.97.72 TODO */
  11394. function parse_PtgRefN(blob, length, opts) {
  11395. var type = (blob[blob.l] & 0x60)>>5;
  11396. blob.l += 1;
  11397. var loc = parse_RgceLocRel(blob, 0, opts);
  11398. return [type, loc];
  11399. }
  11400. /* [MS-XLS] 2.5.198.85 ; [MS-XLSB] 2.5.97.69 TODO */
  11401. function parse_PtgRef3d(blob, length, opts) {
  11402. var type = (blob[blob.l] & 0x60)>>5;
  11403. blob.l += 1;
  11404. var ixti = blob.read_shift(2); // XtiIndex
  11405. if(opts && opts.biff == 5) blob.l += 12;
  11406. var loc = parse_RgceLoc(blob, 0, opts); // TODO: or RgceLocRel
  11407. return [type, ixti, loc];
  11408. }
  11409. /* [MS-XLS] 2.5.198.62 ; [MS-XLSB] 2.5.97.45 TODO */
  11410. function parse_PtgFunc(blob, length, opts) {
  11411. //var ptg = blob[blob.l] & 0x1F;
  11412. var type = (blob[blob.l] & 0x60)>>5;
  11413. blob.l += 1;
  11414. var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
  11415. return [FtabArgc[iftab], Ftab[iftab], type];
  11416. }
  11417. /* [MS-XLS] 2.5.198.63 ; [MS-XLSB] 2.5.97.46 TODO */
  11418. function parse_PtgFuncVar(blob, length, opts) {
  11419. var type = blob[blob.l++];
  11420. var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [(type == 0x58 ? -1 : 0), blob.read_shift(1)]: parsetab(blob);
  11421. return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
  11422. }
  11423. function parsetab(blob) {
  11424. return [blob[blob.l+1]>>7, blob.read_shift(2) & 0x7FFF];
  11425. }
  11426. /* [MS-XLS] 2.5.198.41 ; [MS-XLSB] 2.5.97.33 */
  11427. function parse_PtgAttrSum(blob, length, opts) {
  11428. blob.l += opts && opts.biff == 2 ? 3 : 4; return;
  11429. }
  11430. /* [MS-XLS] 2.5.198.58 ; [MS-XLSB] 2.5.97.40 */
  11431. function parse_PtgExp(blob, length, opts) {
  11432. blob.l++;
  11433. if(opts && opts.biff == 12) return [blob.read_shift(4, 'i'), 0];
  11434. var row = blob.read_shift(2);
  11435. var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11436. return [row, col];
  11437. }
  11438. /* [MS-XLS] 2.5.198.57 ; [MS-XLSB] 2.5.97.39 */
  11439. function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }
  11440. /* [MS-XLS] 2.5.198.66 ; [MS-XLSB] 2.5.97.49 */
  11441. function parse_PtgInt(blob) { blob.l++; return blob.read_shift(2); }
  11442. /* [MS-XLS] 2.5.198.42 ; [MS-XLSB] 2.5.97.34 */
  11443. function parse_PtgBool(blob) { blob.l++; return blob.read_shift(1)!==0;}
  11444. /* [MS-XLS] 2.5.198.79 ; [MS-XLSB] 2.5.97.63 */
  11445. function parse_PtgNum(blob) { blob.l++; return parse_Xnum(blob, 8); }
  11446. /* [MS-XLS] 2.5.198.89 ; [MS-XLSB] 2.5.97.74 */
  11447. function parse_PtgStr(blob, length, opts) { blob.l++; return parse_ShortXLUnicodeString(blob, length-1, opts); }
  11448. /* [MS-XLS] 2.5.192.112 + 2.5.192.11{3,4,5,6,7} */
  11449. /* [MS-XLSB] 2.5.97.93 + 2.5.97.9{4,5,6,7} */
  11450. function parse_SerAr(blob, biff) {
  11451. var val = [blob.read_shift(1)];
  11452. if(biff == 12) switch(val[0]) {
  11453. case 0x02: val[0] = 0x04; break; /* SerBool */
  11454. case 0x04: val[0] = 0x10; break; /* SerErr */
  11455. case 0x00: val[0] = 0x01; break; /* SerNum */
  11456. case 0x01: val[0] = 0x02; break; /* SerStr */
  11457. }
  11458. switch(val[0]) {
  11459. case 0x04: /* SerBool -- boolean */
  11460. val[1] = parsebool(blob, 1) ? 'TRUE' : 'FALSE';
  11461. if(biff != 12) blob.l += 7; break;
  11462. case 0x25: /* appears to be an alias */
  11463. case 0x10: /* SerErr -- error */
  11464. val[1] = BErr[blob[blob.l]];
  11465. blob.l += ((biff == 12) ? 4 : 8); break;
  11466. case 0x00: /* SerNil -- honestly, I'm not sure how to reproduce this */
  11467. blob.l += 8; break;
  11468. case 0x01: /* SerNum -- Xnum */
  11469. val[1] = parse_Xnum(blob, 8); break;
  11470. case 0x02: /* SerStr -- XLUnicodeString (<256 chars) */
  11471. val[1] = parse_XLUnicodeString2(blob, 0, {biff:biff > 0 && biff < 8 ? 2 : biff}); break;
  11472. default: throw new Error("Bad SerAr: " + val[0]); /* Unreachable */
  11473. }
  11474. return val;
  11475. }
  11476. /* [MS-XLS] 2.5.198.61 ; [MS-XLSB] 2.5.97.44 */
  11477. function parse_PtgExtraMem(blob, cce, opts) {
  11478. var count = blob.read_shift((opts.biff == 12) ? 4 : 2);
  11479. var out = [];
  11480. for(var i = 0; i != count; ++i) out.push(((opts.biff == 12) ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
  11481. return out;
  11482. }
  11483. /* [MS-XLS] 2.5.198.59 ; [MS-XLSB] 2.5.97.41 */
  11484. function parse_PtgExtraArray(blob, length, opts) {
  11485. var rows = 0, cols = 0;
  11486. if(opts.biff == 12) {
  11487. rows = blob.read_shift(4); // DRw
  11488. cols = blob.read_shift(4); // DCol
  11489. } else {
  11490. cols = 1 + blob.read_shift(1); //DColByteU
  11491. rows = 1 + blob.read_shift(2); //DRw
  11492. }
  11493. if(opts.biff >= 2 && opts.biff < 8) { --rows; if(--cols == 0) cols = 0x100; }
  11494. // $FlowIgnore
  11495. for(var i = 0, o = []; i != rows && (o[i] = []); ++i)
  11496. for(var j = 0; j != cols; ++j) o[i][j] = parse_SerAr(blob, opts.biff);
  11497. return o;
  11498. }
  11499. /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 */
  11500. function parse_PtgName(blob, length, opts) {
  11501. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11502. var w = (!opts || (opts.biff >= 8)) ? 4 : 2;
  11503. var nameindex = blob.read_shift(w);
  11504. switch(opts.biff) {
  11505. case 2: blob.l += 5; break;
  11506. case 3: case 4: blob.l += 8; break;
  11507. case 5: blob.l += 12; break;
  11508. }
  11509. return [type, 0, nameindex];
  11510. }
  11511. /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 */
  11512. function parse_PtgNameX(blob, length, opts) {
  11513. if(opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
  11514. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11515. var ixti = blob.read_shift(2); // XtiIndex
  11516. var nameindex = blob.read_shift(4);
  11517. return [type, ixti, nameindex];
  11518. }
  11519. function parse_PtgNameX_BIFF5(blob) {
  11520. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11521. var ixti = blob.read_shift(2, 'i'); // XtiIndex
  11522. blob.l += 8;
  11523. var nameindex = blob.read_shift(2);
  11524. blob.l += 12;
  11525. return [type, ixti, nameindex];
  11526. }
  11527. /* [MS-XLS] 2.5.198.70 ; [MS-XLSB] 2.5.97.54 */
  11528. function parse_PtgMemArea(blob, length, opts) {
  11529. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11530. blob.l += (opts && opts.biff == 2 ? 3 : 4);
  11531. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11532. return [type, cce];
  11533. }
  11534. /* [MS-XLS] 2.5.198.72 ; [MS-XLSB] 2.5.97.56 */
  11535. function parse_PtgMemFunc(blob, length, opts) {
  11536. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11537. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  11538. return [type, cce];
  11539. }
  11540. /* [MS-XLS] 2.5.198.86 ; [MS-XLSB] 2.5.97.69 */
  11541. function parse_PtgRefErr(blob, length, opts) {
  11542. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11543. blob.l += 4;
  11544. if(opts.biff < 8) blob.l--;
  11545. if(opts.biff == 12) blob.l += 2;
  11546. return [type];
  11547. }
  11548. /* [MS-XLS] 2.5.198.87 ; [MS-XLSB] 2.5.97.71 */
  11549. function parse_PtgRefErr3d(blob, length, opts) {
  11550. var type = (blob[blob.l++] & 0x60) >> 5;
  11551. var ixti = blob.read_shift(2);
  11552. var w = 4;
  11553. if(opts) switch(opts.biff) {
  11554. case 5: w = 15; break;
  11555. case 12: w = 6; break;
  11556. }
  11557. blob.l += w;
  11558. return [type, ixti];
  11559. }
  11560. /* [MS-XLS] 2.5.198.71 ; [MS-XLSB] 2.5.97.55 */
  11561. var parse_PtgMemErr = parsenoop;
  11562. /* [MS-XLS] 2.5.198.73 ; [MS-XLSB] 2.5.97.57 */
  11563. var parse_PtgMemNoMem = parsenoop;
  11564. /* [MS-XLS] 2.5.198.92 */
  11565. var parse_PtgTbl = parsenoop;
  11566. function parse_PtgElfLoc(blob, length, opts) {
  11567. blob.l += 2;
  11568. return [parse_RgceElfLoc(blob, 4, opts)];
  11569. }
  11570. function parse_PtgElfNoop(blob) {
  11571. blob.l += 6;
  11572. return [];
  11573. }
  11574. /* [MS-XLS] 2.5.198.46 */
  11575. var parse_PtgElfCol = parse_PtgElfLoc;
  11576. /* [MS-XLS] 2.5.198.47 */
  11577. var parse_PtgElfColS = parse_PtgElfNoop;
  11578. /* [MS-XLS] 2.5.198.48 */
  11579. var parse_PtgElfColSV = parse_PtgElfNoop;
  11580. /* [MS-XLS] 2.5.198.49 */
  11581. var parse_PtgElfColV = parse_PtgElfLoc;
  11582. /* [MS-XLS] 2.5.198.50 */
  11583. function parse_PtgElfLel(blob) {
  11584. blob.l += 2;
  11585. return [parseuint16(blob), blob.read_shift(2) & 0x01];
  11586. }
  11587. /* [MS-XLS] 2.5.198.51 */
  11588. var parse_PtgElfRadical = parse_PtgElfLoc;
  11589. /* [MS-XLS] 2.5.198.52 */
  11590. var parse_PtgElfRadicalLel = parse_PtgElfLel;
  11591. /* [MS-XLS] 2.5.198.53 */
  11592. var parse_PtgElfRadicalS = parse_PtgElfNoop;
  11593. /* [MS-XLS] 2.5.198.54 */
  11594. var parse_PtgElfRw = parse_PtgElfLoc;
  11595. /* [MS-XLS] 2.5.198.55 */
  11596. var parse_PtgElfRwV = parse_PtgElfLoc;
  11597. /* [MS-XLSB] 2.5.97.52 TODO */
  11598. var PtgListRT = [
  11599. "Data",
  11600. "All",
  11601. "Headers",
  11602. "??",
  11603. "?Data2",
  11604. "??",
  11605. "?DataHeaders",
  11606. "??",
  11607. "Totals",
  11608. "??",
  11609. "??",
  11610. "??",
  11611. "?DataTotals",
  11612. "??",
  11613. "??",
  11614. "??",
  11615. "?Current"
  11616. ];
  11617. function parse_PtgList(blob) {
  11618. blob.l += 2;
  11619. var ixti = blob.read_shift(2);
  11620. var flags = blob.read_shift(2);
  11621. var idx = blob.read_shift(4);
  11622. var c = blob.read_shift(2);
  11623. var C = blob.read_shift(2);
  11624. var rt = PtgListRT[(flags >> 2) & 0x1F];
  11625. return {ixti: ixti, coltype:(flags&0x3), rt:rt, idx:idx, c:c, C:C};
  11626. }
  11627. /* [MS-XLS] 2.5.198.91 ; [MS-XLSB] 2.5.97.76 */
  11628. function parse_PtgSxName(blob) {
  11629. blob.l += 2;
  11630. return [blob.read_shift(4)];
  11631. }
  11632. /* [XLS] old spec */
  11633. function parse_PtgSheet(blob, length, opts) {
  11634. blob.l += 5;
  11635. blob.l += 2;
  11636. blob.l += (opts.biff == 2 ? 1 : 4);
  11637. return ["PTGSHEET"];
  11638. }
  11639. function parse_PtgEndSheet(blob, length, opts) {
  11640. blob.l += (opts.biff == 2 ? 4 : 5);
  11641. return ["PTGENDSHEET"];
  11642. }
  11643. function parse_PtgMemAreaN(blob) {
  11644. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11645. var cce = blob.read_shift(2);
  11646. return [type, cce];
  11647. }
  11648. function parse_PtgMemNoMemN(blob) {
  11649. var type = (blob.read_shift(1) >>> 5) & 0x03;
  11650. var cce = blob.read_shift(2);
  11651. return [type, cce];
  11652. }
  11653. function parse_PtgAttrNoop(blob) {
  11654. blob.l += 4;
  11655. return [0, 0];
  11656. }
  11657. /* [MS-XLS] 2.5.198.25 ; [MS-XLSB] 2.5.97.16 */
  11658. var PtgTypes = {
  11659. 0x01: { n:'PtgExp', f:parse_PtgExp },
  11660. 0x02: { n:'PtgTbl', f:parse_PtgTbl },
  11661. 0x03: { n:'PtgAdd', f:parseread1 },
  11662. 0x04: { n:'PtgSub', f:parseread1 },
  11663. 0x05: { n:'PtgMul', f:parseread1 },
  11664. 0x06: { n:'PtgDiv', f:parseread1 },
  11665. 0x07: { n:'PtgPower', f:parseread1 },
  11666. 0x08: { n:'PtgConcat', f:parseread1 },
  11667. 0x09: { n:'PtgLt', f:parseread1 },
  11668. 0x0A: { n:'PtgLe', f:parseread1 },
  11669. 0x0B: { n:'PtgEq', f:parseread1 },
  11670. 0x0C: { n:'PtgGe', f:parseread1 },
  11671. 0x0D: { n:'PtgGt', f:parseread1 },
  11672. 0x0E: { n:'PtgNe', f:parseread1 },
  11673. 0x0F: { n:'PtgIsect', f:parseread1 },
  11674. 0x10: { n:'PtgUnion', f:parseread1 },
  11675. 0x11: { n:'PtgRange', f:parseread1 },
  11676. 0x12: { n:'PtgUplus', f:parseread1 },
  11677. 0x13: { n:'PtgUminus', f:parseread1 },
  11678. 0x14: { n:'PtgPercent', f:parseread1 },
  11679. 0x15: { n:'PtgParen', f:parseread1 },
  11680. 0x16: { n:'PtgMissArg', f:parseread1 },
  11681. 0x17: { n:'PtgStr', f:parse_PtgStr },
  11682. 0x1A: { n:'PtgSheet', f:parse_PtgSheet },
  11683. 0x1B: { n:'PtgEndSheet', f:parse_PtgEndSheet },
  11684. 0x1C: { n:'PtgErr', f:parse_PtgErr },
  11685. 0x1D: { n:'PtgBool', f:parse_PtgBool },
  11686. 0x1E: { n:'PtgInt', f:parse_PtgInt },
  11687. 0x1F: { n:'PtgNum', f:parse_PtgNum },
  11688. 0x20: { n:'PtgArray', f:parse_PtgArray },
  11689. 0x21: { n:'PtgFunc', f:parse_PtgFunc },
  11690. 0x22: { n:'PtgFuncVar', f:parse_PtgFuncVar },
  11691. 0x23: { n:'PtgName', f:parse_PtgName },
  11692. 0x24: { n:'PtgRef', f:parse_PtgRef },
  11693. 0x25: { n:'PtgArea', f:parse_PtgArea },
  11694. 0x26: { n:'PtgMemArea', f:parse_PtgMemArea },
  11695. 0x27: { n:'PtgMemErr', f:parse_PtgMemErr },
  11696. 0x28: { n:'PtgMemNoMem', f:parse_PtgMemNoMem },
  11697. 0x29: { n:'PtgMemFunc', f:parse_PtgMemFunc },
  11698. 0x2A: { n:'PtgRefErr', f:parse_PtgRefErr },
  11699. 0x2B: { n:'PtgAreaErr', f:parse_PtgAreaErr },
  11700. 0x2C: { n:'PtgRefN', f:parse_PtgRefN },
  11701. 0x2D: { n:'PtgAreaN', f:parse_PtgAreaN },
  11702. 0x2E: { n:'PtgMemAreaN', f:parse_PtgMemAreaN },
  11703. 0x2F: { n:'PtgMemNoMemN', f:parse_PtgMemNoMemN },
  11704. 0x39: { n:'PtgNameX', f:parse_PtgNameX },
  11705. 0x3A: { n:'PtgRef3d', f:parse_PtgRef3d },
  11706. 0x3B: { n:'PtgArea3d', f:parse_PtgArea3d },
  11707. 0x3C: { n:'PtgRefErr3d', f:parse_PtgRefErr3d },
  11708. 0x3D: { n:'PtgAreaErr3d', f:parse_PtgAreaErr3d },
  11709. 0xFF: {}
  11710. };
  11711. /* These are duplicated in the PtgTypes table */
  11712. var PtgDupes = {
  11713. 0x40: 0x20, 0x60: 0x20,
  11714. 0x41: 0x21, 0x61: 0x21,
  11715. 0x42: 0x22, 0x62: 0x22,
  11716. 0x43: 0x23, 0x63: 0x23,
  11717. 0x44: 0x24, 0x64: 0x24,
  11718. 0x45: 0x25, 0x65: 0x25,
  11719. 0x46: 0x26, 0x66: 0x26,
  11720. 0x47: 0x27, 0x67: 0x27,
  11721. 0x48: 0x28, 0x68: 0x28,
  11722. 0x49: 0x29, 0x69: 0x29,
  11723. 0x4A: 0x2A, 0x6A: 0x2A,
  11724. 0x4B: 0x2B, 0x6B: 0x2B,
  11725. 0x4C: 0x2C, 0x6C: 0x2C,
  11726. 0x4D: 0x2D, 0x6D: 0x2D,
  11727. 0x4E: 0x2E, 0x6E: 0x2E,
  11728. 0x4F: 0x2F, 0x6F: 0x2F,
  11729. 0x58: 0x22, 0x78: 0x22,
  11730. 0x59: 0x39, 0x79: 0x39,
  11731. 0x5A: 0x3A, 0x7A: 0x3A,
  11732. 0x5B: 0x3B, 0x7B: 0x3B,
  11733. 0x5C: 0x3C, 0x7C: 0x3C,
  11734. 0x5D: 0x3D, 0x7D: 0x3D
  11735. };
  11736. var Ptg18 = {
  11737. 0x01: { n:'PtgElfLel', f:parse_PtgElfLel },
  11738. 0x02: { n:'PtgElfRw', f:parse_PtgElfRw },
  11739. 0x03: { n:'PtgElfCol', f:parse_PtgElfCol },
  11740. 0x06: { n:'PtgElfRwV', f:parse_PtgElfRwV },
  11741. 0x07: { n:'PtgElfColV', f:parse_PtgElfColV },
  11742. 0x0A: { n:'PtgElfRadical', f:parse_PtgElfRadical },
  11743. 0x0B: { n:'PtgElfRadicalS', f:parse_PtgElfRadicalS },
  11744. 0x0D: { n:'PtgElfColS', f:parse_PtgElfColS },
  11745. 0x0F: { n:'PtgElfColSV', f:parse_PtgElfColSV },
  11746. 0x10: { n:'PtgElfRadicalLel', f:parse_PtgElfRadicalLel },
  11747. 0x19: { n:'PtgList', f:parse_PtgList },
  11748. 0x1D: { n:'PtgSxName', f:parse_PtgSxName },
  11749. 0xFF: {}
  11750. };
  11751. var Ptg19 = {
  11752. 0x00: { n:'PtgAttrNoop', f:parse_PtgAttrNoop },
  11753. 0x01: { n:'PtgAttrSemi', f:parse_PtgAttrSemi },
  11754. 0x02: { n:'PtgAttrIf', f:parse_PtgAttrIf },
  11755. 0x04: { n:'PtgAttrChoose', f:parse_PtgAttrChoose },
  11756. 0x08: { n:'PtgAttrGoto', f:parse_PtgAttrGoto },
  11757. 0x10: { n:'PtgAttrSum', f:parse_PtgAttrSum },
  11758. 0x20: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
  11759. 0x21: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
  11760. 0x40: { n:'PtgAttrSpace', f:parse_PtgAttrSpace },
  11761. 0x41: { n:'PtgAttrSpaceSemi', f:parse_PtgAttrSpaceSemi },
  11762. 0x80: { n:'PtgAttrIfError', f:parse_PtgAttrIfError },
  11763. 0xFF: {}
  11764. };
  11765. /* [MS-XLS] 2.5.198.103 ; [MS-XLSB] 2.5.97.87 */
  11766. function parse_RgbExtra(blob, length, rgce, opts) {
  11767. if(opts.biff < 8) return parsenoop(blob, length);
  11768. var target = blob.l + length;
  11769. var o = [];
  11770. for(var i = 0; i !== rgce.length; ++i) {
  11771. switch(rgce[i][0]) {
  11772. case 'PtgArray': /* PtgArray -> PtgExtraArray */
  11773. rgce[i][1] = parse_PtgExtraArray(blob, 0, opts);
  11774. o.push(rgce[i][1]);
  11775. break;
  11776. case 'PtgMemArea': /* PtgMemArea -> PtgExtraMem */
  11777. rgce[i][2] = parse_PtgExtraMem(blob, rgce[i][1], opts);
  11778. o.push(rgce[i][2]);
  11779. break;
  11780. case 'PtgExp': /* PtgExp -> PtgExtraCol */
  11781. if(opts && opts.biff == 12) {
  11782. rgce[i][1][1] = blob.read_shift(4);
  11783. o.push(rgce[i][1]);
  11784. } break;
  11785. case 'PtgList': /* TODO: PtgList -> PtgExtraList */
  11786. case 'PtgElfRadicalS': /* TODO: PtgElfRadicalS -> PtgExtraElf */
  11787. case 'PtgElfColS': /* TODO: PtgElfColS -> PtgExtraElf */
  11788. case 'PtgElfColSV': /* TODO: PtgElfColSV -> PtgExtraElf */
  11789. throw "Unsupported " + rgce[i][0];
  11790. default: break;
  11791. }
  11792. }
  11793. length = target - blob.l;
  11794. /* note: this is technically an error but Excel disregards */
  11795. //if(target !== blob.l && blob.l !== target - length) throw new Error(target + " != " + blob.l);
  11796. if(length !== 0) o.push(parsenoop(blob, length));
  11797. return o;
  11798. }
  11799. /* [MS-XLS] 2.5.198.104 ; [MS-XLSB] 2.5.97.88 */
  11800. function parse_Rgce(blob, length, opts) {
  11801. var target = blob.l + length;
  11802. var R, id, ptgs = [];
  11803. while(target != blob.l) {
  11804. length = target - blob.l;
  11805. id = blob[blob.l];
  11806. R = PtgTypes[id] || PtgTypes[PtgDupes[id]];
  11807. if(id === 0x18 || id === 0x19) R = (id === 0x18 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
  11808. if(!R || !R.f) { /*ptgs.push*/(parsenoop(blob, length)); }
  11809. else { ptgs.push([R.n, R.f(blob, length, opts)]); }
  11810. }
  11811. return ptgs;
  11812. }
  11813. function stringify_array(f) {
  11814. var o = [];
  11815. for(var i = 0; i < f.length; ++i) {
  11816. var x = f[i], r = [];
  11817. for(var j = 0; j < x.length; ++j) {
  11818. var y = x[j];
  11819. if(y) switch(y[0]) {
  11820. // TODO: handle embedded quotes
  11821. case 0x02:
  11822. r.push('"' + y[1].replace(/"/g,'""') + '"'); break;
  11823. default: r.push(y[1]);
  11824. } else r.push("");
  11825. }
  11826. o.push(r.join(","));
  11827. }
  11828. return o.join(";");
  11829. }
  11830. /* [MS-XLS] 2.2.2 ; [MS-XLSB] 2.2.2 TODO */
  11831. var PtgBinOp = {
  11832. PtgAdd: "+",
  11833. PtgConcat: "&",
  11834. PtgDiv: "/",
  11835. PtgEq: "=",
  11836. PtgGe: ">=",
  11837. PtgGt: ">",
  11838. PtgLe: "<=",
  11839. PtgLt: "<",
  11840. PtgMul: "*",
  11841. PtgNe: "<>",
  11842. PtgPower: "^",
  11843. PtgSub: "-"
  11844. };
  11845. // List of invalid characters needs to be tested further
  11846. function formula_quote_sheet_name(sname, opts) {
  11847. if(!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
  11848. if (/[^\w\u4E00-\u9FFF\u3040-\u30FF]/.test(sname)) return "'" + sname + "'";
  11849. return sname;
  11850. }
  11851. function get_ixti_raw(supbooks, ixti, opts) {
  11852. if(!supbooks) return "SH33TJSERR0";
  11853. if(opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
  11854. if(!supbooks.XTI) return "SH33TJSERR6";
  11855. var XTI = supbooks.XTI[ixti];
  11856. if(opts.biff < 8) {
  11857. if(ixti > 10000) ixti-= 65536;
  11858. if(ixti < 0) ixti = -ixti;
  11859. return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
  11860. }
  11861. if(!XTI) return "SH33TJSERR1";
  11862. var o = "";
  11863. if(opts.biff > 8) switch(supbooks[XTI[0]][0]) {
  11864. case 0x0165: /* 'BrtSupSelf' */
  11865. o = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
  11866. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  11867. case 0x0166: /* 'BrtSupSame' */
  11868. if(opts.SID != null) return supbooks.SheetNames[opts.SID];
  11869. return "SH33TJSSAME" + supbooks[XTI[0]][0];
  11870. case 0x0163: /* 'BrtSupBookSrc' */
  11871. /* falls through */
  11872. default: return "SH33TJSSRC" + supbooks[XTI[0]][0];
  11873. }
  11874. switch(supbooks[XTI[0]][0][0]) {
  11875. case 0x0401:
  11876. o = XTI[1] == -1 ? "#REF" : (supbooks.SheetNames[XTI[1]] || "SH33TJSERR3");
  11877. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  11878. case 0x3A01: return supbooks[XTI[0]].slice(1).map(function(name) { return name.Name; }).join(";;"); //return "SH33TJSERR8";
  11879. default:
  11880. if(!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
  11881. o = XTI[1] == -1 ? "#REF" : (supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4");
  11882. return XTI[1] == XTI[2] ? o : o + ":" + supbooks[XTI[0]][0][3][XTI[2]];
  11883. }
  11884. }
  11885. function get_ixti(supbooks, ixti, opts) {
  11886. var ixtiraw = get_ixti_raw(supbooks, ixti, opts);
  11887. return ixtiraw == "#REF" ? ixtiraw : formula_quote_sheet_name(ixtiraw, opts);
  11888. }
  11889. function stringify_formula(formula/*Array<any>*/, range, cell, supbooks, opts) {
  11890. var biff = (opts && opts.biff) || 8;
  11891. var _range = /*range != null ? range :*/ {s:{c:0, r:0},e:{c:0, r:0}};
  11892. var stack = [], e1, e2, c, ixti=0, nameidx=0, r, sname="";
  11893. if(!formula[0] || !formula[0][0]) return "";
  11894. var last_sp = -1, sp = "";
  11895. for(var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
  11896. var f = formula[0][ff];
  11897. switch(f[0]) {
  11898. case 'PtgUminus': /* [MS-XLS] 2.5.198.93 */
  11899. stack.push("-" + stack.pop()); break;
  11900. case 'PtgUplus': /* [MS-XLS] 2.5.198.95 */
  11901. stack.push("+" + stack.pop()); break;
  11902. case 'PtgPercent': /* [MS-XLS] 2.5.198.81 */
  11903. stack.push(stack.pop() + "%"); break;
  11904. case 'PtgAdd': /* [MS-XLS] 2.5.198.26 */
  11905. case 'PtgConcat': /* [MS-XLS] 2.5.198.43 */
  11906. case 'PtgDiv': /* [MS-XLS] 2.5.198.45 */
  11907. case 'PtgEq': /* [MS-XLS] 2.5.198.56 */
  11908. case 'PtgGe': /* [MS-XLS] 2.5.198.64 */
  11909. case 'PtgGt': /* [MS-XLS] 2.5.198.65 */
  11910. case 'PtgLe': /* [MS-XLS] 2.5.198.68 */
  11911. case 'PtgLt': /* [MS-XLS] 2.5.198.69 */
  11912. case 'PtgMul': /* [MS-XLS] 2.5.198.75 */
  11913. case 'PtgNe': /* [MS-XLS] 2.5.198.78 */
  11914. case 'PtgPower': /* [MS-XLS] 2.5.198.82 */
  11915. case 'PtgSub': /* [MS-XLS] 2.5.198.90 */
  11916. e1 = stack.pop(); e2 = stack.pop();
  11917. if(last_sp >= 0) {
  11918. switch(formula[0][last_sp][1][0]) {
  11919. case 0:
  11920. // $FlowIgnore
  11921. sp = fill(" ", formula[0][last_sp][1][1]); break;
  11922. case 1:
  11923. // $FlowIgnore
  11924. sp = fill("\r", formula[0][last_sp][1][1]); break;
  11925. default:
  11926. sp = "";
  11927. // $FlowIgnore
  11928. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  11929. }
  11930. e2 = e2 + sp;
  11931. last_sp = -1;
  11932. }
  11933. stack.push(e2+PtgBinOp[f[0]]+e1);
  11934. break;
  11935. case 'PtgIsect': /* [MS-XLS] 2.5.198.67 */
  11936. e1 = stack.pop(); e2 = stack.pop();
  11937. stack.push(e2+" "+e1);
  11938. break;
  11939. case 'PtgUnion': /* [MS-XLS] 2.5.198.94 */
  11940. e1 = stack.pop(); e2 = stack.pop();
  11941. stack.push(e2+","+e1);
  11942. break;
  11943. case 'PtgRange': /* [MS-XLS] 2.5.198.83 */
  11944. e1 = stack.pop(); e2 = stack.pop();
  11945. stack.push(e2+":"+e1);
  11946. break;
  11947. case 'PtgAttrChoose': /* [MS-XLS] 2.5.198.34 */
  11948. break;
  11949. case 'PtgAttrGoto': /* [MS-XLS] 2.5.198.35 */
  11950. break;
  11951. case 'PtgAttrIf': /* [MS-XLS] 2.5.198.36 */
  11952. break;
  11953. case 'PtgAttrIfError': /* [MS-XLSB] 2.5.97.28 */
  11954. break;
  11955. case 'PtgRef': /* [MS-XLS] 2.5.198.84 */
  11956. c = shift_cell_xls((f[1][1]), _range, opts);
  11957. stack.push(encode_cell_xls(c, biff));
  11958. break;
  11959. case 'PtgRefN': /* [MS-XLS] 2.5.198.88 */
  11960. c = cell ? shift_cell_xls((f[1][1]), cell, opts) : (f[1][1]);
  11961. stack.push(encode_cell_xls(c, biff));
  11962. break;
  11963. case 'PtgRef3d': /* [MS-XLS] 2.5.198.85 */
  11964. ixti = f[1][1]; c = shift_cell_xls((f[1][2]), _range, opts);
  11965. sname = get_ixti(supbooks, ixti, opts);
  11966. var w = sname; /* IE9 fails on defined names */ // eslint-disable-line no-unused-vars
  11967. stack.push(sname + "!" + encode_cell_xls(c, biff));
  11968. break;
  11969. case 'PtgFunc': /* [MS-XLS] 2.5.198.62 */
  11970. case 'PtgFuncVar': /* [MS-XLS] 2.5.198.63 */
  11971. /* f[1] = [argc, func, type] */
  11972. var argc = (f[1][0]), func = (f[1][1]);
  11973. if(!argc) argc = 0;
  11974. argc &= 0x7F;
  11975. var args = argc == 0 ? [] : stack.slice(-argc);
  11976. stack.length -= argc;
  11977. if(func === 'User') func = args.shift();
  11978. stack.push(func + "(" + args.join(",") + ")");
  11979. break;
  11980. case 'PtgBool': /* [MS-XLS] 2.5.198.42 */
  11981. stack.push(f[1] ? "TRUE" : "FALSE"); break;
  11982. case 'PtgInt': /* [MS-XLS] 2.5.198.66 */
  11983. stack.push(f[1]); break;
  11984. case 'PtgNum': /* [MS-XLS] 2.5.198.79 TODO: precision? */
  11985. stack.push(String(f[1])); break;
  11986. case 'PtgStr': /* [MS-XLS] 2.5.198.89 */
  11987. // $FlowIgnore
  11988. stack.push('"' + f[1].replace(/"/g, '""') + '"'); break;
  11989. case 'PtgErr': /* [MS-XLS] 2.5.198.57 */
  11990. stack.push(f[1]); break;
  11991. case 'PtgAreaN': /* [MS-XLS] 2.5.198.31 TODO */
  11992. r = shift_range_xls(f[1][1], cell ? {s:cell} : _range, opts);
  11993. stack.push(encode_range_xls((r), opts));
  11994. break;
  11995. case 'PtgArea': /* [MS-XLS] 2.5.198.27 TODO: fixed points */
  11996. r = shift_range_xls(f[1][1], _range, opts);
  11997. stack.push(encode_range_xls((r), opts));
  11998. break;
  11999. case 'PtgArea3d': /* [MS-XLS] 2.5.198.28 TODO */
  12000. ixti = f[1][1]; r = f[1][2];
  12001. sname = get_ixti(supbooks, ixti, opts);
  12002. stack.push(sname + "!" + encode_range_xls((r), opts));
  12003. break;
  12004. case 'PtgAttrSum': /* [MS-XLS] 2.5.198.41 */
  12005. stack.push("SUM(" + stack.pop() + ")");
  12006. break;
  12007. case 'PtgAttrBaxcel': /* [MS-XLS] 2.5.198.33 */
  12008. case 'PtgAttrSemi': /* [MS-XLS] 2.5.198.37 */
  12009. break;
  12010. case 'PtgName': /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 TODO: revisions */
  12011. /* f[1] = type, 0, nameindex */
  12012. nameidx = (f[1][2]);
  12013. var lbl = (supbooks.names||[])[nameidx-1] || (supbooks[0]||[])[nameidx];
  12014. var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
  12015. /* [MS-XLSB] 2.5.97.10 Ftab -- last verified 20220204 */
  12016. if(name && name.slice(0,6) == "_xlfn." && !opts.xlfn) name = name.slice(6);
  12017. stack.push(name);
  12018. break;
  12019. case 'PtgNameX': /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 TODO: revisions */
  12020. /* f[1] = type, ixti, nameindex */
  12021. var bookidx = (f[1][1]); nameidx = (f[1][2]); var externbook;
  12022. /* TODO: Properly handle missing values -- this should be using get_ixti_raw primarily */
  12023. if(opts.biff <= 5) {
  12024. if(bookidx < 0) bookidx = -bookidx;
  12025. if(supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
  12026. } else {
  12027. var o = "";
  12028. if(((supbooks[bookidx]||[])[0]||[])[0] == 0x3A01){/* empty */}
  12029. else if(((supbooks[bookidx]||[])[0]||[])[0] == 0x0401){
  12030. if(supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
  12031. o = supbooks.SheetNames[supbooks[bookidx][nameidx].itab-1] + "!";
  12032. }
  12033. }
  12034. else o = supbooks.SheetNames[nameidx-1]+ "!";
  12035. if(supbooks[bookidx] && supbooks[bookidx][nameidx]) o += supbooks[bookidx][nameidx].Name;
  12036. else if(supbooks[0] && supbooks[0][nameidx]) o += supbooks[0][nameidx].Name;
  12037. else {
  12038. var ixtidata = (get_ixti_raw(supbooks, bookidx, opts)||"").split(";;");
  12039. if(ixtidata[nameidx - 1]) o = ixtidata[nameidx - 1]; // TODO: confirm this is correct
  12040. else o += "SH33TJSERRX";
  12041. }
  12042. stack.push(o);
  12043. break;
  12044. }
  12045. if(!externbook) externbook = {Name: "SH33TJSERRY"};
  12046. stack.push(externbook.Name);
  12047. break;
  12048. case 'PtgParen': /* [MS-XLS] 2.5.198.80 */
  12049. var lp = '(', rp = ')';
  12050. if(last_sp >= 0) {
  12051. sp = "";
  12052. switch(formula[0][last_sp][1][0]) {
  12053. // $FlowIgnore
  12054. case 2: lp = fill(" ", formula[0][last_sp][1][1]) + lp; break;
  12055. // $FlowIgnore
  12056. case 3: lp = fill("\r", formula[0][last_sp][1][1]) + lp; break;
  12057. // $FlowIgnore
  12058. case 4: rp = fill(" ", formula[0][last_sp][1][1]) + rp; break;
  12059. // $FlowIgnore
  12060. case 5: rp = fill("\r", formula[0][last_sp][1][1]) + rp; break;
  12061. default:
  12062. // $FlowIgnore
  12063. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  12064. }
  12065. last_sp = -1;
  12066. }
  12067. stack.push(lp + stack.pop() + rp); break;
  12068. case 'PtgRefErr': /* [MS-XLS] 2.5.198.86 */
  12069. stack.push('#REF!'); break;
  12070. case 'PtgRefErr3d': /* [MS-XLS] 2.5.198.87 */
  12071. stack.push('#REF!'); break;
  12072. case 'PtgExp': /* [MS-XLS] 2.5.198.58 TODO */
  12073. c = {c:(f[1][1]),r:(f[1][0])};
  12074. var q = ({c: cell.c, r:cell.r});
  12075. if(supbooks.sharedf[encode_cell(c)]) {
  12076. var parsedf = (supbooks.sharedf[encode_cell(c)]);
  12077. stack.push(stringify_formula(parsedf, _range, q, supbooks, opts));
  12078. } else {
  12079. var fnd = false;
  12080. for(e1=0;e1!=supbooks.arrayf.length; ++e1) {
  12081. /* TODO: should be something like range_has */
  12082. e2 = supbooks.arrayf[e1];
  12083. if(c.c < e2[0].s.c || c.c > e2[0].e.c) continue;
  12084. if(c.r < e2[0].s.r || c.r > e2[0].e.r) continue;
  12085. stack.push(stringify_formula(e2[1], _range, q, supbooks, opts));
  12086. fnd = true;
  12087. break;
  12088. }
  12089. if(!fnd) stack.push(f[1]);
  12090. }
  12091. break;
  12092. case 'PtgArray': /* [MS-XLS] 2.5.198.32 TODO */
  12093. stack.push("{" + stringify_array(f[1]) + "}");
  12094. break;
  12095. case 'PtgMemArea': /* [MS-XLS] 2.5.198.70 TODO: confirm this is a non-display */
  12096. //stack.push("(" + f[2].map(encode_range).join(",") + ")");
  12097. break;
  12098. case 'PtgAttrSpace': /* [MS-XLS] 2.5.198.38 */
  12099. case 'PtgAttrSpaceSemi': /* [MS-XLS] 2.5.198.39 */
  12100. last_sp = ff;
  12101. break;
  12102. case 'PtgTbl': /* [MS-XLS] 2.5.198.92 TODO */
  12103. break;
  12104. case 'PtgMemErr': /* [MS-XLS] 2.5.198.71 */
  12105. break;
  12106. case 'PtgMissArg': /* [MS-XLS] 2.5.198.74 */
  12107. stack.push("");
  12108. break;
  12109. case 'PtgAreaErr': /* [MS-XLS] 2.5.198.29 */
  12110. stack.push("#REF!"); break;
  12111. case 'PtgAreaErr3d': /* [MS-XLS] 2.5.198.30 */
  12112. stack.push("#REF!"); break;
  12113. case 'PtgList': /* [MS-XLSB] 2.5.97.52 */
  12114. // $FlowIgnore
  12115. stack.push("Table" + f[1].idx + "[#" + f[1].rt + "]");
  12116. break;
  12117. case 'PtgMemAreaN':
  12118. case 'PtgMemNoMemN':
  12119. case 'PtgAttrNoop':
  12120. case 'PtgSheet':
  12121. case 'PtgEndSheet':
  12122. break;
  12123. case 'PtgMemFunc': /* [MS-XLS] 2.5.198.72 TODO */
  12124. break;
  12125. case 'PtgMemNoMem': /* [MS-XLS] 2.5.198.73 TODO */
  12126. break;
  12127. case 'PtgElfCol': /* [MS-XLS] 2.5.198.46 */
  12128. case 'PtgElfColS': /* [MS-XLS] 2.5.198.47 */
  12129. case 'PtgElfColSV': /* [MS-XLS] 2.5.198.48 */
  12130. case 'PtgElfColV': /* [MS-XLS] 2.5.198.49 */
  12131. case 'PtgElfLel': /* [MS-XLS] 2.5.198.50 */
  12132. case 'PtgElfRadical': /* [MS-XLS] 2.5.198.51 */
  12133. case 'PtgElfRadicalLel': /* [MS-XLS] 2.5.198.52 */
  12134. case 'PtgElfRadicalS': /* [MS-XLS] 2.5.198.53 */
  12135. case 'PtgElfRw': /* [MS-XLS] 2.5.198.54 */
  12136. case 'PtgElfRwV': /* [MS-XLS] 2.5.198.55 */
  12137. throw new Error("Unsupported ELFs");
  12138. case 'PtgSxName': /* [MS-XLS] 2.5.198.91 TODO -- find a test case */
  12139. throw new Error('Unrecognized Formula Token: ' + String(f));
  12140. default: throw new Error('Unrecognized Formula Token: ' + String(f));
  12141. }
  12142. var PtgNonDisp = ['PtgAttrSpace', 'PtgAttrSpaceSemi', 'PtgAttrGoto'];
  12143. if(opts.biff != 3) if(last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
  12144. f = formula[0][last_sp];
  12145. var _left = true;
  12146. switch(f[1][0]) {
  12147. /* note: some bad XLSB files omit the PtgParen */
  12148. case 4: _left = false;
  12149. /* falls through */
  12150. case 0:
  12151. // $FlowIgnore
  12152. sp = fill(" ", f[1][1]); break;
  12153. case 5: _left = false;
  12154. /* falls through */
  12155. case 1:
  12156. // $FlowIgnore
  12157. sp = fill("\r", f[1][1]); break;
  12158. default:
  12159. sp = "";
  12160. // $FlowIgnore
  12161. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f[1][0]);
  12162. }
  12163. stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
  12164. last_sp = -1;
  12165. }
  12166. }
  12167. if(stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
  12168. return stack[0];
  12169. }
  12170. /* [MS-XLS] 2.5.198.1 TODO */
  12171. function parse_ArrayParsedFormula(blob, length, opts) {
  12172. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  12173. var rgcb, cce = blob.read_shift(len); // length of rgce
  12174. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  12175. var rgce = parse_Rgce(blob, cce, opts);
  12176. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  12177. blob.l = target;
  12178. return [rgce, rgcb];
  12179. }
  12180. /* [MS-XLS] 2.5.198.3 TODO */
  12181. function parse_XLSCellParsedFormula(blob, length, opts) {
  12182. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  12183. var rgcb, cce = blob.read_shift(len); // length of rgce
  12184. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  12185. var rgce = parse_Rgce(blob, cce, opts);
  12186. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  12187. blob.l = target;
  12188. return [rgce, rgcb];
  12189. }
  12190. /* [MS-XLS] 2.5.198.21 */
  12191. function parse_NameParsedFormula(blob, length, opts, cce) {
  12192. var target = blob.l + length;
  12193. var rgce = parse_Rgce(blob, cce, opts);
  12194. var rgcb;
  12195. if(target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
  12196. return [rgce, rgcb];
  12197. }
  12198. /* [MS-XLS] 2.5.198.118 TODO */
  12199. function parse_SharedParsedFormula(blob, length, opts) {
  12200. var target = blob.l + length;
  12201. var rgcb, cce = blob.read_shift(2); // length of rgce
  12202. var rgce = parse_Rgce(blob, cce, opts);
  12203. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  12204. if(length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
  12205. return [rgce, rgcb];
  12206. }
  12207. /* [MS-XLS] 2.5.133 TODO: how to emit empty strings? */
  12208. function parse_FormulaValue(blob) {
  12209. var b;
  12210. if(__readUInt16LE(blob,blob.l + 6) !== 0xFFFF) return [parse_Xnum(blob),'n'];
  12211. switch(blob[blob.l]) {
  12212. case 0x00: blob.l += 8; return ["String", 's'];
  12213. case 0x01: b = blob[blob.l+2] === 0x1; blob.l += 8; return [b,'b'];
  12214. case 0x02: b = blob[blob.l+2]; blob.l += 8; return [b,'e'];
  12215. case 0x03: blob.l += 8; return ["",'s'];
  12216. }
  12217. return [];
  12218. }
  12219. function write_FormulaValue(value) {
  12220. if(value == null) {
  12221. // Blank String Value
  12222. var o = new_buf(8);
  12223. o.write_shift(1, 0x03);
  12224. o.write_shift(1, 0);
  12225. o.write_shift(2, 0);
  12226. o.write_shift(2, 0);
  12227. o.write_shift(2, 0xFFFF);
  12228. return o;
  12229. } else if(typeof value == "number") return write_Xnum(value);
  12230. return write_Xnum(0);
  12231. }
  12232. /* [MS-XLS] 2.4.127 TODO */
  12233. function parse_Formula(blob, length, opts) {
  12234. var end = blob.l + length;
  12235. var cell = parse_XLSCell(blob, 6);
  12236. if(opts.biff == 2) ++blob.l;
  12237. var val = parse_FormulaValue(blob,8);
  12238. var flags = blob.read_shift(1);
  12239. if(opts.biff != 2) {
  12240. blob.read_shift(1);
  12241. if(opts.biff >= 5) {
  12242. /*var chn = */blob.read_shift(4);
  12243. }
  12244. }
  12245. var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
  12246. return {cell:cell, val:val[0], formula:cbf, shared: (flags >> 3) & 1, tt:val[1]};
  12247. }
  12248. function write_Formula(cell, R, C, opts, os) {
  12249. // Cell
  12250. var o1 = write_XLSCell(R, C, os);
  12251. // FormulaValue
  12252. var o2 = write_FormulaValue(cell.v);
  12253. // flags + cache
  12254. var o3 = new_buf(6);
  12255. var flags = 0x01 | 0x20;
  12256. o3.write_shift(2, flags);
  12257. o3.write_shift(4, 0);
  12258. // CellParsedFormula
  12259. var bf = new_buf(cell.bf.length);
  12260. for(var i = 0; i < cell.bf.length; ++i) bf[i] = cell.bf[i];
  12261. var out = bconcat([o1, o2, o3, bf]);
  12262. return out;
  12263. }
  12264. /* XLSB Parsed Formula records have the same shape */
  12265. function parse_XLSBParsedFormula(data, length, opts) {
  12266. var cce = data.read_shift(4);
  12267. var rgce = parse_Rgce(data, cce, opts);
  12268. var cb = data.read_shift(4);
  12269. var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
  12270. return [rgce, rgcb];
  12271. }
  12272. /* [MS-XLSB] 2.5.97.1 ArrayParsedFormula */
  12273. var parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
  12274. /* [MS-XLSB] 2.5.97.4 CellParsedFormula */
  12275. var parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
  12276. /* [MS-XLSB] 2.5.97.8 DVParsedFormula */
  12277. //var parse_XLSBDVParsedFormula = parse_XLSBParsedFormula;
  12278. /* [MS-XLSB] 2.5.97.9 FRTParsedFormula */
  12279. //var parse_XLSBFRTParsedFormula = parse_XLSBParsedFormula2;
  12280. /* [MS-XLSB] 2.5.97.12 NameParsedFormula */
  12281. var parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
  12282. /* [MS-XLSB] 2.5.97.98 SharedParsedFormula */
  12283. var parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
  12284. var Cetab = {
  12285. 0: "BEEP",
  12286. 1: "OPEN",
  12287. 2: "OPEN.LINKS",
  12288. 3: "CLOSE.ALL",
  12289. 4: "SAVE",
  12290. 5: "SAVE.AS",
  12291. 6: "FILE.DELETE",
  12292. 7: "PAGE.SETUP",
  12293. 8: "PRINT",
  12294. 9: "PRINTER.SETUP",
  12295. 10: "QUIT",
  12296. 11: "NEW.WINDOW",
  12297. 12: "ARRANGE.ALL",
  12298. 13: "WINDOW.SIZE",
  12299. 14: "WINDOW.MOVE",
  12300. 15: "FULL",
  12301. 16: "CLOSE",
  12302. 17: "RUN",
  12303. 22: "SET.PRINT.AREA",
  12304. 23: "SET.PRINT.TITLES",
  12305. 24: "SET.PAGE.BREAK",
  12306. 25: "REMOVE.PAGE.BREAK",
  12307. 26: "FONT",
  12308. 27: "DISPLAY",
  12309. 28: "PROTECT.DOCUMENT",
  12310. 29: "PRECISION",
  12311. 30: "A1.R1C1",
  12312. 31: "CALCULATE.NOW",
  12313. 32: "CALCULATION",
  12314. 34: "DATA.FIND",
  12315. 35: "EXTRACT",
  12316. 36: "DATA.DELETE",
  12317. 37: "SET.DATABASE",
  12318. 38: "SET.CRITERIA",
  12319. 39: "SORT",
  12320. 40: "DATA.SERIES",
  12321. 41: "TABLE",
  12322. 42: "FORMAT.NUMBER",
  12323. 43: "ALIGNMENT",
  12324. 44: "STYLE",
  12325. 45: "BORDER",
  12326. 46: "CELL.PROTECTION",
  12327. 47: "COLUMN.WIDTH",
  12328. 48: "UNDO",
  12329. 49: "CUT",
  12330. 50: "COPY",
  12331. 51: "PASTE",
  12332. 52: "CLEAR",
  12333. 53: "PASTE.SPECIAL",
  12334. 54: "EDIT.DELETE",
  12335. 55: "INSERT",
  12336. 56: "FILL.RIGHT",
  12337. 57: "FILL.DOWN",
  12338. 61: "DEFINE.NAME",
  12339. 62: "CREATE.NAMES",
  12340. 63: "FORMULA.GOTO",
  12341. 64: "FORMULA.FIND",
  12342. 65: "SELECT.LAST.CELL",
  12343. 66: "SHOW.ACTIVE.CELL",
  12344. 67: "GALLERY.AREA",
  12345. 68: "GALLERY.BAR",
  12346. 69: "GALLERY.COLUMN",
  12347. 70: "GALLERY.LINE",
  12348. 71: "GALLERY.PIE",
  12349. 72: "GALLERY.SCATTER",
  12350. 73: "COMBINATION",
  12351. 74: "PREFERRED",
  12352. 75: "ADD.OVERLAY",
  12353. 76: "GRIDLINES",
  12354. 77: "SET.PREFERRED",
  12355. 78: "AXES",
  12356. 79: "LEGEND",
  12357. 80: "ATTACH.TEXT",
  12358. 81: "ADD.ARROW",
  12359. 82: "SELECT.CHART",
  12360. 83: "SELECT.PLOT.AREA",
  12361. 84: "PATTERNS",
  12362. 85: "MAIN.CHART",
  12363. 86: "OVERLAY",
  12364. 87: "SCALE",
  12365. 88: "FORMAT.LEGEND",
  12366. 89: "FORMAT.TEXT",
  12367. 90: "EDIT.REPEAT",
  12368. 91: "PARSE",
  12369. 92: "JUSTIFY",
  12370. 93: "HIDE",
  12371. 94: "UNHIDE",
  12372. 95: "WORKSPACE",
  12373. 96: "FORMULA",
  12374. 97: "FORMULA.FILL",
  12375. 98: "FORMULA.ARRAY",
  12376. 99: "DATA.FIND.NEXT",
  12377. 100: "DATA.FIND.PREV",
  12378. 101: "FORMULA.FIND.NEXT",
  12379. 102: "FORMULA.FIND.PREV",
  12380. 103: "ACTIVATE",
  12381. 104: "ACTIVATE.NEXT",
  12382. 105: "ACTIVATE.PREV",
  12383. 106: "UNLOCKED.NEXT",
  12384. 107: "UNLOCKED.PREV",
  12385. 108: "COPY.PICTURE",
  12386. 109: "SELECT",
  12387. 110: "DELETE.NAME",
  12388. 111: "DELETE.FORMAT",
  12389. 112: "VLINE",
  12390. 113: "HLINE",
  12391. 114: "VPAGE",
  12392. 115: "HPAGE",
  12393. 116: "VSCROLL",
  12394. 117: "HSCROLL",
  12395. 118: "ALERT",
  12396. 119: "NEW",
  12397. 120: "CANCEL.COPY",
  12398. 121: "SHOW.CLIPBOARD",
  12399. 122: "MESSAGE",
  12400. 124: "PASTE.LINK",
  12401. 125: "APP.ACTIVATE",
  12402. 126: "DELETE.ARROW",
  12403. 127: "ROW.HEIGHT",
  12404. 128: "FORMAT.MOVE",
  12405. 129: "FORMAT.SIZE",
  12406. 130: "FORMULA.REPLACE",
  12407. 131: "SEND.KEYS",
  12408. 132: "SELECT.SPECIAL",
  12409. 133: "APPLY.NAMES",
  12410. 134: "REPLACE.FONT",
  12411. 135: "FREEZE.PANES",
  12412. 136: "SHOW.INFO",
  12413. 137: "SPLIT",
  12414. 138: "ON.WINDOW",
  12415. 139: "ON.DATA",
  12416. 140: "DISABLE.INPUT",
  12417. 142: "OUTLINE",
  12418. 143: "LIST.NAMES",
  12419. 144: "FILE.CLOSE",
  12420. 145: "SAVE.WORKBOOK",
  12421. 146: "DATA.FORM",
  12422. 147: "COPY.CHART",
  12423. 148: "ON.TIME",
  12424. 149: "WAIT",
  12425. 150: "FORMAT.FONT",
  12426. 151: "FILL.UP",
  12427. 152: "FILL.LEFT",
  12428. 153: "DELETE.OVERLAY",
  12429. 155: "SHORT.MENUS",
  12430. 159: "SET.UPDATE.STATUS",
  12431. 161: "COLOR.PALETTE",
  12432. 162: "DELETE.STYLE",
  12433. 163: "WINDOW.RESTORE",
  12434. 164: "WINDOW.MAXIMIZE",
  12435. 166: "CHANGE.LINK",
  12436. 167: "CALCULATE.DOCUMENT",
  12437. 168: "ON.KEY",
  12438. 169: "APP.RESTORE",
  12439. 170: "APP.MOVE",
  12440. 171: "APP.SIZE",
  12441. 172: "APP.MINIMIZE",
  12442. 173: "APP.MAXIMIZE",
  12443. 174: "BRING.TO.FRONT",
  12444. 175: "SEND.TO.BACK",
  12445. 185: "MAIN.CHART.TYPE",
  12446. 186: "OVERLAY.CHART.TYPE",
  12447. 187: "SELECT.END",
  12448. 188: "OPEN.MAIL",
  12449. 189: "SEND.MAIL",
  12450. 190: "STANDARD.FONT",
  12451. 191: "CONSOLIDATE",
  12452. 192: "SORT.SPECIAL",
  12453. 193: "GALLERY.3D.AREA",
  12454. 194: "GALLERY.3D.COLUMN",
  12455. 195: "GALLERY.3D.LINE",
  12456. 196: "GALLERY.3D.PIE",
  12457. 197: "VIEW.3D",
  12458. 198: "GOAL.SEEK",
  12459. 199: "WORKGROUP",
  12460. 200: "FILL.GROUP",
  12461. 201: "UPDATE.LINK",
  12462. 202: "PROMOTE",
  12463. 203: "DEMOTE",
  12464. 204: "SHOW.DETAIL",
  12465. 206: "UNGROUP",
  12466. 207: "OBJECT.PROPERTIES",
  12467. 208: "SAVE.NEW.OBJECT",
  12468. 209: "SHARE",
  12469. 210: "SHARE.NAME",
  12470. 211: "DUPLICATE",
  12471. 212: "APPLY.STYLE",
  12472. 213: "ASSIGN.TO.OBJECT",
  12473. 214: "OBJECT.PROTECTION",
  12474. 215: "HIDE.OBJECT",
  12475. 216: "SET.EXTRACT",
  12476. 217: "CREATE.PUBLISHER",
  12477. 218: "SUBSCRIBE.TO",
  12478. 219: "ATTRIBUTES",
  12479. 220: "SHOW.TOOLBAR",
  12480. 222: "PRINT.PREVIEW",
  12481. 223: "EDIT.COLOR",
  12482. 224: "SHOW.LEVELS",
  12483. 225: "FORMAT.MAIN",
  12484. 226: "FORMAT.OVERLAY",
  12485. 227: "ON.RECALC",
  12486. 228: "EDIT.SERIES",
  12487. 229: "DEFINE.STYLE",
  12488. 240: "LINE.PRINT",
  12489. 243: "ENTER.DATA",
  12490. 249: "GALLERY.RADAR",
  12491. 250: "MERGE.STYLES",
  12492. 251: "EDITION.OPTIONS",
  12493. 252: "PASTE.PICTURE",
  12494. 253: "PASTE.PICTURE.LINK",
  12495. 254: "SPELLING",
  12496. 256: "ZOOM",
  12497. 259: "INSERT.OBJECT",
  12498. 260: "WINDOW.MINIMIZE",
  12499. 265: "SOUND.NOTE",
  12500. 266: "SOUND.PLAY",
  12501. 267: "FORMAT.SHAPE",
  12502. 268: "EXTEND.POLYGON",
  12503. 269: "FORMAT.AUTO",
  12504. 272: "GALLERY.3D.BAR",
  12505. 273: "GALLERY.3D.SURFACE",
  12506. 274: "FILL.AUTO",
  12507. 276: "CUSTOMIZE.TOOLBAR",
  12508. 277: "ADD.TOOL",
  12509. 278: "EDIT.OBJECT",
  12510. 279: "ON.DOUBLECLICK",
  12511. 280: "ON.ENTRY",
  12512. 281: "WORKBOOK.ADD",
  12513. 282: "WORKBOOK.MOVE",
  12514. 283: "WORKBOOK.COPY",
  12515. 284: "WORKBOOK.OPTIONS",
  12516. 285: "SAVE.WORKSPACE",
  12517. 288: "CHART.WIZARD",
  12518. 289: "DELETE.TOOL",
  12519. 290: "MOVE.TOOL",
  12520. 291: "WORKBOOK.SELECT",
  12521. 292: "WORKBOOK.ACTIVATE",
  12522. 293: "ASSIGN.TO.TOOL",
  12523. 295: "COPY.TOOL",
  12524. 296: "RESET.TOOL",
  12525. 297: "CONSTRAIN.NUMERIC",
  12526. 298: "PASTE.TOOL",
  12527. 302: "WORKBOOK.NEW",
  12528. 305: "SCENARIO.CELLS",
  12529. 306: "SCENARIO.DELETE",
  12530. 307: "SCENARIO.ADD",
  12531. 308: "SCENARIO.EDIT",
  12532. 309: "SCENARIO.SHOW",
  12533. 310: "SCENARIO.SHOW.NEXT",
  12534. 311: "SCENARIO.SUMMARY",
  12535. 312: "PIVOT.TABLE.WIZARD",
  12536. 313: "PIVOT.FIELD.PROPERTIES",
  12537. 314: "PIVOT.FIELD",
  12538. 315: "PIVOT.ITEM",
  12539. 316: "PIVOT.ADD.FIELDS",
  12540. 318: "OPTIONS.CALCULATION",
  12541. 319: "OPTIONS.EDIT",
  12542. 320: "OPTIONS.VIEW",
  12543. 321: "ADDIN.MANAGER",
  12544. 322: "MENU.EDITOR",
  12545. 323: "ATTACH.TOOLBARS",
  12546. 324: "VBAActivate",
  12547. 325: "OPTIONS.CHART",
  12548. 328: "VBA.INSERT.FILE",
  12549. 330: "VBA.PROCEDURE.DEFINITION",
  12550. 336: "ROUTING.SLIP",
  12551. 338: "ROUTE.DOCUMENT",
  12552. 339: "MAIL.LOGON",
  12553. 342: "INSERT.PICTURE",
  12554. 343: "EDIT.TOOL",
  12555. 344: "GALLERY.DOUGHNUT",
  12556. 350: "CHART.TREND",
  12557. 352: "PIVOT.ITEM.PROPERTIES",
  12558. 354: "WORKBOOK.INSERT",
  12559. 355: "OPTIONS.TRANSITION",
  12560. 356: "OPTIONS.GENERAL",
  12561. 370: "FILTER.ADVANCED",
  12562. 373: "MAIL.ADD.MAILER",
  12563. 374: "MAIL.DELETE.MAILER",
  12564. 375: "MAIL.REPLY",
  12565. 376: "MAIL.REPLY.ALL",
  12566. 377: "MAIL.FORWARD",
  12567. 378: "MAIL.NEXT.LETTER",
  12568. 379: "DATA.LABEL",
  12569. 380: "INSERT.TITLE",
  12570. 381: "FONT.PROPERTIES",
  12571. 382: "MACRO.OPTIONS",
  12572. 383: "WORKBOOK.HIDE",
  12573. 384: "WORKBOOK.UNHIDE",
  12574. 385: "WORKBOOK.DELETE",
  12575. 386: "WORKBOOK.NAME",
  12576. 388: "GALLERY.CUSTOM",
  12577. 390: "ADD.CHART.AUTOFORMAT",
  12578. 391: "DELETE.CHART.AUTOFORMAT",
  12579. 392: "CHART.ADD.DATA",
  12580. 393: "AUTO.OUTLINE",
  12581. 394: "TAB.ORDER",
  12582. 395: "SHOW.DIALOG",
  12583. 396: "SELECT.ALL",
  12584. 397: "UNGROUP.SHEETS",
  12585. 398: "SUBTOTAL.CREATE",
  12586. 399: "SUBTOTAL.REMOVE",
  12587. 400: "RENAME.OBJECT",
  12588. 412: "WORKBOOK.SCROLL",
  12589. 413: "WORKBOOK.NEXT",
  12590. 414: "WORKBOOK.PREV",
  12591. 415: "WORKBOOK.TAB.SPLIT",
  12592. 416: "FULL.SCREEN",
  12593. 417: "WORKBOOK.PROTECT",
  12594. 420: "SCROLLBAR.PROPERTIES",
  12595. 421: "PIVOT.SHOW.PAGES",
  12596. 422: "TEXT.TO.COLUMNS",
  12597. 423: "FORMAT.CHARTTYPE",
  12598. 424: "LINK.FORMAT",
  12599. 425: "TRACER.DISPLAY",
  12600. 430: "TRACER.NAVIGATE",
  12601. 431: "TRACER.CLEAR",
  12602. 432: "TRACER.ERROR",
  12603. 433: "PIVOT.FIELD.GROUP",
  12604. 434: "PIVOT.FIELD.UNGROUP",
  12605. 435: "CHECKBOX.PROPERTIES",
  12606. 436: "LABEL.PROPERTIES",
  12607. 437: "LISTBOX.PROPERTIES",
  12608. 438: "EDITBOX.PROPERTIES",
  12609. 439: "PIVOT.REFRESH",
  12610. 440: "LINK.COMBO",
  12611. 441: "OPEN.TEXT",
  12612. 442: "HIDE.DIALOG",
  12613. 443: "SET.DIALOG.FOCUS",
  12614. 444: "ENABLE.OBJECT",
  12615. 445: "PUSHBUTTON.PROPERTIES",
  12616. 446: "SET.DIALOG.DEFAULT",
  12617. 447: "FILTER",
  12618. 448: "FILTER.SHOW.ALL",
  12619. 449: "CLEAR.OUTLINE",
  12620. 450: "FUNCTION.WIZARD",
  12621. 451: "ADD.LIST.ITEM",
  12622. 452: "SET.LIST.ITEM",
  12623. 453: "REMOVE.LIST.ITEM",
  12624. 454: "SELECT.LIST.ITEM",
  12625. 455: "SET.CONTROL.VALUE",
  12626. 456: "SAVE.COPY.AS",
  12627. 458: "OPTIONS.LISTS.ADD",
  12628. 459: "OPTIONS.LISTS.DELETE",
  12629. 460: "SERIES.AXES",
  12630. 461: "SERIES.X",
  12631. 462: "SERIES.Y",
  12632. 463: "ERRORBAR.X",
  12633. 464: "ERRORBAR.Y",
  12634. 465: "FORMAT.CHART",
  12635. 466: "SERIES.ORDER",
  12636. 467: "MAIL.LOGOFF",
  12637. 468: "CLEAR.ROUTING.SLIP",
  12638. 469: "APP.ACTIVATE.MICROSOFT",
  12639. 470: "MAIL.EDIT.MAILER",
  12640. 471: "ON.SHEET",
  12641. 472: "STANDARD.WIDTH",
  12642. 473: "SCENARIO.MERGE",
  12643. 474: "SUMMARY.INFO",
  12644. 475: "FIND.FILE",
  12645. 476: "ACTIVE.CELL.FONT",
  12646. 477: "ENABLE.TIPWIZARD",
  12647. 478: "VBA.MAKE.ADDIN",
  12648. 480: "INSERTDATATABLE",
  12649. 481: "WORKGROUP.OPTIONS",
  12650. 482: "MAIL.SEND.MAILER",
  12651. 485: "AUTOCORRECT",
  12652. 489: "POST.DOCUMENT",
  12653. 491: "PICKLIST",
  12654. 493: "VIEW.SHOW",
  12655. 494: "VIEW.DEFINE",
  12656. 495: "VIEW.DELETE",
  12657. 509: "SHEET.BACKGROUND",
  12658. 510: "INSERT.MAP.OBJECT",
  12659. 511: "OPTIONS.MENONO",
  12660. 517: "MSOCHECKS",
  12661. 518: "NORMAL",
  12662. 519: "LAYOUT",
  12663. 520: "RM.PRINT.AREA",
  12664. 521: "CLEAR.PRINT.AREA",
  12665. 522: "ADD.PRINT.AREA",
  12666. 523: "MOVE.BRK",
  12667. 545: "HIDECURR.NOTE",
  12668. 546: "HIDEALL.NOTES",
  12669. 547: "DELETE.NOTE",
  12670. 548: "TRAVERSE.NOTES",
  12671. 549: "ACTIVATE.NOTES",
  12672. 620: "PROTECT.REVISIONS",
  12673. 621: "UNPROTECT.REVISIONS",
  12674. 647: "OPTIONS.ME",
  12675. 653: "WEB.PUBLISH",
  12676. 667: "NEWWEBQUERY",
  12677. 673: "PIVOT.TABLE.CHART",
  12678. 753: "OPTIONS.SAVE",
  12679. 755: "OPTIONS.SPELL",
  12680. 808: "HIDEALL.INKANNOTS"
  12681. };
  12682. var Ftab = {
  12683. 0: "COUNT",
  12684. 1: "IF",
  12685. 2: "ISNA",
  12686. 3: "ISERROR",
  12687. 4: "SUM",
  12688. 5: "AVERAGE",
  12689. 6: "MIN",
  12690. 7: "MAX",
  12691. 8: "ROW",
  12692. 9: "COLUMN",
  12693. 10: "NA",
  12694. 11: "NPV",
  12695. 12: "STDEV",
  12696. 13: "DOLLAR",
  12697. 14: "FIXED",
  12698. 15: "SIN",
  12699. 16: "COS",
  12700. 17: "TAN",
  12701. 18: "ATAN",
  12702. 19: "PI",
  12703. 20: "SQRT",
  12704. 21: "EXP",
  12705. 22: "LN",
  12706. 23: "LOG10",
  12707. 24: "ABS",
  12708. 25: "INT",
  12709. 26: "SIGN",
  12710. 27: "ROUND",
  12711. 28: "LOOKUP",
  12712. 29: "INDEX",
  12713. 30: "REPT",
  12714. 31: "MID",
  12715. 32: "LEN",
  12716. 33: "VALUE",
  12717. 34: "TRUE",
  12718. 35: "FALSE",
  12719. 36: "AND",
  12720. 37: "OR",
  12721. 38: "NOT",
  12722. 39: "MOD",
  12723. 40: "DCOUNT",
  12724. 41: "DSUM",
  12725. 42: "DAVERAGE",
  12726. 43: "DMIN",
  12727. 44: "DMAX",
  12728. 45: "DSTDEV",
  12729. 46: "VAR",
  12730. 47: "DVAR",
  12731. 48: "TEXT",
  12732. 49: "LINEST",
  12733. 50: "TREND",
  12734. 51: "LOGEST",
  12735. 52: "GROWTH",
  12736. 53: "GOTO",
  12737. 54: "HALT",
  12738. 55: "RETURN",
  12739. 56: "PV",
  12740. 57: "FV",
  12741. 58: "NPER",
  12742. 59: "PMT",
  12743. 60: "RATE",
  12744. 61: "MIRR",
  12745. 62: "IRR",
  12746. 63: "RAND",
  12747. 64: "MATCH",
  12748. 65: "DATE",
  12749. 66: "TIME",
  12750. 67: "DAY",
  12751. 68: "MONTH",
  12752. 69: "YEAR",
  12753. 70: "WEEKDAY",
  12754. 71: "HOUR",
  12755. 72: "MINUTE",
  12756. 73: "SECOND",
  12757. 74: "NOW",
  12758. 75: "AREAS",
  12759. 76: "ROWS",
  12760. 77: "COLUMNS",
  12761. 78: "OFFSET",
  12762. 79: "ABSREF",
  12763. 80: "RELREF",
  12764. 81: "ARGUMENT",
  12765. 82: "SEARCH",
  12766. 83: "TRANSPOSE",
  12767. 84: "ERROR",
  12768. 85: "STEP",
  12769. 86: "TYPE",
  12770. 87: "ECHO",
  12771. 88: "SET.NAME",
  12772. 89: "CALLER",
  12773. 90: "DEREF",
  12774. 91: "WINDOWS",
  12775. 92: "SERIES",
  12776. 93: "DOCUMENTS",
  12777. 94: "ACTIVE.CELL",
  12778. 95: "SELECTION",
  12779. 96: "RESULT",
  12780. 97: "ATAN2",
  12781. 98: "ASIN",
  12782. 99: "ACOS",
  12783. 100: "CHOOSE",
  12784. 101: "HLOOKUP",
  12785. 102: "VLOOKUP",
  12786. 103: "LINKS",
  12787. 104: "INPUT",
  12788. 105: "ISREF",
  12789. 106: "GET.FORMULA",
  12790. 107: "GET.NAME",
  12791. 108: "SET.VALUE",
  12792. 109: "LOG",
  12793. 110: "EXEC",
  12794. 111: "CHAR",
  12795. 112: "LOWER",
  12796. 113: "UPPER",
  12797. 114: "PROPER",
  12798. 115: "LEFT",
  12799. 116: "RIGHT",
  12800. 117: "EXACT",
  12801. 118: "TRIM",
  12802. 119: "REPLACE",
  12803. 120: "SUBSTITUTE",
  12804. 121: "CODE",
  12805. 122: "NAMES",
  12806. 123: "DIRECTORY",
  12807. 124: "FIND",
  12808. 125: "CELL",
  12809. 126: "ISERR",
  12810. 127: "ISTEXT",
  12811. 128: "ISNUMBER",
  12812. 129: "ISBLANK",
  12813. 130: "T",
  12814. 131: "N",
  12815. 132: "FOPEN",
  12816. 133: "FCLOSE",
  12817. 134: "FSIZE",
  12818. 135: "FREADLN",
  12819. 136: "FREAD",
  12820. 137: "FWRITELN",
  12821. 138: "FWRITE",
  12822. 139: "FPOS",
  12823. 140: "DATEVALUE",
  12824. 141: "TIMEVALUE",
  12825. 142: "SLN",
  12826. 143: "SYD",
  12827. 144: "DDB",
  12828. 145: "GET.DEF",
  12829. 146: "REFTEXT",
  12830. 147: "TEXTREF",
  12831. 148: "INDIRECT",
  12832. 149: "REGISTER",
  12833. 150: "CALL",
  12834. 151: "ADD.BAR",
  12835. 152: "ADD.MENU",
  12836. 153: "ADD.COMMAND",
  12837. 154: "ENABLE.COMMAND",
  12838. 155: "CHECK.COMMAND",
  12839. 156: "RENAME.COMMAND",
  12840. 157: "SHOW.BAR",
  12841. 158: "DELETE.MENU",
  12842. 159: "DELETE.COMMAND",
  12843. 160: "GET.CHART.ITEM",
  12844. 161: "DIALOG.BOX",
  12845. 162: "CLEAN",
  12846. 163: "MDETERM",
  12847. 164: "MINVERSE",
  12848. 165: "MMULT",
  12849. 166: "FILES",
  12850. 167: "IPMT",
  12851. 168: "PPMT",
  12852. 169: "COUNTA",
  12853. 170: "CANCEL.KEY",
  12854. 171: "FOR",
  12855. 172: "WHILE",
  12856. 173: "BREAK",
  12857. 174: "NEXT",
  12858. 175: "INITIATE",
  12859. 176: "REQUEST",
  12860. 177: "POKE",
  12861. 178: "EXECUTE",
  12862. 179: "TERMINATE",
  12863. 180: "RESTART",
  12864. 181: "HELP",
  12865. 182: "GET.BAR",
  12866. 183: "PRODUCT",
  12867. 184: "FACT",
  12868. 185: "GET.CELL",
  12869. 186: "GET.WORKSPACE",
  12870. 187: "GET.WINDOW",
  12871. 188: "GET.DOCUMENT",
  12872. 189: "DPRODUCT",
  12873. 190: "ISNONTEXT",
  12874. 191: "GET.NOTE",
  12875. 192: "NOTE",
  12876. 193: "STDEVP",
  12877. 194: "VARP",
  12878. 195: "DSTDEVP",
  12879. 196: "DVARP",
  12880. 197: "TRUNC",
  12881. 198: "ISLOGICAL",
  12882. 199: "DCOUNTA",
  12883. 200: "DELETE.BAR",
  12884. 201: "UNREGISTER",
  12885. 204: "USDOLLAR",
  12886. 205: "FINDB",
  12887. 206: "SEARCHB",
  12888. 207: "REPLACEB",
  12889. 208: "LEFTB",
  12890. 209: "RIGHTB",
  12891. 210: "MIDB",
  12892. 211: "LENB",
  12893. 212: "ROUNDUP",
  12894. 213: "ROUNDDOWN",
  12895. 214: "ASC",
  12896. 215: "DBCS",
  12897. 216: "RANK",
  12898. 219: "ADDRESS",
  12899. 220: "DAYS360",
  12900. 221: "TODAY",
  12901. 222: "VDB",
  12902. 223: "ELSE",
  12903. 224: "ELSE.IF",
  12904. 225: "END.IF",
  12905. 226: "FOR.CELL",
  12906. 227: "MEDIAN",
  12907. 228: "SUMPRODUCT",
  12908. 229: "SINH",
  12909. 230: "COSH",
  12910. 231: "TANH",
  12911. 232: "ASINH",
  12912. 233: "ACOSH",
  12913. 234: "ATANH",
  12914. 235: "DGET",
  12915. 236: "CREATE.OBJECT",
  12916. 237: "VOLATILE",
  12917. 238: "LAST.ERROR",
  12918. 239: "CUSTOM.UNDO",
  12919. 240: "CUSTOM.REPEAT",
  12920. 241: "FORMULA.CONVERT",
  12921. 242: "GET.LINK.INFO",
  12922. 243: "TEXT.BOX",
  12923. 244: "INFO",
  12924. 245: "GROUP",
  12925. 246: "GET.OBJECT",
  12926. 247: "DB",
  12927. 248: "PAUSE",
  12928. 251: "RESUME",
  12929. 252: "FREQUENCY",
  12930. 253: "ADD.TOOLBAR",
  12931. 254: "DELETE.TOOLBAR",
  12932. 255: "User",
  12933. 256: "RESET.TOOLBAR",
  12934. 257: "EVALUATE",
  12935. 258: "GET.TOOLBAR",
  12936. 259: "GET.TOOL",
  12937. 260: "SPELLING.CHECK",
  12938. 261: "ERROR.TYPE",
  12939. 262: "APP.TITLE",
  12940. 263: "WINDOW.TITLE",
  12941. 264: "SAVE.TOOLBAR",
  12942. 265: "ENABLE.TOOL",
  12943. 266: "PRESS.TOOL",
  12944. 267: "REGISTER.ID",
  12945. 268: "GET.WORKBOOK",
  12946. 269: "AVEDEV",
  12947. 270: "BETADIST",
  12948. 271: "GAMMALN",
  12949. 272: "BETAINV",
  12950. 273: "BINOMDIST",
  12951. 274: "CHIDIST",
  12952. 275: "CHIINV",
  12953. 276: "COMBIN",
  12954. 277: "CONFIDENCE",
  12955. 278: "CRITBINOM",
  12956. 279: "EVEN",
  12957. 280: "EXPONDIST",
  12958. 281: "FDIST",
  12959. 282: "FINV",
  12960. 283: "FISHER",
  12961. 284: "FISHERINV",
  12962. 285: "FLOOR",
  12963. 286: "GAMMADIST",
  12964. 287: "GAMMAINV",
  12965. 288: "CEILING",
  12966. 289: "HYPGEOMDIST",
  12967. 290: "LOGNORMDIST",
  12968. 291: "LOGINV",
  12969. 292: "NEGBINOMDIST",
  12970. 293: "NORMDIST",
  12971. 294: "NORMSDIST",
  12972. 295: "NORMINV",
  12973. 296: "NORMSINV",
  12974. 297: "STANDARDIZE",
  12975. 298: "ODD",
  12976. 299: "PERMUT",
  12977. 300: "POISSON",
  12978. 301: "TDIST",
  12979. 302: "WEIBULL",
  12980. 303: "SUMXMY2",
  12981. 304: "SUMX2MY2",
  12982. 305: "SUMX2PY2",
  12983. 306: "CHITEST",
  12984. 307: "CORREL",
  12985. 308: "COVAR",
  12986. 309: "FORECAST",
  12987. 310: "FTEST",
  12988. 311: "INTERCEPT",
  12989. 312: "PEARSON",
  12990. 313: "RSQ",
  12991. 314: "STEYX",
  12992. 315: "SLOPE",
  12993. 316: "TTEST",
  12994. 317: "PROB",
  12995. 318: "DEVSQ",
  12996. 319: "GEOMEAN",
  12997. 320: "HARMEAN",
  12998. 321: "SUMSQ",
  12999. 322: "KURT",
  13000. 323: "SKEW",
  13001. 324: "ZTEST",
  13002. 325: "LARGE",
  13003. 326: "SMALL",
  13004. 327: "QUARTILE",
  13005. 328: "PERCENTILE",
  13006. 329: "PERCENTRANK",
  13007. 330: "MODE",
  13008. 331: "TRIMMEAN",
  13009. 332: "TINV",
  13010. 334: "MOVIE.COMMAND",
  13011. 335: "GET.MOVIE",
  13012. 336: "CONCATENATE",
  13013. 337: "POWER",
  13014. 338: "PIVOT.ADD.DATA",
  13015. 339: "GET.PIVOT.TABLE",
  13016. 340: "GET.PIVOT.FIELD",
  13017. 341: "GET.PIVOT.ITEM",
  13018. 342: "RADIANS",
  13019. 343: "DEGREES",
  13020. 344: "SUBTOTAL",
  13021. 345: "SUMIF",
  13022. 346: "COUNTIF",
  13023. 347: "COUNTBLANK",
  13024. 348: "SCENARIO.GET",
  13025. 349: "OPTIONS.LISTS.GET",
  13026. 350: "ISPMT",
  13027. 351: "DATEDIF",
  13028. 352: "DATESTRING",
  13029. 353: "NUMBERSTRING",
  13030. 354: "ROMAN",
  13031. 355: "OPEN.DIALOG",
  13032. 356: "SAVE.DIALOG",
  13033. 357: "VIEW.GET",
  13034. 358: "GETPIVOTDATA",
  13035. 359: "HYPERLINK",
  13036. 360: "PHONETIC",
  13037. 361: "AVERAGEA",
  13038. 362: "MAXA",
  13039. 363: "MINA",
  13040. 364: "STDEVPA",
  13041. 365: "VARPA",
  13042. 366: "STDEVA",
  13043. 367: "VARA",
  13044. 368: "BAHTTEXT",
  13045. 369: "THAIDAYOFWEEK",
  13046. 370: "THAIDIGIT",
  13047. 371: "THAIMONTHOFYEAR",
  13048. 372: "THAINUMSOUND",
  13049. 373: "THAINUMSTRING",
  13050. 374: "THAISTRINGLENGTH",
  13051. 375: "ISTHAIDIGIT",
  13052. 376: "ROUNDBAHTDOWN",
  13053. 377: "ROUNDBAHTUP",
  13054. 378: "THAIYEAR",
  13055. 379: "RTD",
  13056. 380: "CUBEVALUE",
  13057. 381: "CUBEMEMBER",
  13058. 382: "CUBEMEMBERPROPERTY",
  13059. 383: "CUBERANKEDMEMBER",
  13060. 384: "HEX2BIN",
  13061. 385: "HEX2DEC",
  13062. 386: "HEX2OCT",
  13063. 387: "DEC2BIN",
  13064. 388: "DEC2HEX",
  13065. 389: "DEC2OCT",
  13066. 390: "OCT2BIN",
  13067. 391: "OCT2HEX",
  13068. 392: "OCT2DEC",
  13069. 393: "BIN2DEC",
  13070. 394: "BIN2OCT",
  13071. 395: "BIN2HEX",
  13072. 396: "IMSUB",
  13073. 397: "IMDIV",
  13074. 398: "IMPOWER",
  13075. 399: "IMABS",
  13076. 400: "IMSQRT",
  13077. 401: "IMLN",
  13078. 402: "IMLOG2",
  13079. 403: "IMLOG10",
  13080. 404: "IMSIN",
  13081. 405: "IMCOS",
  13082. 406: "IMEXP",
  13083. 407: "IMARGUMENT",
  13084. 408: "IMCONJUGATE",
  13085. 409: "IMAGINARY",
  13086. 410: "IMREAL",
  13087. 411: "COMPLEX",
  13088. 412: "IMSUM",
  13089. 413: "IMPRODUCT",
  13090. 414: "SERIESSUM",
  13091. 415: "FACTDOUBLE",
  13092. 416: "SQRTPI",
  13093. 417: "QUOTIENT",
  13094. 418: "DELTA",
  13095. 419: "GESTEP",
  13096. 420: "ISEVEN",
  13097. 421: "ISODD",
  13098. 422: "MROUND",
  13099. 423: "ERF",
  13100. 424: "ERFC",
  13101. 425: "BESSELJ",
  13102. 426: "BESSELK",
  13103. 427: "BESSELY",
  13104. 428: "BESSELI",
  13105. 429: "XIRR",
  13106. 430: "XNPV",
  13107. 431: "PRICEMAT",
  13108. 432: "YIELDMAT",
  13109. 433: "INTRATE",
  13110. 434: "RECEIVED",
  13111. 435: "DISC",
  13112. 436: "PRICEDISC",
  13113. 437: "YIELDDISC",
  13114. 438: "TBILLEQ",
  13115. 439: "TBILLPRICE",
  13116. 440: "TBILLYIELD",
  13117. 441: "PRICE",
  13118. 442: "YIELD",
  13119. 443: "DOLLARDE",
  13120. 444: "DOLLARFR",
  13121. 445: "NOMINAL",
  13122. 446: "EFFECT",
  13123. 447: "CUMPRINC",
  13124. 448: "CUMIPMT",
  13125. 449: "EDATE",
  13126. 450: "EOMONTH",
  13127. 451: "YEARFRAC",
  13128. 452: "COUPDAYBS",
  13129. 453: "COUPDAYS",
  13130. 454: "COUPDAYSNC",
  13131. 455: "COUPNCD",
  13132. 456: "COUPNUM",
  13133. 457: "COUPPCD",
  13134. 458: "DURATION",
  13135. 459: "MDURATION",
  13136. 460: "ODDLPRICE",
  13137. 461: "ODDLYIELD",
  13138. 462: "ODDFPRICE",
  13139. 463: "ODDFYIELD",
  13140. 464: "RANDBETWEEN",
  13141. 465: "WEEKNUM",
  13142. 466: "AMORDEGRC",
  13143. 467: "AMORLINC",
  13144. 468: "CONVERT",
  13145. 724: "SHEETJS",
  13146. 469: "ACCRINT",
  13147. 470: "ACCRINTM",
  13148. 471: "WORKDAY",
  13149. 472: "NETWORKDAYS",
  13150. 473: "GCD",
  13151. 474: "MULTINOMIAL",
  13152. 475: "LCM",
  13153. 476: "FVSCHEDULE",
  13154. 477: "CUBEKPIMEMBER",
  13155. 478: "CUBESET",
  13156. 479: "CUBESETCOUNT",
  13157. 480: "IFERROR",
  13158. 481: "COUNTIFS",
  13159. 482: "SUMIFS",
  13160. 483: "AVERAGEIF",
  13161. 484: "AVERAGEIFS"
  13162. };
  13163. var FtabArgc = {
  13164. 2: 1,
  13165. 3: 1,
  13166. 10: 0,
  13167. 15: 1,
  13168. 16: 1,
  13169. 17: 1,
  13170. 18: 1,
  13171. 19: 0,
  13172. 20: 1,
  13173. 21: 1,
  13174. 22: 1,
  13175. 23: 1,
  13176. 24: 1,
  13177. 25: 1,
  13178. 26: 1,
  13179. 27: 2,
  13180. 30: 2,
  13181. 31: 3,
  13182. 32: 1,
  13183. 33: 1,
  13184. 34: 0,
  13185. 35: 0,
  13186. 38: 1,
  13187. 39: 2,
  13188. 40: 3,
  13189. 41: 3,
  13190. 42: 3,
  13191. 43: 3,
  13192. 44: 3,
  13193. 45: 3,
  13194. 47: 3,
  13195. 48: 2,
  13196. 53: 1,
  13197. 61: 3,
  13198. 63: 0,
  13199. 65: 3,
  13200. 66: 3,
  13201. 67: 1,
  13202. 68: 1,
  13203. 69: 1,
  13204. 70: 1,
  13205. 71: 1,
  13206. 72: 1,
  13207. 73: 1,
  13208. 74: 0,
  13209. 75: 1,
  13210. 76: 1,
  13211. 77: 1,
  13212. 79: 2,
  13213. 80: 2,
  13214. 83: 1,
  13215. 85: 0,
  13216. 86: 1,
  13217. 89: 0,
  13218. 90: 1,
  13219. 94: 0,
  13220. 95: 0,
  13221. 97: 2,
  13222. 98: 1,
  13223. 99: 1,
  13224. 101: 3,
  13225. 102: 3,
  13226. 105: 1,
  13227. 106: 1,
  13228. 108: 2,
  13229. 111: 1,
  13230. 112: 1,
  13231. 113: 1,
  13232. 114: 1,
  13233. 117: 2,
  13234. 118: 1,
  13235. 119: 4,
  13236. 121: 1,
  13237. 126: 1,
  13238. 127: 1,
  13239. 128: 1,
  13240. 129: 1,
  13241. 130: 1,
  13242. 131: 1,
  13243. 133: 1,
  13244. 134: 1,
  13245. 135: 1,
  13246. 136: 2,
  13247. 137: 2,
  13248. 138: 2,
  13249. 140: 1,
  13250. 141: 1,
  13251. 142: 3,
  13252. 143: 4,
  13253. 144: 4,
  13254. 161: 1,
  13255. 162: 1,
  13256. 163: 1,
  13257. 164: 1,
  13258. 165: 2,
  13259. 172: 1,
  13260. 175: 2,
  13261. 176: 2,
  13262. 177: 3,
  13263. 178: 2,
  13264. 179: 1,
  13265. 184: 1,
  13266. 186: 1,
  13267. 189: 3,
  13268. 190: 1,
  13269. 195: 3,
  13270. 196: 3,
  13271. 197: 1,
  13272. 198: 1,
  13273. 199: 3,
  13274. 201: 1,
  13275. 207: 4,
  13276. 210: 3,
  13277. 211: 1,
  13278. 212: 2,
  13279. 213: 2,
  13280. 214: 1,
  13281. 215: 1,
  13282. 225: 0,
  13283. 229: 1,
  13284. 230: 1,
  13285. 231: 1,
  13286. 232: 1,
  13287. 233: 1,
  13288. 234: 1,
  13289. 235: 3,
  13290. 244: 1,
  13291. 247: 4,
  13292. 252: 2,
  13293. 257: 1,
  13294. 261: 1,
  13295. 271: 1,
  13296. 273: 4,
  13297. 274: 2,
  13298. 275: 2,
  13299. 276: 2,
  13300. 277: 3,
  13301. 278: 3,
  13302. 279: 1,
  13303. 280: 3,
  13304. 281: 3,
  13305. 282: 3,
  13306. 283: 1,
  13307. 284: 1,
  13308. 285: 2,
  13309. 286: 4,
  13310. 287: 3,
  13311. 288: 2,
  13312. 289: 4,
  13313. 290: 3,
  13314. 291: 3,
  13315. 292: 3,
  13316. 293: 4,
  13317. 294: 1,
  13318. 295: 3,
  13319. 296: 1,
  13320. 297: 3,
  13321. 298: 1,
  13322. 299: 2,
  13323. 300: 3,
  13324. 301: 3,
  13325. 302: 4,
  13326. 303: 2,
  13327. 304: 2,
  13328. 305: 2,
  13329. 306: 2,
  13330. 307: 2,
  13331. 308: 2,
  13332. 309: 3,
  13333. 310: 2,
  13334. 311: 2,
  13335. 312: 2,
  13336. 313: 2,
  13337. 314: 2,
  13338. 315: 2,
  13339. 316: 4,
  13340. 325: 2,
  13341. 326: 2,
  13342. 327: 2,
  13343. 328: 2,
  13344. 331: 2,
  13345. 332: 2,
  13346. 337: 2,
  13347. 342: 1,
  13348. 343: 1,
  13349. 346: 2,
  13350. 347: 1,
  13351. 350: 4,
  13352. 351: 3,
  13353. 352: 1,
  13354. 353: 2,
  13355. 360: 1,
  13356. 368: 1,
  13357. 369: 1,
  13358. 370: 1,
  13359. 371: 1,
  13360. 372: 1,
  13361. 373: 1,
  13362. 374: 1,
  13363. 375: 1,
  13364. 376: 1,
  13365. 377: 1,
  13366. 378: 1,
  13367. 382: 3,
  13368. 385: 1,
  13369. 392: 1,
  13370. 393: 1,
  13371. 396: 2,
  13372. 397: 2,
  13373. 398: 2,
  13374. 399: 1,
  13375. 400: 1,
  13376. 401: 1,
  13377. 402: 1,
  13378. 403: 1,
  13379. 404: 1,
  13380. 405: 1,
  13381. 406: 1,
  13382. 407: 1,
  13383. 408: 1,
  13384. 409: 1,
  13385. 410: 1,
  13386. 414: 4,
  13387. 415: 1,
  13388. 416: 1,
  13389. 417: 2,
  13390. 420: 1,
  13391. 421: 1,
  13392. 422: 2,
  13393. 424: 1,
  13394. 425: 2,
  13395. 426: 2,
  13396. 427: 2,
  13397. 428: 2,
  13398. 430: 3,
  13399. 438: 3,
  13400. 439: 3,
  13401. 440: 3,
  13402. 443: 2,
  13403. 444: 2,
  13404. 445: 2,
  13405. 446: 2,
  13406. 447: 6,
  13407. 448: 6,
  13408. 449: 2,
  13409. 450: 2,
  13410. 464: 2,
  13411. 468: 3,
  13412. 476: 2,
  13413. 479: 1,
  13414. 480: 2,
  13415. 65535: 0
  13416. };
  13417. /* Part 3 TODO: actually parse formulae */
  13418. function ods_to_csf_formula(f) {
  13419. if(f.slice(0,3) == "of:") f = f.slice(3);
  13420. /* 5.2 Basic Expressions */
  13421. if(f.charCodeAt(0) == 61) {
  13422. f = f.slice(1);
  13423. if(f.charCodeAt(0) == 61) f = f.slice(1);
  13424. }
  13425. f = f.replace(/COM\.MICROSOFT\./g, "");
  13426. /* Part 3 Section 5.8 References */
  13427. f = f.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) { return $1.replace(/\./g,""); });
  13428. /* TODO: something other than this */
  13429. f = f.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
  13430. return f.replace(/[;~]/g,",").replace(/\|/g,";");
  13431. }
  13432. function csf_to_ods_formula(f) {
  13433. var o = "of:=" + f.replace(crefregex, "$1[.$2$3$4$5]").replace(/\]:\[/g,":");
  13434. /* TODO: something other than this */
  13435. return o.replace(/;/g, "|").replace(/,/g,";");
  13436. }
  13437. function ods_to_csf_3D(r) {
  13438. var a = r.split(":");
  13439. var s = a[0].split(".")[0];
  13440. return [s, a[0].split(".")[1] + (a.length > 1 ? (":" + (a[1].split(".")[1] || a[1].split(".")[0])) : "")];
  13441. }
  13442. function csf_to_ods_3D(r) {
  13443. return r.replace(/\./,"!");
  13444. }
  13445. var strs = {}; // shared strings
  13446. var _ssfopts = {}; // spreadsheet formatting options
  13447. /*global Map */
  13448. var browser_has_Map = typeof Map !== 'undefined';
  13449. function get_sst_id(sst, str, rev) {
  13450. var i = 0, len = sst.length;
  13451. if(rev) {
  13452. if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
  13453. var revarr = browser_has_Map ? rev.get(str) : rev[str];
  13454. for(; i < revarr.length; ++i) {
  13455. if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
  13456. }
  13457. }
  13458. } else for(; i < len; ++i) {
  13459. if(sst[i].t === str) { sst.Count ++; return i; }
  13460. }
  13461. sst[len] = ({t:str}); sst.Count ++; sst.Unique ++;
  13462. if(rev) {
  13463. if(browser_has_Map) {
  13464. if(!rev.has(str)) rev.set(str, []);
  13465. rev.get(str).push(len);
  13466. } else {
  13467. if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
  13468. rev[str].push(len);
  13469. }
  13470. }
  13471. return len;
  13472. }
  13473. function col_obj_w(C, col) {
  13474. var p = ({min:C+1,max:C+1});
  13475. /* wch (chars), wpx (pixels) */
  13476. var wch = -1;
  13477. if(col.MDW) MDW = col.MDW;
  13478. if(col.width != null) p.customWidth = 1;
  13479. else if(col.wpx != null) wch = px2char(col.wpx);
  13480. else if(col.wch != null) wch = col.wch;
  13481. if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
  13482. else if(col.width != null) p.width = col.width;
  13483. if(col.hidden) p.hidden = true;
  13484. if(col.level != null) { p.outlineLevel = p.level = col.level; }
  13485. return p;
  13486. }
  13487. function default_margins(margins, mode) {
  13488. if(!margins) return;
  13489. var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  13490. if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
  13491. if(margins.left == null) margins.left = defs[0];
  13492. if(margins.right == null) margins.right = defs[1];
  13493. if(margins.top == null) margins.top = defs[2];
  13494. if(margins.bottom == null) margins.bottom = defs[3];
  13495. if(margins.header == null) margins.header = defs[4];
  13496. if(margins.footer == null) margins.footer = defs[5];
  13497. }
  13498. function get_cell_style(styles, cell, opts) {
  13499. var z = opts.revssf[cell.z != null ? cell.z : "General"];
  13500. var i = 0x3c, len = styles.length;
  13501. if(z == null && opts.ssf) {
  13502. for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
  13503. SSF_load(cell.z, i);
  13504. // $FlowIgnore
  13505. opts.ssf[i] = cell.z;
  13506. opts.revssf[cell.z] = z = i;
  13507. break;
  13508. }
  13509. }
  13510. for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
  13511. styles[len] = {
  13512. numFmtId:z,
  13513. fontId:0,
  13514. fillId:0,
  13515. borderId:0,
  13516. xfId:0,
  13517. applyNumberFormat:1
  13518. };
  13519. return len;
  13520. }
  13521. function safe_format(p, fmtid, fillid, opts, themes, styles) {
  13522. try {
  13523. if(opts.cellNF) p.z = table_fmt[fmtid];
  13524. } catch(e) { if(opts.WTF) throw e; }
  13525. if(p.t === 'z' && !opts.cellStyles) return;
  13526. if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
  13527. if((!opts || opts.cellText !== false) && p.t !== 'z') try {
  13528. if(table_fmt[fmtid] == null) SSF_load(SSFImplicit[fmtid] || "General", fmtid);
  13529. if(p.t === 'e') p.w = p.w || BErr[p.v];
  13530. else if(fmtid === 0) {
  13531. if(p.t === 'n') {
  13532. if((p.v|0) === p.v) p.w = p.v.toString(10);
  13533. else p.w = SSF_general_num(p.v);
  13534. }
  13535. else if(p.t === 'd') {
  13536. var dd = datenum(p.v);
  13537. if((dd|0) === dd) p.w = dd.toString(10);
  13538. else p.w = SSF_general_num(dd);
  13539. }
  13540. else if(p.v === undefined) return "";
  13541. else p.w = SSF_general(p.v,_ssfopts);
  13542. }
  13543. else if(p.t === 'd') p.w = SSF_format(fmtid,datenum(p.v),_ssfopts);
  13544. else p.w = SSF_format(fmtid,p.v,_ssfopts);
  13545. } catch(e) { if(opts.WTF) throw e; }
  13546. if(!opts.cellStyles) return;
  13547. if(fillid != null) try {
  13548. p.s = styles.Fills[fillid];
  13549. if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
  13550. p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
  13551. if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
  13552. }
  13553. if (p.s.bgColor && p.s.bgColor.theme) {
  13554. p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
  13555. if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
  13556. }
  13557. } catch(e) { if(opts.WTF && styles.Fills) throw e; }
  13558. }
  13559. function check_ws(ws, sname, i) {
  13560. if(ws && ws['!ref']) {
  13561. var range = safe_decode_range(ws['!ref']);
  13562. if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
  13563. }
  13564. }
  13565. function parse_ws_xml_dim(ws, s) {
  13566. var d = safe_decode_range(s);
  13567. 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);
  13568. }
  13569. var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
  13570. var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
  13571. var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
  13572. var dimregex = /"(\w*:\w*)"/;
  13573. var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
  13574. var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
  13575. var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
  13576. var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
  13577. var sheetprregex2= /<(?:\w:)?sheetPr[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetPr)>/;
  13578. var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
  13579. /* 18.3 Worksheets */
  13580. function parse_ws_xml(data, opts, idx, rels, wb, themes, styles) {
  13581. if(!data) return data;
  13582. if(!rels) rels = {'!id':{}};
  13583. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  13584. /* 18.3.1.99 worksheet CT_Worksheet */
  13585. var s = opts.dense ? ([]) : ({});
  13586. var refguess = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} });
  13587. var data1 = "", data2 = "";
  13588. var mtch = data.match(sheetdataregex);
  13589. if(mtch) {
  13590. data1 = data.slice(0, mtch.index);
  13591. data2 = data.slice(mtch.index + mtch[0].length);
  13592. } else data1 = data2 = data;
  13593. /* 18.3.1.82 sheetPr CT_SheetPr */
  13594. var sheetPr = data1.match(sheetprregex);
  13595. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  13596. else if((sheetPr = data1.match(sheetprregex2))) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1]||"", s, wb, idx, styles, themes);
  13597. /* 18.3.1.35 dimension CT_SheetDimension */
  13598. var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
  13599. if(ridx > 0) {
  13600. var ref = data1.slice(ridx,ridx+50).match(dimregex);
  13601. if(ref) parse_ws_xml_dim(s, ref[1]);
  13602. }
  13603. /* 18.3.1.88 sheetViews CT_SheetViews */
  13604. var svs = data1.match(svsregex);
  13605. if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  13606. /* 18.3.1.17 cols CT_Cols */
  13607. var columns = [];
  13608. if(opts.cellStyles) {
  13609. /* 18.3.1.13 col CT_Col */
  13610. var cols = data1.match(colregex);
  13611. if(cols) parse_ws_xml_cols(columns, cols);
  13612. }
  13613. /* 18.3.1.80 sheetData CT_SheetData ? */
  13614. if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
  13615. /* 18.3.1.2 autoFilter CT_AutoFilter */
  13616. var afilter = data2.match(afregex);
  13617. if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);
  13618. /* 18.3.1.55 mergeCells CT_MergeCells */
  13619. var merges = [];
  13620. var _merge = data2.match(mergecregex);
  13621. if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
  13622. merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
  13623. /* 18.3.1.48 hyperlinks CT_Hyperlinks */
  13624. var hlink = data2.match(hlinkregex);
  13625. if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
  13626. /* 18.3.1.62 pageMargins CT_PageMargins */
  13627. var margins = data2.match(marginregex);
  13628. if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));
  13629. if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
  13630. if(opts.sheetRows > 0 && s["!ref"]) {
  13631. var tmpref = safe_decode_range(s["!ref"]);
  13632. if(opts.sheetRows <= +tmpref.e.r) {
  13633. tmpref.e.r = opts.sheetRows - 1;
  13634. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  13635. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  13636. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  13637. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  13638. s["!fullref"] = s["!ref"];
  13639. s["!ref"] = encode_range(tmpref);
  13640. }
  13641. }
  13642. if(columns.length > 0) s["!cols"] = columns;
  13643. if(merges.length > 0) s["!merges"] = merges;
  13644. return s;
  13645. }
  13646. function write_ws_xml_merges(merges) {
  13647. if(merges.length === 0) return "";
  13648. var o = '<mergeCells count="' + merges.length + '">';
  13649. for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
  13650. return o + '</mergeCells>';
  13651. }
  13652. /* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
  13653. function parse_ws_xml_sheetpr(sheetPr, s, wb, idx) {
  13654. var data = parsexmltag(sheetPr);
  13655. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  13656. if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
  13657. }
  13658. function parse_ws_xml_sheetpr2(sheetPr, body, s, wb, idx) {
  13659. parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s, wb, idx);
  13660. }
  13661. function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
  13662. var needed = false;
  13663. var props = {}, payload = null;
  13664. if(opts.bookType !== 'xlsx' && wb.vbaraw) {
  13665. var cname = wb.SheetNames[idx];
  13666. try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
  13667. needed = true;
  13668. props.codeName = utf8write(escapexml(cname));
  13669. }
  13670. if(ws && ws["!outline"]) {
  13671. var outlineprops = {summaryBelow:1, summaryRight:1};
  13672. if(ws["!outline"].above) outlineprops.summaryBelow = 0;
  13673. if(ws["!outline"].left) outlineprops.summaryRight = 0;
  13674. payload = (payload||"") + writextag('outlinePr', null, outlineprops);
  13675. }
  13676. if(!needed && !payload) return;
  13677. o[o.length] = (writextag('sheetPr', payload, props));
  13678. }
  13679. /* 18.3.1.85 sheetProtection CT_SheetProtection */
  13680. var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
  13681. var sheetprot_deftrue = [
  13682. "formatColumns", "formatRows", "formatCells",
  13683. "insertColumns", "insertRows", "insertHyperlinks",
  13684. "deleteColumns", "deleteRows",
  13685. "sort", "autoFilter", "pivotTables"
  13686. ];
  13687. function write_ws_xml_protection(sp) {
  13688. // algorithmName, hashValue, saltValue, spinCount
  13689. var o = ({sheet:1});
  13690. sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
  13691. sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
  13692. /* TODO: algorithm */
  13693. if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
  13694. return writextag('sheetProtection', null, o);
  13695. }
  13696. function parse_ws_xml_hlinks(s, data, rels) {
  13697. var dense = Array.isArray(s);
  13698. for(var i = 0; i != data.length; ++i) {
  13699. var val = parsexmltag(utf8read(data[i]), true);
  13700. if(!val.ref) return;
  13701. var rel = ((rels || {})['!id']||[])[val.id];
  13702. if(rel) {
  13703. val.Target = rel.Target;
  13704. if(val.location) val.Target += "#"+unescapexml(val.location);
  13705. } else {
  13706. val.Target = "#" + unescapexml(val.location);
  13707. rel = {Target: val.Target, TargetMode: 'Internal'};
  13708. }
  13709. val.Rel = rel;
  13710. if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
  13711. var rng = safe_decode_range(val.ref);
  13712. for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
  13713. var addr = encode_cell({c:C,r:R});
  13714. if(dense) {
  13715. if(!s[R]) s[R] = [];
  13716. if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
  13717. s[R][C].l = val;
  13718. } else {
  13719. if(!s[addr]) s[addr] = {t:"z",v:undefined};
  13720. s[addr].l = val;
  13721. }
  13722. }
  13723. }
  13724. }
  13725. function parse_ws_xml_margins(margin) {
  13726. var o = {};
  13727. ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
  13728. if(margin[k]) o[k] = parseFloat(margin[k]);
  13729. });
  13730. return o;
  13731. }
  13732. function write_ws_xml_margins(margin) {
  13733. default_margins(margin);
  13734. return writextag('pageMargins', null, margin);
  13735. }
  13736. function parse_ws_xml_cols(columns, cols) {
  13737. var seencol = false;
  13738. for(var coli = 0; coli != cols.length; ++coli) {
  13739. var coll = parsexmltag(cols[coli], true);
  13740. if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
  13741. var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
  13742. if(coll.outlineLevel) coll.level = (+coll.outlineLevel || 0);
  13743. delete coll.min; delete coll.max; coll.width = +coll.width;
  13744. if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
  13745. process_col(coll);
  13746. while(colm <= colM) columns[colm++] = dup(coll);
  13747. }
  13748. }
  13749. function write_ws_xml_cols(ws, cols) {
  13750. var o = ["<cols>"], col;
  13751. for(var i = 0; i != cols.length; ++i) {
  13752. if(!(col = cols[i])) continue;
  13753. o[o.length] = (writextag('col', null, col_obj_w(i, col)));
  13754. }
  13755. o[o.length] = "</cols>";
  13756. return o.join("");
  13757. }
  13758. function parse_ws_xml_autofilter(data) {
  13759. var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
  13760. return o;
  13761. }
  13762. function write_ws_xml_autofilter(data, ws, wb, idx) {
  13763. var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
  13764. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  13765. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  13766. var names = wb.Workbook.Names;
  13767. var range = decode_range(ref);
  13768. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  13769. for(var i = 0; i < names.length; ++i) {
  13770. var name = names[i];
  13771. if(name.Name != '_xlnm._FilterDatabase') continue;
  13772. if(name.Sheet != idx) continue;
  13773. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  13774. }
  13775. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  13776. return writextag("autoFilter", null, {ref:ref});
  13777. }
  13778. /* 18.3.1.88 sheetViews CT_SheetViews */
  13779. /* 18.3.1.87 sheetView CT_SheetView */
  13780. var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
  13781. function parse_ws_xml_sheetviews(data, wb) {
  13782. if(!wb.Views) wb.Views = [{}];
  13783. (data.match(sviewregex)||[]).forEach(function(r, i) {
  13784. var tag = parsexmltag(r);
  13785. // $FlowIgnore
  13786. if(!wb.Views[i]) wb.Views[i] = {};
  13787. // $FlowIgnore
  13788. if(+tag.zoomScale) wb.Views[i].zoom = +tag.zoomScale;
  13789. // $FlowIgnore
  13790. if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
  13791. });
  13792. }
  13793. function write_ws_xml_sheetviews(ws, opts, idx, wb) {
  13794. var sview = ({workbookViewId:"0"});
  13795. // $FlowIgnore
  13796. if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
  13797. return writextag("sheetViews", writextag("sheetView", null, sview), {});
  13798. }
  13799. function write_ws_xml_cell(cell, ref, ws, opts) {
  13800. if(cell.c) ws['!comments'].push([ref, cell.c]);
  13801. if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z' && !cell.f) return "";
  13802. var vv = "";
  13803. var oldt = cell.t, oldv = cell.v;
  13804. if(cell.t !== "z") switch(cell.t) {
  13805. case 'b': vv = cell.v ? "1" : "0"; break;
  13806. case 'n': vv = ''+cell.v; break;
  13807. case 'e': vv = BErr[cell.v]; break;
  13808. case 'd':
  13809. if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
  13810. else {
  13811. cell = dup(cell);
  13812. cell.t = 'n';
  13813. vv = ''+(cell.v = datenum(parseDate(cell.v)));
  13814. }
  13815. if(typeof cell.z === 'undefined') cell.z = table_fmt[14];
  13816. break;
  13817. default: vv = cell.v; break;
  13818. }
  13819. var v = writetag('v', escapexml(vv)), o = ({r:ref});
  13820. /* TODO: cell style */
  13821. var os = get_cell_style(opts.cellXfs, cell, opts);
  13822. if(os !== 0) o.s = os;
  13823. switch(cell.t) {
  13824. case 'n': break;
  13825. case 'd': o.t = "d"; break;
  13826. case 'b': o.t = "b"; break;
  13827. case 'e': o.t = "e"; break;
  13828. case 'z': break;
  13829. default: if(cell.v == null) { delete cell.t; break; }
  13830. if(cell.v.length > 32767) throw new Error("Text length must not exceed 32767 characters");
  13831. if(opts && opts.bookSST) {
  13832. v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
  13833. o.t = "s"; break;
  13834. }
  13835. o.t = "str"; break;
  13836. }
  13837. if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
  13838. if(typeof cell.f == "string" && cell.f) {
  13839. var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
  13840. v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
  13841. }
  13842. if(cell.l) ws['!links'].push([ref, cell.l]);
  13843. if(cell.D) o.cm = 1;
  13844. return writextag('c', v, o);
  13845. }
  13846. var parse_ws_xml_data = (function() {
  13847. var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  13848. var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
  13849. var refregex = /ref=["']([^"']*)["']/;
  13850. var match_v = matchtag("v"), match_f = matchtag("f");
  13851. return function parse_ws_xml_data(sdata, s, opts, guess, themes, styles) {
  13852. var ri = 0, x = "", cells = [], cref = [], idx=0, i=0, cc=0, d="", p;
  13853. var tag, tagr = 0, tagc = 0;
  13854. var sstr, ftag;
  13855. var fmtid = 0, fillid = 0;
  13856. var do_format = Array.isArray(styles.CellXf), cf;
  13857. var arrayf = [];
  13858. var sharedf = [];
  13859. var dense = Array.isArray(s);
  13860. var rows = [], rowobj = {}, rowrite = false;
  13861. var sheetStubs = !!opts.sheetStubs;
  13862. for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
  13863. x = marr[mt].trim();
  13864. var xlen = x.length;
  13865. if(xlen === 0) continue;
  13866. /* 18.3.1.73 row CT_Row */
  13867. var rstarti = 0;
  13868. outa: for(ri = 0; ri < xlen; ++ri) switch(/*x.charCodeAt(ri)*/x[ri]) {
  13869. case ">" /*62*/:
  13870. if(/*x.charCodeAt(ri-1) != 47*/x[ri-1] != "/") { ++ri; break outa; }
  13871. if(opts && opts.cellStyles) {
  13872. // TODO: avoid duplication
  13873. tag = parsexmltag(x.slice(rstarti,ri), true);
  13874. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  13875. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  13876. rowobj = {}; rowrite = false;
  13877. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  13878. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  13879. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  13880. if(rowrite) rows[tagr-1] = rowobj;
  13881. }
  13882. break;
  13883. case "<" /*60*/: rstarti = ri; break;
  13884. }
  13885. if(rstarti >= ri) break;
  13886. tag = parsexmltag(x.slice(rstarti,ri), true);
  13887. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  13888. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  13889. if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
  13890. if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
  13891. if(opts && opts.cellStyles) {
  13892. rowobj = {}; rowrite = false;
  13893. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  13894. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  13895. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  13896. if(rowrite) rows[tagr-1] = rowobj;
  13897. }
  13898. /* 18.3.1.4 c CT_Cell */
  13899. cells = x.slice(ri).split(cellregex);
  13900. for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
  13901. cells = cells.slice(rslice);
  13902. for(ri = 0; ri != cells.length; ++ri) {
  13903. x = cells[ri].trim();
  13904. if(x.length === 0) continue;
  13905. cref = x.match(rregex); idx = ri; i=0; cc=0;
  13906. x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
  13907. if(cref != null && cref.length === 2) {
  13908. idx = 0; d=cref[1];
  13909. for(i=0; i != d.length; ++i) {
  13910. if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
  13911. idx = 26*idx + cc;
  13912. }
  13913. --idx;
  13914. tagc = idx;
  13915. } else ++tagc;
  13916. for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
  13917. tag = parsexmltag(x.slice(0,i), true);
  13918. if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
  13919. d = x.slice(i);
  13920. p = ({t:""});
  13921. if((cref=d.match(match_v))!= null && cref[1] !== '') p.v=unescapexml(cref[1]);
  13922. if(opts.cellFormula) {
  13923. if((cref=d.match(match_f))!= null && cref[1] !== '') {
  13924. /* TODO: match against XLSXFutureFunctions */
  13925. p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
  13926. if(!opts.xlfn) p.f = _xlfn(p.f);
  13927. if(cref[0].indexOf('t="array"') > -1) {
  13928. p.F = (d.match(refregex)||[])[1];
  13929. if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
  13930. } else if(cref[0].indexOf('t="shared"') > -1) {
  13931. // TODO: parse formula
  13932. ftag = parsexmltag(cref[0]);
  13933. var ___f = unescapexml(utf8read(cref[1]));
  13934. if(!opts.xlfn) ___f = _xlfn(___f);
  13935. sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
  13936. }
  13937. } else if((cref=d.match(/<f[^>]*\/>/))) {
  13938. ftag = parsexmltag(cref[0]);
  13939. if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
  13940. }
  13941. /* TODO: factor out contains logic */
  13942. var _tag = decode_cell(tag.r);
  13943. for(i = 0; i < arrayf.length; ++i)
  13944. if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
  13945. if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
  13946. p.F = arrayf[i][1];
  13947. }
  13948. if(tag.t == null && p.v === undefined) {
  13949. if(p.f || p.F) {
  13950. p.v = 0; p.t = "n";
  13951. } else if(!sheetStubs) continue;
  13952. else p.t = "z";
  13953. }
  13954. else p.t = tag.t || "n";
  13955. if(guess.s.c > tagc) guess.s.c = tagc;
  13956. if(guess.e.c < tagc) guess.e.c = tagc;
  13957. /* 18.18.11 t ST_CellType */
  13958. switch(p.t) {
  13959. case 'n':
  13960. if(p.v == "" || p.v == null) {
  13961. if(!sheetStubs) continue;
  13962. p.t = 'z';
  13963. } else p.v = parseFloat(p.v);
  13964. break;
  13965. case 's':
  13966. if(typeof p.v == 'undefined') {
  13967. if(!sheetStubs) continue;
  13968. p.t = 'z';
  13969. } else {
  13970. sstr = strs[parseInt(p.v, 10)];
  13971. p.v = sstr.t;
  13972. p.r = sstr.r;
  13973. if(opts.cellHTML) p.h = sstr.h;
  13974. }
  13975. break;
  13976. case 'str':
  13977. p.t = "s";
  13978. p.v = (p.v!=null) ? utf8read(p.v) : '';
  13979. if(opts.cellHTML) p.h = escapehtml(p.v);
  13980. break;
  13981. case 'inlineStr':
  13982. cref = d.match(isregex);
  13983. p.t = 's';
  13984. if(cref != null && (sstr = parse_si(cref[1]))) {
  13985. p.v = sstr.t;
  13986. if(opts.cellHTML) p.h = sstr.h;
  13987. } else p.v = "";
  13988. break;
  13989. case 'b': p.v = parsexmlbool(p.v); break;
  13990. case 'd':
  13991. if(opts.cellDates) p.v = parseDate(p.v, 1);
  13992. else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
  13993. break;
  13994. /* error string in .w, number in .v */
  13995. case 'e':
  13996. if(!opts || opts.cellText !== false) p.w = p.v;
  13997. p.v = RBErr[p.v]; break;
  13998. }
  13999. /* formatting */
  14000. fmtid = fillid = 0;
  14001. cf = null;
  14002. if(do_format && tag.s !== undefined) {
  14003. cf = styles.CellXf[tag.s];
  14004. if(cf != null) {
  14005. if(cf.numFmtId != null) fmtid = cf.numFmtId;
  14006. if(opts.cellStyles) {
  14007. if(cf.fillId != null) fillid = cf.fillId;
  14008. }
  14009. }
  14010. }
  14011. safe_format(p, fmtid, fillid, opts, themes, styles);
  14012. if(opts.cellDates && do_format && p.t == 'n' && fmt_is_date(table_fmt[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
  14013. if(tag.cm && opts.xlmeta) {
  14014. var cm = (opts.xlmeta.Cell||[])[+tag.cm-1];
  14015. if(cm && cm.type == 'XLDAPR') p.D = true;
  14016. }
  14017. if(dense) {
  14018. var _r = decode_cell(tag.r);
  14019. if(!s[_r.r]) s[_r.r] = [];
  14020. s[_r.r][_r.c] = p;
  14021. } else s[tag.r] = p;
  14022. }
  14023. }
  14024. if(rows.length > 0) s['!rows'] = rows;
  14025. }; })();
  14026. function write_ws_xml_data(ws, opts, idx, wb) {
  14027. var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
  14028. var dense = Array.isArray(ws);
  14029. var params = ({r:rr}), row, height = -1;
  14030. for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
  14031. for(R = range.s.r; R <= range.e.r; ++R) {
  14032. r = [];
  14033. rr = encode_row(R);
  14034. for(C = range.s.c; C <= range.e.c; ++C) {
  14035. ref = cols[C] + rr;
  14036. var _cell = dense ? (ws[R]||[])[C]: ws[ref];
  14037. if(_cell === undefined) continue;
  14038. if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
  14039. }
  14040. if(r.length > 0 || (rows && rows[R])) {
  14041. params = ({r:rr});
  14042. if(rows && rows[R]) {
  14043. row = rows[R];
  14044. if(row.hidden) params.hidden = 1;
  14045. height = -1;
  14046. if(row.hpx) height = px2pt(row.hpx);
  14047. else if(row.hpt) height = row.hpt;
  14048. if(height > -1) { params.ht = height; params.customHeight = 1; }
  14049. if(row.level) { params.outlineLevel = row.level; }
  14050. }
  14051. o[o.length] = (writextag('row', r.join(""), params));
  14052. }
  14053. }
  14054. if(rows) for(; R < rows.length; ++R) {
  14055. if(rows && rows[R]) {
  14056. params = ({r:R+1});
  14057. row = rows[R];
  14058. if(row.hidden) params.hidden = 1;
  14059. height = -1;
  14060. if (row.hpx) height = px2pt(row.hpx);
  14061. else if (row.hpt) height = row.hpt;
  14062. if (height > -1) { params.ht = height; params.customHeight = 1; }
  14063. if (row.level) { params.outlineLevel = row.level; }
  14064. o[o.length] = (writextag('row', "", params));
  14065. }
  14066. }
  14067. return o.join("");
  14068. }
  14069. function write_ws_xml(idx, opts, wb, rels) {
  14070. var o = [XML_HEADER, writextag('worksheet', null, {
  14071. 'xmlns': XMLNS_main[0],
  14072. 'xmlns:r': XMLNS.r
  14073. })];
  14074. var s = wb.SheetNames[idx], sidx = 0, rdata = "";
  14075. var ws = wb.Sheets[s];
  14076. if(ws == null) ws = {};
  14077. var ref = ws['!ref'] || 'A1';
  14078. var range = safe_decode_range(ref);
  14079. if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
  14080. if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
  14081. range.e.c = Math.min(range.e.c, 0x3FFF);
  14082. range.e.r = Math.min(range.e.c, 0xFFFFF);
  14083. ref = encode_range(range);
  14084. }
  14085. if(!rels) rels = {};
  14086. ws['!comments'] = [];
  14087. var _drawing = [];
  14088. write_ws_xml_sheetpr(ws, wb, idx, opts, o);
  14089. o[o.length] = (writextag('dimension', null, {'ref': ref}));
  14090. o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
  14091. /* TODO: store in WB, undefined styles */
  14092. if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
  14093. defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
  14094. baseColWidth:opts.sheetFormat.baseColWidth||'10',
  14095. outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
  14096. }));
  14097. if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
  14098. o[sidx = o.length] = '<sheetData/>';
  14099. ws['!links'] = [];
  14100. if(ws['!ref'] != null) {
  14101. rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
  14102. if(rdata.length > 0) o[o.length] = (rdata);
  14103. }
  14104. if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
  14105. /* sheetCalcPr */
  14106. if(ws['!protect']) o[o.length] = write_ws_xml_protection(ws['!protect']);
  14107. /* protectedRanges */
  14108. /* scenarios */
  14109. if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
  14110. /* sortState */
  14111. /* dataConsolidate */
  14112. /* customSheetViews */
  14113. if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
  14114. /* phoneticPr */
  14115. /* conditionalFormatting */
  14116. /* dataValidations */
  14117. var relc = -1, rel, rId = -1;
  14118. if(ws['!links'].length > 0) {
  14119. o[o.length] = "<hyperlinks>";
  14120. ws['!links'].forEach(function(l) {
  14121. if(!l[1].Target) return;
  14122. rel = ({"ref":l[0]});
  14123. if(l[1].Target.charAt(0) != "#") {
  14124. rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
  14125. rel["r:id"] = "rId"+rId;
  14126. }
  14127. if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
  14128. if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
  14129. o[o.length] = writextag("hyperlink",null,rel);
  14130. });
  14131. o[o.length] = "</hyperlinks>";
  14132. }
  14133. delete ws['!links'];
  14134. /* printOptions */
  14135. if(ws['!margins'] != null) o[o.length] = write_ws_xml_margins(ws['!margins']);
  14136. /* pageSetup */
  14137. /* headerFooter */
  14138. /* rowBreaks */
  14139. /* colBreaks */
  14140. /* customProperties */
  14141. /* cellWatches */
  14142. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
  14143. /* smartTags */
  14144. if(_drawing.length > 0) {
  14145. rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  14146. o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
  14147. ws['!drawing'] = _drawing;
  14148. }
  14149. if(ws['!comments'].length > 0) {
  14150. rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  14151. o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
  14152. ws['!legacy'] = rId;
  14153. }
  14154. /* legacyDrawingHF */
  14155. /* picture */
  14156. /* oleObjects */
  14157. /* controls */
  14158. /* webPublishItems */
  14159. /* tableParts */
  14160. /* extLst */
  14161. if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
  14162. return o.join("");
  14163. }
  14164. /* [MS-XLSB] 2.4.726 BrtRowHdr */
  14165. function parse_BrtRowHdr(data, length) {
  14166. var z = ({});
  14167. var tgt = data.l + length;
  14168. z.r = data.read_shift(4);
  14169. data.l += 4; // TODO: ixfe
  14170. var miyRw = data.read_shift(2);
  14171. data.l += 1; // TODO: top/bot padding
  14172. var flags = data.read_shift(1);
  14173. data.l = tgt;
  14174. if(flags & 0x07) z.level = flags & 0x07;
  14175. if(flags & 0x10) z.hidden = true;
  14176. if(flags & 0x20) z.hpt = miyRw / 20;
  14177. return z;
  14178. }
  14179. function write_BrtRowHdr(R, range, ws) {
  14180. var o = new_buf(17+8*16);
  14181. var row = (ws['!rows']||[])[R]||{};
  14182. o.write_shift(4, R);
  14183. o.write_shift(4, 0); /* TODO: ixfe */
  14184. var miyRw = 0x0140;
  14185. if(row.hpx) miyRw = px2pt(row.hpx) * 20;
  14186. else if(row.hpt) miyRw = row.hpt * 20;
  14187. o.write_shift(2, miyRw);
  14188. o.write_shift(1, 0); /* top/bot padding */
  14189. var flags = 0x0;
  14190. if(row.level) flags |= row.level;
  14191. if(row.hidden) flags |= 0x10;
  14192. if(row.hpx || row.hpt) flags |= 0x20;
  14193. o.write_shift(1, flags);
  14194. o.write_shift(1, 0); /* phonetic guide */
  14195. /* [MS-XLSB] 2.5.8 BrtColSpan explains the mechanism */
  14196. var ncolspan = 0, lcs = o.l;
  14197. o.l += 4;
  14198. var caddr = {r:R, c:0};
  14199. for(var i = 0; i < 16; ++i) {
  14200. if((range.s.c > ((i+1) << 10)) || (range.e.c < (i << 10))) continue;
  14201. var first = -1, last = -1;
  14202. for(var j = (i<<10); j < ((i+1)<<10); ++j) {
  14203. caddr.c = j;
  14204. var cell = Array.isArray(ws) ? (ws[caddr.r]||[])[caddr.c] : ws[encode_cell(caddr)];
  14205. if(cell) { if(first < 0) first = j; last = j; }
  14206. }
  14207. if(first < 0) continue;
  14208. ++ncolspan;
  14209. o.write_shift(4, first);
  14210. o.write_shift(4, last);
  14211. }
  14212. var l = o.l;
  14213. o.l = lcs;
  14214. o.write_shift(4, ncolspan);
  14215. o.l = l;
  14216. return o.length > o.l ? o.slice(0, o.l) : o;
  14217. }
  14218. function write_row_header(ba, ws, range, R) {
  14219. var o = write_BrtRowHdr(R, range, ws);
  14220. if((o.length > 17) || (ws['!rows']||[])[R]) write_record(ba, 0x0000 /* BrtRowHdr */, o);
  14221. }
  14222. /* [MS-XLSB] 2.4.820 BrtWsDim */
  14223. var parse_BrtWsDim = parse_UncheckedRfX;
  14224. var write_BrtWsDim = write_UncheckedRfX;
  14225. /* [MS-XLSB] 2.4.821 BrtWsFmtInfo */
  14226. function parse_BrtWsFmtInfo() {
  14227. }
  14228. //function write_BrtWsFmtInfo(ws, o) { }
  14229. /* [MS-XLSB] 2.4.823 BrtWsProp */
  14230. function parse_BrtWsProp(data, length) {
  14231. var z = {};
  14232. var f = data[data.l]; ++data.l;
  14233. z.above = !(f & 0x40);
  14234. z.left = !(f & 0x80);
  14235. /* TODO: pull flags */
  14236. data.l += 18;
  14237. z.name = parse_XLSBCodeName(data, length - 19);
  14238. return z;
  14239. }
  14240. function write_BrtWsProp(str, outl, o) {
  14241. if(o == null) o = new_buf(84+4*str.length);
  14242. var f = 0xC0;
  14243. if(outl) {
  14244. if(outl.above) f &= ~0x40;
  14245. if(outl.left) f &= ~0x80;
  14246. }
  14247. o.write_shift(1, f);
  14248. for(var i = 1; i < 3; ++i) o.write_shift(1,0);
  14249. write_BrtColor({auto:1}, o);
  14250. o.write_shift(-4,-1);
  14251. o.write_shift(-4,-1);
  14252. write_XLSBCodeName(str, o);
  14253. return o.slice(0, o.l);
  14254. }
  14255. /* [MS-XLSB] 2.4.306 BrtCellBlank */
  14256. function parse_BrtCellBlank(data) {
  14257. var cell = parse_XLSBCell(data);
  14258. return [cell];
  14259. }
  14260. function write_BrtCellBlank(cell, ncell, o) {
  14261. if(o == null) o = new_buf(8);
  14262. return write_XLSBCell(ncell, o);
  14263. }
  14264. function parse_BrtShortBlank(data) {
  14265. var cell = parse_XLSBShortCell(data);
  14266. return [cell];
  14267. }
  14268. function write_BrtShortBlank(cell, ncell, o) {
  14269. if(o == null) o = new_buf(4);
  14270. return write_XLSBShortCell(ncell, o);
  14271. }
  14272. /* [MS-XLSB] 2.4.307 BrtCellBool */
  14273. function parse_BrtCellBool(data) {
  14274. var cell = parse_XLSBCell(data);
  14275. var fBool = data.read_shift(1);
  14276. return [cell, fBool, 'b'];
  14277. }
  14278. function write_BrtCellBool(cell, ncell, o) {
  14279. if(o == null) o = new_buf(9);
  14280. write_XLSBCell(ncell, o);
  14281. o.write_shift(1, cell.v ? 1 : 0);
  14282. return o;
  14283. }
  14284. function parse_BrtShortBool(data) {
  14285. var cell = parse_XLSBShortCell(data);
  14286. var fBool = data.read_shift(1);
  14287. return [cell, fBool, 'b'];
  14288. }
  14289. function write_BrtShortBool(cell, ncell, o) {
  14290. if(o == null) o = new_buf(5);
  14291. write_XLSBShortCell(ncell, o);
  14292. o.write_shift(1, cell.v ? 1 : 0);
  14293. return o;
  14294. }
  14295. /* [MS-XLSB] 2.4.308 BrtCellError */
  14296. function parse_BrtCellError(data) {
  14297. var cell = parse_XLSBCell(data);
  14298. var bError = data.read_shift(1);
  14299. return [cell, bError, 'e'];
  14300. }
  14301. function write_BrtCellError(cell, ncell, o) {
  14302. if(o == null) o = new_buf(9);
  14303. write_XLSBCell(ncell, o);
  14304. o.write_shift(1, cell.v);
  14305. return o;
  14306. }
  14307. function parse_BrtShortError(data) {
  14308. var cell = parse_XLSBShortCell(data);
  14309. var bError = data.read_shift(1);
  14310. return [cell, bError, 'e'];
  14311. }
  14312. function write_BrtShortError(cell, ncell, o) {
  14313. if(o == null) o = new_buf(8);
  14314. write_XLSBShortCell(ncell, o);
  14315. o.write_shift(1, cell.v);
  14316. o.write_shift(2, 0);
  14317. o.write_shift(1, 0);
  14318. return o;
  14319. }
  14320. /* [MS-XLSB] 2.4.311 BrtCellIsst */
  14321. function parse_BrtCellIsst(data) {
  14322. var cell = parse_XLSBCell(data);
  14323. var isst = data.read_shift(4);
  14324. return [cell, isst, 's'];
  14325. }
  14326. function write_BrtCellIsst(cell, ncell, o) {
  14327. if(o == null) o = new_buf(12);
  14328. write_XLSBCell(ncell, o);
  14329. o.write_shift(4, ncell.v);
  14330. return o;
  14331. }
  14332. function parse_BrtShortIsst(data) {
  14333. var cell = parse_XLSBShortCell(data);
  14334. var isst = data.read_shift(4);
  14335. return [cell, isst, 's'];
  14336. }
  14337. function write_BrtShortIsst(cell, ncell, o) {
  14338. if(o == null) o = new_buf(8);
  14339. write_XLSBShortCell(ncell, o);
  14340. o.write_shift(4, ncell.v);
  14341. return o;
  14342. }
  14343. /* [MS-XLSB] 2.4.313 BrtCellReal */
  14344. function parse_BrtCellReal(data) {
  14345. var cell = parse_XLSBCell(data);
  14346. var value = parse_Xnum(data);
  14347. return [cell, value, 'n'];
  14348. }
  14349. function write_BrtCellReal(cell, ncell, o) {
  14350. if(o == null) o = new_buf(16);
  14351. write_XLSBCell(ncell, o);
  14352. write_Xnum(cell.v, o);
  14353. return o;
  14354. }
  14355. function parse_BrtShortReal(data) {
  14356. var cell = parse_XLSBShortCell(data);
  14357. var value = parse_Xnum(data);
  14358. return [cell, value, 'n'];
  14359. }
  14360. function write_BrtShortReal(cell, ncell, o) {
  14361. if(o == null) o = new_buf(12);
  14362. write_XLSBShortCell(ncell, o);
  14363. write_Xnum(cell.v, o);
  14364. return o;
  14365. }
  14366. /* [MS-XLSB] 2.4.314 BrtCellRk */
  14367. function parse_BrtCellRk(data) {
  14368. var cell = parse_XLSBCell(data);
  14369. var value = parse_RkNumber(data);
  14370. return [cell, value, 'n'];
  14371. }
  14372. function write_BrtCellRk(cell, ncell, o) {
  14373. if(o == null) o = new_buf(12);
  14374. write_XLSBCell(ncell, o);
  14375. write_RkNumber(cell.v, o);
  14376. return o;
  14377. }
  14378. function parse_BrtShortRk(data) {
  14379. var cell = parse_XLSBShortCell(data);
  14380. var value = parse_RkNumber(data);
  14381. return [cell, value, 'n'];
  14382. }
  14383. function write_BrtShortRk(cell, ncell, o) {
  14384. if(o == null) o = new_buf(8);
  14385. write_XLSBShortCell(ncell, o);
  14386. write_RkNumber(cell.v, o);
  14387. return o;
  14388. }
  14389. /* [MS-XLSB] 2.4.323 BrtCellRString */
  14390. function parse_BrtCellRString(data) {
  14391. var cell = parse_XLSBCell(data);
  14392. var value = parse_RichStr(data);
  14393. return [cell, value, 'is'];
  14394. }
  14395. /* [MS-XLSB] 2.4.317 BrtCellSt */
  14396. function parse_BrtCellSt(data) {
  14397. var cell = parse_XLSBCell(data);
  14398. var value = parse_XLWideString(data);
  14399. return [cell, value, 'str'];
  14400. }
  14401. function write_BrtCellSt(cell, ncell, o) {
  14402. if(o == null) o = new_buf(12 + 4 * cell.v.length);
  14403. write_XLSBCell(ncell, o);
  14404. write_XLWideString(cell.v, o);
  14405. return o.length > o.l ? o.slice(0, o.l) : o;
  14406. }
  14407. function parse_BrtShortSt(data) {
  14408. var cell = parse_XLSBShortCell(data);
  14409. var value = parse_XLWideString(data);
  14410. return [cell, value, 'str'];
  14411. }
  14412. function write_BrtShortSt(cell, ncell, o) {
  14413. if(o == null) o = new_buf(8 + 4 * cell.v.length);
  14414. write_XLSBShortCell(ncell, o);
  14415. write_XLWideString(cell.v, o);
  14416. return o.length > o.l ? o.slice(0, o.l) : o;
  14417. }
  14418. /* [MS-XLSB] 2.4.653 BrtFmlaBool */
  14419. function parse_BrtFmlaBool(data, length, opts) {
  14420. var end = data.l + length;
  14421. var cell = parse_XLSBCell(data);
  14422. cell.r = opts['!row'];
  14423. var value = data.read_shift(1);
  14424. var o = [cell, value, 'b'];
  14425. if(opts.cellFormula) {
  14426. data.l += 2;
  14427. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14428. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14429. }
  14430. else data.l = end;
  14431. return o;
  14432. }
  14433. /* [MS-XLSB] 2.4.654 BrtFmlaError */
  14434. function parse_BrtFmlaError(data, length, opts) {
  14435. var end = data.l + length;
  14436. var cell = parse_XLSBCell(data);
  14437. cell.r = opts['!row'];
  14438. var value = data.read_shift(1);
  14439. var o = [cell, value, 'e'];
  14440. if(opts.cellFormula) {
  14441. data.l += 2;
  14442. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14443. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14444. }
  14445. else data.l = end;
  14446. return o;
  14447. }
  14448. /* [MS-XLSB] 2.4.655 BrtFmlaNum */
  14449. function parse_BrtFmlaNum(data, length, opts) {
  14450. var end = data.l + length;
  14451. var cell = parse_XLSBCell(data);
  14452. cell.r = opts['!row'];
  14453. var value = parse_Xnum(data);
  14454. var o = [cell, value, 'n'];
  14455. if(opts.cellFormula) {
  14456. data.l += 2;
  14457. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14458. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14459. }
  14460. else data.l = end;
  14461. return o;
  14462. }
  14463. /* [MS-XLSB] 2.4.656 BrtFmlaString */
  14464. function parse_BrtFmlaString(data, length, opts) {
  14465. var end = data.l + length;
  14466. var cell = parse_XLSBCell(data);
  14467. cell.r = opts['!row'];
  14468. var value = parse_XLWideString(data);
  14469. var o = [cell, value, 'str'];
  14470. if(opts.cellFormula) {
  14471. data.l += 2;
  14472. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  14473. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  14474. }
  14475. else data.l = end;
  14476. return o;
  14477. }
  14478. /* [MS-XLSB] 2.4.682 BrtMergeCell */
  14479. var parse_BrtMergeCell = parse_UncheckedRfX;
  14480. var write_BrtMergeCell = write_UncheckedRfX;
  14481. /* [MS-XLSB] 2.4.107 BrtBeginMergeCells */
  14482. function write_BrtBeginMergeCells(cnt, o) {
  14483. if(o == null) o = new_buf(4);
  14484. o.write_shift(4, cnt);
  14485. return o;
  14486. }
  14487. /* [MS-XLSB] 2.4.662 BrtHLink */
  14488. function parse_BrtHLink(data, length) {
  14489. var end = data.l + length;
  14490. var rfx = parse_UncheckedRfX(data, 16);
  14491. var relId = parse_XLNullableWideString(data);
  14492. var loc = parse_XLWideString(data);
  14493. var tooltip = parse_XLWideString(data);
  14494. var display = parse_XLWideString(data);
  14495. data.l = end;
  14496. var o = ({rfx:rfx, relId:relId, loc:loc, display:display});
  14497. if(tooltip) o.Tooltip = tooltip;
  14498. return o;
  14499. }
  14500. function write_BrtHLink(l, rId) {
  14501. var o = new_buf(50+4*(l[1].Target.length + (l[1].Tooltip || "").length));
  14502. write_UncheckedRfX({s:decode_cell(l[0]), e:decode_cell(l[0])}, o);
  14503. write_RelID("rId" + rId, o);
  14504. var locidx = l[1].Target.indexOf("#");
  14505. var loc = locidx == -1 ? "" : l[1].Target.slice(locidx+1);
  14506. write_XLWideString(loc || "", o);
  14507. write_XLWideString(l[1].Tooltip || "", o);
  14508. write_XLWideString("", o);
  14509. return o.slice(0, o.l);
  14510. }
  14511. /* [MS-XLSB] 2.4.692 BrtPane */
  14512. function parse_BrtPane(/*data, length, opts*/) {
  14513. }
  14514. /* [MS-XLSB] 2.4.6 BrtArrFmla */
  14515. function parse_BrtArrFmla(data, length, opts) {
  14516. var end = data.l + length;
  14517. var rfx = parse_RfX(data, 16);
  14518. var fAlwaysCalc = data.read_shift(1);
  14519. var o = [rfx]; o[2] = fAlwaysCalc;
  14520. if(opts.cellFormula) {
  14521. var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
  14522. o[1] = formula;
  14523. } else data.l = end;
  14524. return o;
  14525. }
  14526. /* [MS-XLSB] 2.4.750 BrtShrFmla */
  14527. function parse_BrtShrFmla(data, length, opts) {
  14528. var end = data.l + length;
  14529. var rfx = parse_UncheckedRfX(data, 16);
  14530. var o = [rfx];
  14531. if(opts.cellFormula) {
  14532. var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
  14533. o[1] = formula;
  14534. data.l = end;
  14535. } else data.l = end;
  14536. return o;
  14537. }
  14538. /* [MS-XLSB] 2.4.323 BrtColInfo */
  14539. /* TODO: once XLS ColInfo is set, combine the functions */
  14540. function write_BrtColInfo(C, col, o) {
  14541. if(o == null) o = new_buf(18);
  14542. var p = col_obj_w(C, col);
  14543. o.write_shift(-4, C);
  14544. o.write_shift(-4, C);
  14545. o.write_shift(4, (p.width || 10) * 256);
  14546. o.write_shift(4, 0/*ixfe*/); // style
  14547. var flags = 0;
  14548. if(col.hidden) flags |= 0x01;
  14549. if(typeof p.width == 'number') flags |= 0x02;
  14550. if(col.level) flags |= (col.level << 8);
  14551. o.write_shift(2, flags); // bit flag
  14552. return o;
  14553. }
  14554. /* [MS-XLSB] 2.4.678 BrtMargins */
  14555. var BrtMarginKeys = ["left","right","top","bottom","header","footer"];
  14556. function parse_BrtMargins(data) {
  14557. var margins = ({});
  14558. BrtMarginKeys.forEach(function(k) { margins[k] = parse_Xnum(data, 8); });
  14559. return margins;
  14560. }
  14561. function write_BrtMargins(margins, o) {
  14562. if(o == null) o = new_buf(6*8);
  14563. default_margins(margins);
  14564. BrtMarginKeys.forEach(function(k) { write_Xnum((margins)[k], o); });
  14565. return o;
  14566. }
  14567. /* [MS-XLSB] 2.4.299 BrtBeginWsView */
  14568. function parse_BrtBeginWsView(data) {
  14569. var f = data.read_shift(2);
  14570. data.l += 28;
  14571. return { RTL: f & 0x20 };
  14572. }
  14573. function write_BrtBeginWsView(ws, Workbook, o) {
  14574. if(o == null) o = new_buf(30);
  14575. var f = 0x39c;
  14576. if((((Workbook||{}).Views||[])[0]||{}).RTL) f |= 0x20;
  14577. o.write_shift(2, f); // bit flag
  14578. o.write_shift(4, 0);
  14579. o.write_shift(4, 0); // view first row
  14580. o.write_shift(4, 0); // view first col
  14581. o.write_shift(1, 0); // gridline color ICV
  14582. o.write_shift(1, 0);
  14583. o.write_shift(2, 0);
  14584. o.write_shift(2, 100); // zoom scale
  14585. o.write_shift(2, 0);
  14586. o.write_shift(2, 0);
  14587. o.write_shift(2, 0);
  14588. o.write_shift(4, 0); // workbook view id
  14589. return o;
  14590. }
  14591. /* [MS-XLSB] 2.4.309 BrtCellIgnoreEC */
  14592. function write_BrtCellIgnoreEC(ref) {
  14593. var o = new_buf(24);
  14594. o.write_shift(4, 4);
  14595. o.write_shift(4, 1);
  14596. write_UncheckedRfX(ref, o);
  14597. return o;
  14598. }
  14599. /* [MS-XLSB] 2.4.748 BrtSheetProtection */
  14600. function write_BrtSheetProtection(sp, o) {
  14601. if(o == null) o = new_buf(16*4+2);
  14602. o.write_shift(2, sp.password ? crypto_CreatePasswordVerifier_Method1(sp.password) : 0);
  14603. o.write_shift(4, 1); // this record should not be written if no protection
  14604. [
  14605. ["objects", false], // fObjects
  14606. ["scenarios", false], // fScenarios
  14607. ["formatCells", true], // fFormatCells
  14608. ["formatColumns", true], // fFormatColumns
  14609. ["formatRows", true], // fFormatRows
  14610. ["insertColumns", true], // fInsertColumns
  14611. ["insertRows", true], // fInsertRows
  14612. ["insertHyperlinks", true], // fInsertHyperlinks
  14613. ["deleteColumns", true], // fDeleteColumns
  14614. ["deleteRows", true], // fDeleteRows
  14615. ["selectLockedCells", false], // fSelLockedCells
  14616. ["sort", true], // fSort
  14617. ["autoFilter", true], // fAutoFilter
  14618. ["pivotTables", true], // fPivotTables
  14619. ["selectUnlockedCells", false] // fSelUnlockedCells
  14620. ].forEach(function(n) {
  14621. if(n[1]) o.write_shift(4, sp[n[0]] != null && !sp[n[0]] ? 1 : 0);
  14622. else o.write_shift(4, sp[n[0]] != null && sp[n[0]] ? 0 : 1);
  14623. });
  14624. return o;
  14625. }
  14626. function parse_BrtDVal(/*data, length, opts*/) {
  14627. }
  14628. function parse_BrtDVal14(/*data, length, opts*/) {
  14629. }
  14630. /* [MS-XLSB] 2.1.7.61 Worksheet */
  14631. function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles) {
  14632. if(!data) return data;
  14633. var opts = _opts || {};
  14634. if(!rels) rels = {'!id':{}};
  14635. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  14636. var s = (opts.dense ? [] : {});
  14637. var ref;
  14638. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  14639. var state = [];
  14640. var pass = false, end = false;
  14641. var row, p, cf, R, C, addr, sstr, rr, cell;
  14642. var merges = [];
  14643. opts.biff = 12;
  14644. opts['!row'] = 0;
  14645. var ai = 0, af = false;
  14646. var arrayf = [];
  14647. var sharedf = {};
  14648. var supbooks = opts.supbooks || wb.supbooks || ([[]]);
  14649. supbooks.sharedf = sharedf;
  14650. supbooks.arrayf = arrayf;
  14651. supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x) { return x.name; });
  14652. if(!opts.supbooks) {
  14653. opts.supbooks = supbooks;
  14654. if(wb.Names) for(var i = 0; i < wb.Names.length; ++i) supbooks[0][i+1] = wb.Names[i];
  14655. }
  14656. var colinfo = [], rowinfo = [];
  14657. var seencol = false;
  14658. XLSBRecordEnum[0x0010] = { n:"BrtShortReal", f:parse_BrtShortReal };
  14659. var cm, vm;
  14660. recordhopper(data, function ws_parse(val, RR, RT) {
  14661. if(end) return;
  14662. switch(RT) {
  14663. case 0x0094: /* 'BrtWsDim' */
  14664. ref = val; break;
  14665. case 0x0000: /* 'BrtRowHdr' */
  14666. row = val;
  14667. if(opts.sheetRows && opts.sheetRows <= row.r) end=true;
  14668. rr = encode_row(R = row.r);
  14669. opts['!row'] = row.r;
  14670. if(val.hidden || val.hpt || val.level != null) {
  14671. if(val.hpt) val.hpx = pt2px(val.hpt);
  14672. rowinfo[val.r] = val;
  14673. }
  14674. break;
  14675. case 0x0002: /* 'BrtCellRk' */
  14676. case 0x0003: /* 'BrtCellError' */
  14677. case 0x0004: /* 'BrtCellBool' */
  14678. case 0x0005: /* 'BrtCellReal' */
  14679. case 0x0006: /* 'BrtCellSt' */
  14680. case 0x0007: /* 'BrtCellIsst' */
  14681. case 0x0008: /* 'BrtFmlaString' */
  14682. case 0x0009: /* 'BrtFmlaNum' */
  14683. case 0x000A: /* 'BrtFmlaBool' */
  14684. case 0x000B: /* 'BrtFmlaError' */
  14685. case 0x000D: /* 'BrtShortRk' */
  14686. case 0x000E: /* 'BrtShortError' */
  14687. case 0x000F: /* 'BrtShortBool' */
  14688. case 0x0010: /* 'BrtShortReal' */
  14689. case 0x0011: /* 'BrtShortSt' */
  14690. case 0x0012: /* 'BrtShortIsst' */
  14691. case 0x003E: /* 'BrtCellRString' */
  14692. p = ({t:val[2]});
  14693. switch(val[2]) {
  14694. case 'n': p.v = val[1]; break;
  14695. case 's': sstr = strs[val[1]]; p.v = sstr.t; p.r = sstr.r; break;
  14696. case 'b': p.v = val[1] ? true : false; break;
  14697. case 'e': p.v = val[1]; if(opts.cellText !== false) p.w = BErr[p.v]; break;
  14698. case 'str': p.t = 's'; p.v = val[1]; break;
  14699. case 'is': p.t = 's'; p.v = val[1].t; break;
  14700. }
  14701. if((cf = styles.CellXf[val[0].iStyleRef])) safe_format(p,cf.numFmtId,null,opts, themes, styles);
  14702. C = val[0].c == -1 ? C + 1 : val[0].c;
  14703. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  14704. else s[encode_col(C) + rr] = p;
  14705. if(opts.cellFormula) {
  14706. af = false;
  14707. for(ai = 0; ai < arrayf.length; ++ai) {
  14708. var aii = arrayf[ai];
  14709. if(row.r >= aii[0].s.r && row.r <= aii[0].e.r)
  14710. if(C >= aii[0].s.c && C <= aii[0].e.c) {
  14711. p.F = encode_range(aii[0]); af = true;
  14712. }
  14713. }
  14714. if(!af && val.length > 3) p.f = val[3];
  14715. }
  14716. if(refguess.s.r > row.r) refguess.s.r = row.r;
  14717. if(refguess.s.c > C) refguess.s.c = C;
  14718. if(refguess.e.r < row.r) refguess.e.r = row.r;
  14719. if(refguess.e.c < C) refguess.e.c = C;
  14720. if(opts.cellDates && cf && p.t == 'n' && fmt_is_date(table_fmt[cf.numFmtId])) {
  14721. 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); }
  14722. }
  14723. if(cm) {
  14724. if(cm.type == 'XLDAPR') p.D = true;
  14725. cm = void 0;
  14726. }
  14727. if(vm) vm = void 0;
  14728. break;
  14729. case 0x0001: /* 'BrtCellBlank' */
  14730. case 0x000C: /* 'BrtShortBlank' */
  14731. if(!opts.sheetStubs || pass) break;
  14732. p = ({t:'z',v:void 0});
  14733. C = val[0].c == -1 ? C + 1 : val[0].c;
  14734. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  14735. else s[encode_col(C) + rr] = p;
  14736. if(refguess.s.r > row.r) refguess.s.r = row.r;
  14737. if(refguess.s.c > C) refguess.s.c = C;
  14738. if(refguess.e.r < row.r) refguess.e.r = row.r;
  14739. if(refguess.e.c < C) refguess.e.c = C;
  14740. if(cm) {
  14741. if(cm.type == 'XLDAPR') p.D = true;
  14742. cm = void 0;
  14743. }
  14744. if(vm) vm = void 0;
  14745. break;
  14746. case 0x00B0: /* 'BrtMergeCell' */
  14747. merges.push(val); break;
  14748. case 0x0031: { /* 'BrtCellMeta' */
  14749. cm = ((opts.xlmeta||{}).Cell||[])[val-1];
  14750. } break;
  14751. case 0x01EE: /* 'BrtHLink' */
  14752. var rel = rels['!id'][val.relId];
  14753. if(rel) {
  14754. val.Target = rel.Target;
  14755. if(val.loc) val.Target += "#"+val.loc;
  14756. val.Rel = rel;
  14757. } else if(val.relId == '') {
  14758. val.Target = "#" + val.loc;
  14759. }
  14760. for(R=val.rfx.s.r;R<=val.rfx.e.r;++R) for(C=val.rfx.s.c;C<=val.rfx.e.c;++C) {
  14761. if(opts.dense) {
  14762. if(!s[R]) s[R] = [];
  14763. if(!s[R][C]) s[R][C] = {t:'z',v:undefined};
  14764. s[R][C].l = val;
  14765. } else {
  14766. addr = encode_cell({c:C,r:R});
  14767. if(!s[addr]) s[addr] = {t:'z',v:undefined};
  14768. s[addr].l = val;
  14769. }
  14770. }
  14771. break;
  14772. case 0x01AA: /* 'BrtArrFmla' */
  14773. if(!opts.cellFormula) break;
  14774. arrayf.push(val);
  14775. cell = ((opts.dense ? s[R][C] : s[encode_col(C) + rr]));
  14776. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  14777. cell.F = encode_range(val[0]);
  14778. break;
  14779. case 0x01AB: /* 'BrtShrFmla' */
  14780. if(!opts.cellFormula) break;
  14781. sharedf[encode_cell(val[0].s)] = val[1];
  14782. cell = (opts.dense ? s[R][C] : s[encode_col(C) + rr]);
  14783. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  14784. break;
  14785. /* identical to 'ColInfo' in XLS */
  14786. case 0x003C: /* 'BrtColInfo' */
  14787. if(!opts.cellStyles) break;
  14788. while(val.e >= val.s) {
  14789. colinfo[val.e--] = { width: val.w/256, hidden: !!(val.flags & 0x01), level: val.level };
  14790. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  14791. process_col(colinfo[val.e+1]);
  14792. }
  14793. break;
  14794. case 0x00A1: /* 'BrtBeginAFilter' */
  14795. s['!autofilter'] = { ref:encode_range(val) };
  14796. break;
  14797. case 0x01DC: /* 'BrtMargins' */
  14798. s['!margins'] = val;
  14799. break;
  14800. case 0x0093: /* 'BrtWsProp' */
  14801. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  14802. if(val.name) wb.Sheets[idx].CodeName = val.name;
  14803. if(val.above || val.left) s['!outline'] = { above: val.above, left: val.left };
  14804. break;
  14805. case 0x0089: /* 'BrtBeginWsView' */
  14806. if(!wb.Views) wb.Views = [{}];
  14807. if(!wb.Views[0]) wb.Views[0] = {};
  14808. if(val.RTL) wb.Views[0].RTL = true;
  14809. break;
  14810. case 0x01E5: /* 'BrtWsFmtInfo' */
  14811. break;
  14812. case 0x0040: /* 'BrtDVal' */
  14813. case 0x041D: /* 'BrtDVal14' */
  14814. break;
  14815. case 0x0097: /* 'BrtPane' */
  14816. break;
  14817. case 0x0098: /* 'BrtSel' */
  14818. case 0x00AF: /* 'BrtAFilterDateGroupItem' */
  14819. case 0x0284: /* 'BrtActiveX' */
  14820. case 0x0271: /* 'BrtBigName' */
  14821. case 0x0232: /* 'BrtBkHim' */
  14822. case 0x018C: /* 'BrtBrk' */
  14823. case 0x0458: /* 'BrtCFIcon' */
  14824. case 0x047A: /* 'BrtCFRuleExt' */
  14825. case 0x01D7: /* 'BrtCFVO' */
  14826. case 0x041A: /* 'BrtCFVO14' */
  14827. case 0x0289: /* 'BrtCellIgnoreEC' */
  14828. case 0x0451: /* 'BrtCellIgnoreEC14' */
  14829. case 0x024D: /* 'BrtCellSmartTagProperty' */
  14830. case 0x025F: /* 'BrtCellWatch' */
  14831. case 0x0234: /* 'BrtColor' */
  14832. case 0x041F: /* 'BrtColor14' */
  14833. case 0x00A8: /* 'BrtColorFilter' */
  14834. case 0x00AE: /* 'BrtCustomFilter' */
  14835. case 0x049C: /* 'BrtCustomFilter14' */
  14836. case 0x01F3: /* 'BrtDRef' */
  14837. case 0x01FB: /* 'BrtDXF' */
  14838. case 0x0226: /* 'BrtDrawing' */
  14839. case 0x00AB: /* 'BrtDynamicFilter' */
  14840. case 0x00A7: /* 'BrtFilter' */
  14841. case 0x0499: /* 'BrtFilter14' */
  14842. case 0x00A9: /* 'BrtIconFilter' */
  14843. case 0x049D: /* 'BrtIconFilter14' */
  14844. case 0x0227: /* 'BrtLegacyDrawing' */
  14845. case 0x0228: /* 'BrtLegacyDrawingHF' */
  14846. case 0x0295: /* 'BrtListPart' */
  14847. case 0x027F: /* 'BrtOleObject' */
  14848. case 0x01DE: /* 'BrtPageSetup' */
  14849. case 0x0219: /* 'BrtPhoneticInfo' */
  14850. case 0x01DD: /* 'BrtPrintOptions' */
  14851. case 0x0218: /* 'BrtRangeProtection' */
  14852. case 0x044F: /* 'BrtRangeProtection14' */
  14853. case 0x02A8: /* 'BrtRangeProtectionIso' */
  14854. case 0x0450: /* 'BrtRangeProtectionIso14' */
  14855. case 0x0400: /* 'BrtRwDescent' */
  14856. case 0x0297: /* 'BrtSheetCalcProp' */
  14857. case 0x0217: /* 'BrtSheetProtection' */
  14858. case 0x02A6: /* 'BrtSheetProtectionIso' */
  14859. case 0x01F8: /* 'BrtSlc' */
  14860. case 0x0413: /* 'BrtSparkline' */
  14861. case 0x01AC: /* 'BrtTable' */
  14862. case 0x00AA: /* 'BrtTop10Filter' */
  14863. case 0x0C00: /* 'BrtUid' */
  14864. case 0x0032: /* 'BrtValueMeta' */
  14865. case 0x0816: /* 'BrtWebExtension' */
  14866. case 0x0415: /* 'BrtWsFmtInfoEx14' */
  14867. break;
  14868. case 0x0023: /* 'BrtFRTBegin' */
  14869. pass = true; break;
  14870. case 0x0024: /* 'BrtFRTEnd' */
  14871. pass = false; break;
  14872. case 0x0025: /* 'BrtACBegin' */
  14873. state.push(RT); pass = true; break;
  14874. case 0x0026: /* 'BrtACEnd' */
  14875. state.pop(); pass = false; break;
  14876. default:
  14877. if(RR.T){/* empty */}
  14878. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  14879. }
  14880. }, opts);
  14881. delete opts.supbooks;
  14882. delete opts['!row'];
  14883. 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);
  14884. if(opts.sheetRows && s["!ref"]) {
  14885. var tmpref = safe_decode_range(s["!ref"]);
  14886. if(opts.sheetRows <= +tmpref.e.r) {
  14887. tmpref.e.r = opts.sheetRows - 1;
  14888. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  14889. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  14890. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  14891. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  14892. s["!fullref"] = s["!ref"];
  14893. s["!ref"] = encode_range(tmpref);
  14894. }
  14895. }
  14896. if(merges.length > 0) s["!merges"] = merges;
  14897. if(colinfo.length > 0) s["!cols"] = colinfo;
  14898. if(rowinfo.length > 0) s["!rows"] = rowinfo;
  14899. return s;
  14900. }
  14901. /* TODO: something useful -- this is a stub */
  14902. function write_ws_bin_cell(ba, cell, R, C, opts, ws, last_seen) {
  14903. if(cell.v === undefined) return false;
  14904. var vv = "";
  14905. switch(cell.t) {
  14906. case 'b': vv = cell.v ? "1" : "0"; break;
  14907. case 'd': // no BrtCellDate :(
  14908. cell = dup(cell);
  14909. cell.z = cell.z || table_fmt[14];
  14910. cell.v = datenum(parseDate(cell.v)); cell.t = 'n';
  14911. break;
  14912. /* falls through */
  14913. case 'n': case 'e': vv = ''+cell.v; break;
  14914. default: vv = cell.v; break;
  14915. }
  14916. var o = ({r:R, c:C});
  14917. /* TODO: cell style */
  14918. o.s = get_cell_style(opts.cellXfs, cell, opts);
  14919. if(cell.l) ws['!links'].push([encode_cell(o), cell.l]);
  14920. if(cell.c) ws['!comments'].push([encode_cell(o), cell.c]);
  14921. switch(cell.t) {
  14922. case 's': case 'str':
  14923. if(opts.bookSST) {
  14924. vv = get_sst_id(opts.Strings, (cell.v), opts.revStrings);
  14925. o.t = "s"; o.v = vv;
  14926. if(last_seen) write_record(ba, 0x0012 /* BrtShortIsst */, write_BrtShortIsst(cell, o));
  14927. else write_record(ba, 0x0007 /* BrtCellIsst */, write_BrtCellIsst(cell, o));
  14928. } else {
  14929. o.t = "str";
  14930. if(last_seen) write_record(ba, 0x0011 /* BrtShortSt */, write_BrtShortSt(cell, o));
  14931. else write_record(ba, 0x0006 /* BrtCellSt */, write_BrtCellSt(cell, o));
  14932. }
  14933. return true;
  14934. case 'n':
  14935. /* TODO: determine threshold for Real vs RK */
  14936. if(cell.v == (cell.v | 0) && cell.v > -1000 && cell.v < 1000) {
  14937. if(last_seen) write_record(ba, 0x000D /* BrtShortRk */, write_BrtShortRk(cell, o));
  14938. else write_record(ba, 0x0002 /* BrtCellRk */, write_BrtCellRk(cell, o));
  14939. } else {
  14940. if(last_seen) write_record(ba, 0x0010 /* BrtShortReal */, write_BrtShortReal(cell, o));
  14941. else write_record(ba, 0x0005 /* BrtCellReal */, write_BrtCellReal(cell, o));
  14942. } return true;
  14943. case 'b':
  14944. o.t = "b";
  14945. if(last_seen) write_record(ba, 0x000F /* BrtShortBool */, write_BrtShortBool(cell, o));
  14946. else write_record(ba, 0x0004 /* BrtCellBool */, write_BrtCellBool(cell, o));
  14947. return true;
  14948. case 'e':
  14949. o.t = "e";
  14950. if(last_seen) write_record(ba, 0x000E /* BrtShortError */, write_BrtShortError(cell, o));
  14951. else write_record(ba, 0x0003 /* BrtCellError */, write_BrtCellError(cell, o));
  14952. return true;
  14953. }
  14954. if(last_seen) write_record(ba, 0x000C /* BrtShortBlank */, write_BrtShortBlank(cell, o));
  14955. else write_record(ba, 0x0001 /* BrtCellBlank */, write_BrtCellBlank(cell, o));
  14956. return true;
  14957. }
  14958. function write_CELLTABLE(ba, ws, idx, opts) {
  14959. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  14960. write_record(ba, 0x0091 /* BrtBeginSheetData */);
  14961. var dense = Array.isArray(ws);
  14962. var cap = range.e.r;
  14963. if(ws['!rows']) cap = Math.max(range.e.r, ws['!rows'].length - 1);
  14964. for(var R = range.s.r; R <= cap; ++R) {
  14965. rr = encode_row(R);
  14966. /* [ACCELLTABLE] */
  14967. /* BrtRowHdr */
  14968. write_row_header(ba, ws, range, R);
  14969. var last_seen = false;
  14970. if(R <= range.e.r) for(var C = range.s.c; C <= range.e.c; ++C) {
  14971. /* *16384CELL */
  14972. if(R === range.s.r) cols[C] = encode_col(C);
  14973. ref = cols[C] + rr;
  14974. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  14975. if(!cell) { last_seen = false; continue; }
  14976. /* write cell */
  14977. last_seen = write_ws_bin_cell(ba, cell, R, C, opts, ws, last_seen);
  14978. }
  14979. }
  14980. write_record(ba, 0x0092 /* BrtEndSheetData */);
  14981. }
  14982. function write_MERGECELLS(ba, ws) {
  14983. if(!ws || !ws['!merges']) return;
  14984. write_record(ba, 0x00B1 /* BrtBeginMergeCells */, write_BrtBeginMergeCells(ws['!merges'].length));
  14985. ws['!merges'].forEach(function(m) { write_record(ba, 0x00B0 /* BrtMergeCell */, write_BrtMergeCell(m)); });
  14986. write_record(ba, 0x00B2 /* BrtEndMergeCells */);
  14987. }
  14988. function write_COLINFOS(ba, ws) {
  14989. if(!ws || !ws['!cols']) return;
  14990. write_record(ba, 0x0186 /* BrtBeginColInfos */);
  14991. ws['!cols'].forEach(function(m, i) { if(m) write_record(ba, 0x003C /* 'BrtColInfo' */, write_BrtColInfo(i, m)); });
  14992. write_record(ba, 0x0187 /* BrtEndColInfos */);
  14993. }
  14994. function write_IGNOREECS(ba, ws) {
  14995. if(!ws || !ws['!ref']) return;
  14996. write_record(ba, 0x0288 /* BrtBeginCellIgnoreECs */);
  14997. write_record(ba, 0x0289 /* BrtCellIgnoreEC */, write_BrtCellIgnoreEC(safe_decode_range(ws['!ref'])));
  14998. write_record(ba, 0x028A /* BrtEndCellIgnoreECs */);
  14999. }
  15000. function write_HLINKS(ba, ws, rels) {
  15001. /* *BrtHLink */
  15002. ws['!links'].forEach(function(l) {
  15003. if(!l[1].Target) return;
  15004. var rId = add_rels(rels, -1, l[1].Target.replace(/#.*$/, ""), RELS.HLINK);
  15005. write_record(ba, 0x01EE /* BrtHLink */, write_BrtHLink(l, rId));
  15006. });
  15007. delete ws['!links'];
  15008. }
  15009. function write_LEGACYDRAWING(ba, ws, idx, rels) {
  15010. /* [BrtLegacyDrawing] */
  15011. if(ws['!comments'].length > 0) {
  15012. var rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  15013. write_record(ba, 0x0227 /* BrtLegacyDrawing */, write_RelID("rId" + rId));
  15014. ws['!legacy'] = rId;
  15015. }
  15016. }
  15017. function write_AUTOFILTER(ba, ws, wb, idx) {
  15018. if(!ws['!autofilter']) return;
  15019. var data = ws['!autofilter'];
  15020. var ref = typeof data.ref === "string" ? data.ref : encode_range(data.ref);
  15021. /* Update FilterDatabase defined name for the worksheet */
  15022. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  15023. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  15024. var names = wb.Workbook.Names;
  15025. var range = decode_range(ref);
  15026. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  15027. for(var i = 0; i < names.length; ++i) {
  15028. var name = names[i];
  15029. if(name.Name != '_xlnm._FilterDatabase') continue;
  15030. if(name.Sheet != idx) continue;
  15031. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  15032. }
  15033. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  15034. write_record(ba, 0x00A1 /* BrtBeginAFilter */, write_UncheckedRfX(safe_decode_range(ref)));
  15035. /* *FILTERCOLUMN */
  15036. /* [SORTSTATE] */
  15037. /* BrtEndAFilter */
  15038. write_record(ba, 0x00A2 /* BrtEndAFilter */);
  15039. }
  15040. function write_WSVIEWS2(ba, ws, Workbook) {
  15041. write_record(ba, 0x0085 /* BrtBeginWsViews */);
  15042. { /* 1*WSVIEW2 */
  15043. /* [ACUID] */
  15044. write_record(ba, 0x0089 /* BrtBeginWsView */, write_BrtBeginWsView(ws, Workbook));
  15045. /* [BrtPane] */
  15046. /* *4BrtSel */
  15047. /* *4SXSELECT */
  15048. /* *FRT */
  15049. write_record(ba, 0x008A /* BrtEndWsView */);
  15050. }
  15051. /* *FRT */
  15052. write_record(ba, 0x0086 /* BrtEndWsViews */);
  15053. }
  15054. function write_WSFMTINFO() {
  15055. /* [ACWSFMTINFO] */
  15056. // write_record(ba, 0x01E5 /* BrtWsFmtInfo */, write_BrtWsFmtInfo(ws));
  15057. }
  15058. function write_SHEETPROTECT(ba, ws) {
  15059. if(!ws['!protect']) return;
  15060. /* [BrtSheetProtectionIso] */
  15061. write_record(ba, 0x0217 /* BrtSheetProtection */, write_BrtSheetProtection(ws['!protect']));
  15062. }
  15063. function write_ws_bin(idx, opts, wb, rels) {
  15064. var ba = buf_array();
  15065. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  15066. var c = s; try { if(wb && wb.Workbook) c = wb.Workbook.Sheets[idx].CodeName || c; } catch(e) {}
  15067. var r = safe_decode_range(ws['!ref'] || "A1");
  15068. if(r.e.c > 0x3FFF || r.e.r > 0xFFFFF) {
  15069. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:XFD1048576");
  15070. r.e.c = Math.min(r.e.c, 0x3FFF);
  15071. r.e.r = Math.min(r.e.c, 0xFFFFF);
  15072. }
  15073. ws['!links'] = [];
  15074. /* passed back to write_zip and removed there */
  15075. ws['!comments'] = [];
  15076. write_record(ba, 0x0081 /* BrtBeginSheet */);
  15077. if(wb.vbaraw || ws['!outline']) write_record(ba, 0x0093 /* BrtWsProp */, write_BrtWsProp(c, ws['!outline']));
  15078. write_record(ba, 0x0094 /* BrtWsDim */, write_BrtWsDim(r));
  15079. write_WSVIEWS2(ba, ws, wb.Workbook);
  15080. write_WSFMTINFO(ba, ws);
  15081. write_COLINFOS(ba, ws, idx, opts, wb);
  15082. write_CELLTABLE(ba, ws, idx, opts, wb);
  15083. /* [BrtSheetCalcProp] */
  15084. write_SHEETPROTECT(ba, ws);
  15085. /* *([BrtRangeProtectionIso] BrtRangeProtection) */
  15086. /* [SCENMAN] */
  15087. write_AUTOFILTER(ba, ws, wb, idx);
  15088. /* [SORTSTATE] */
  15089. /* [DCON] */
  15090. /* [USERSHVIEWS] */
  15091. write_MERGECELLS(ba, ws);
  15092. /* [BrtPhoneticInfo] */
  15093. /* *CONDITIONALFORMATTING */
  15094. /* [DVALS] */
  15095. write_HLINKS(ba, ws, rels);
  15096. /* [BrtPrintOptions] */
  15097. if(ws['!margins']) write_record(ba, 0x01DC /* BrtMargins */, write_BrtMargins(ws['!margins']));
  15098. /* [BrtPageSetup] */
  15099. /* [HEADERFOOTER] */
  15100. /* [RWBRK] */
  15101. /* [COLBRK] */
  15102. /* *BrtBigName */
  15103. /* [CELLWATCHES] */
  15104. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) write_IGNOREECS(ba, ws);
  15105. /* [SMARTTAGS] */
  15106. /* [BrtDrawing] */
  15107. write_LEGACYDRAWING(ba, ws, idx, rels);
  15108. /* [BrtLegacyDrawingHF] */
  15109. /* [BrtBkHim] */
  15110. /* [OLEOBJECTS] */
  15111. /* [ACTIVEXCONTROLS] */
  15112. /* [WEBPUBITEMS] */
  15113. /* [LISTPARTS] */
  15114. /* FRTWORKSHEET */
  15115. write_record(ba, 0x0082 /* BrtEndSheet */);
  15116. return ba.end();
  15117. }
  15118. function parse_Cache(data) {
  15119. var col = [];
  15120. var num = data.match(/^<c:numCache>/);
  15121. var f;
  15122. /* 21.2.2.150 pt CT_NumVal */
  15123. (data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
  15124. var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
  15125. if(!q) return;
  15126. col[+q[1]] = num ? +q[2] : q[2];
  15127. });
  15128. /* 21.2.2.71 formatCode CT_Xstring */
  15129. var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);
  15130. (data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });
  15131. return [col, nf, f];
  15132. }
  15133. /* 21.2 DrawingML - Charts */
  15134. function parse_chart(data, name, opts, rels, wb, csheet) {
  15135. var cs = ((csheet || {"!type":"chart"}));
  15136. if(!data) return csheet;
  15137. /* 21.2.2.27 chart CT_Chart */
  15138. var C = 0, R = 0, col = "A";
  15139. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  15140. /* 21.2.2.120 numCache CT_NumData */
  15141. (data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
  15142. var cache = parse_Cache(nc);
  15143. refguess.s.r = refguess.s.c = 0;
  15144. refguess.e.c = C;
  15145. col = encode_col(C);
  15146. cache[0].forEach(function(n,i) {
  15147. cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
  15148. R = i;
  15149. });
  15150. if(refguess.e.r < R) refguess.e.r = R;
  15151. ++C;
  15152. });
  15153. if(C > 0) cs["!ref"] = encode_range(refguess);
  15154. return cs;
  15155. }
  15156. /* 18.3 Worksheets also covers Chartsheets */
  15157. function parse_cs_xml(data, opts, idx, rels, wb) {
  15158. if(!data) return data;
  15159. /* 18.3.1.12 chartsheet CT_ChartSheet */
  15160. if(!rels) rels = {'!id':{}};
  15161. var s = ({'!type':"chart", '!drawel':null, '!rel':""});
  15162. var m;
  15163. /* 18.3.1.83 sheetPr CT_ChartsheetPr */
  15164. var sheetPr = data.match(sheetprregex);
  15165. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  15166. /* 18.3.1.36 drawing CT_Drawing */
  15167. if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];
  15168. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  15169. return s;
  15170. }
  15171. function write_cs_xml(idx, opts, wb, rels) {
  15172. var o = [XML_HEADER, writextag('chartsheet', null, {
  15173. 'xmlns': XMLNS_main[0],
  15174. 'xmlns:r': XMLNS.r
  15175. })];
  15176. o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
  15177. add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  15178. if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
  15179. return o.join("");
  15180. }
  15181. /* [MS-XLSB] 2.4.331 BrtCsProp */
  15182. function parse_BrtCsProp(data, length) {
  15183. data.l += 10;
  15184. var name = parse_XLWideString(data, length - 10);
  15185. return { name: name };
  15186. }
  15187. /* [MS-XLSB] 2.1.7.7 Chart Sheet */
  15188. function parse_cs_bin(data, opts, idx, rels, wb) {
  15189. if(!data) return data;
  15190. if(!rels) rels = {'!id':{}};
  15191. var s = {'!type':"chart", '!drawel':null, '!rel':""};
  15192. var state = [];
  15193. var pass = false;
  15194. recordhopper(data, function cs_parse(val, R, RT) {
  15195. switch(RT) {
  15196. case 0x0226: /* 'BrtDrawing' */
  15197. s['!rel'] = val; break;
  15198. case 0x028B: /* 'BrtCsProp' */
  15199. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  15200. if(val.name) wb.Sheets[idx].CodeName = val.name;
  15201. break;
  15202. case 0x0232: /* 'BrtBkHim' */
  15203. case 0x028C: /* 'BrtCsPageSetup' */
  15204. case 0x029D: /* 'BrtCsProtection' */
  15205. case 0x02A7: /* 'BrtCsProtectionIso' */
  15206. case 0x0227: /* 'BrtLegacyDrawing' */
  15207. case 0x0228: /* 'BrtLegacyDrawingHF' */
  15208. case 0x01DC: /* 'BrtMargins' */
  15209. case 0x0C00: /* 'BrtUid' */
  15210. break;
  15211. case 0x0023: /* 'BrtFRTBegin' */
  15212. pass = true; break;
  15213. case 0x0024: /* 'BrtFRTEnd' */
  15214. pass = false; break;
  15215. case 0x0025: /* 'BrtACBegin' */
  15216. state.push(RT); break;
  15217. case 0x0026: /* 'BrtACEnd' */
  15218. state.pop(); break;
  15219. default:
  15220. if(R.T > 0) state.push(RT);
  15221. else if(R.T < 0) state.pop();
  15222. else if(!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16));
  15223. }
  15224. }, opts);
  15225. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  15226. return s;
  15227. }
  15228. function write_cs_bin() {
  15229. var ba = buf_array();
  15230. write_record(ba, 0x0081 /* BrtBeginSheet */);
  15231. /* [BrtCsProp] */
  15232. /* CSVIEWS */
  15233. /* [[BrtCsProtectionIso] BrtCsProtection] */
  15234. /* [USERCSVIEWS] */
  15235. /* [BrtMargins] */
  15236. /* [BrtCsPageSetup] */
  15237. /* [HEADERFOOTER] */
  15238. /* BrtDrawing */
  15239. /* [BrtLegacyDrawing] */
  15240. /* [BrtLegacyDrawingHF] */
  15241. /* [BrtBkHim] */
  15242. /* [WEBPUBITEMS] */
  15243. /* FRTCHARTSHEET */
  15244. write_record(ba, 0x0082 /* BrtEndSheet */);
  15245. return ba.end();
  15246. }
  15247. /* 18.2.28 (CT_WorkbookProtection) Defaults */
  15248. var WBPropsDef = [
  15249. ['allowRefreshQuery', false, "bool"],
  15250. ['autoCompressPictures', true, "bool"],
  15251. ['backupFile', false, "bool"],
  15252. ['checkCompatibility', false, "bool"],
  15253. ['CodeName', ''],
  15254. ['date1904', false, "bool"],
  15255. ['defaultThemeVersion', 0, "int"],
  15256. ['filterPrivacy', false, "bool"],
  15257. ['hidePivotFieldList', false, "bool"],
  15258. ['promptedSolutions', false, "bool"],
  15259. ['publishItems', false, "bool"],
  15260. ['refreshAllConnections', false, "bool"],
  15261. ['saveExternalLinkValues', true, "bool"],
  15262. ['showBorderUnselectedTables', true, "bool"],
  15263. ['showInkAnnotation', true, "bool"],
  15264. ['showObjects', 'all'],
  15265. ['showPivotChartFilter', false, "bool"],
  15266. ['updateLinks', 'userSet']
  15267. ];
  15268. /* 18.2.30 (CT_BookView) Defaults */
  15269. var WBViewDef = [
  15270. ['activeTab', 0, "int"],
  15271. ['autoFilterDateGrouping', true, "bool"],
  15272. ['firstSheet', 0, "int"],
  15273. ['minimized', false, "bool"],
  15274. ['showHorizontalScroll', true, "bool"],
  15275. ['showSheetTabs', true, "bool"],
  15276. ['showVerticalScroll', true, "bool"],
  15277. ['tabRatio', 600, "int"],
  15278. ['visibility', 'visible']
  15279. //window{Height,Width}, {x,y}Window
  15280. ];
  15281. /* 18.2.19 (CT_Sheet) Defaults */
  15282. var SheetDef = [
  15283. //['state', 'visible']
  15284. ];
  15285. /* 18.2.2 (CT_CalcPr) Defaults */
  15286. var CalcPrDef = [
  15287. ['calcCompleted', 'true'],
  15288. ['calcMode', 'auto'],
  15289. ['calcOnSave', 'true'],
  15290. ['concurrentCalc', 'true'],
  15291. ['fullCalcOnLoad', 'false'],
  15292. ['fullPrecision', 'true'],
  15293. ['iterate', 'false'],
  15294. ['iterateCount', '100'],
  15295. ['iterateDelta', '0.001'],
  15296. ['refMode', 'A1']
  15297. ];
  15298. /* 18.2.3 (CT_CustomWorkbookView) Defaults */
  15299. /*var CustomWBViewDef = [
  15300. ['autoUpdate', 'false'],
  15301. ['changesSavedWin', 'false'],
  15302. ['includeHiddenRowCol', 'true'],
  15303. ['includePrintSettings', 'true'],
  15304. ['maximized', 'false'],
  15305. ['minimized', 'false'],
  15306. ['onlySync', 'false'],
  15307. ['personalView', 'false'],
  15308. ['showComments', 'commIndicator'],
  15309. ['showFormulaBar', 'true'],
  15310. ['showHorizontalScroll', 'true'],
  15311. ['showObjects', 'all'],
  15312. ['showSheetTabs', 'true'],
  15313. ['showStatusbar', 'true'],
  15314. ['showVerticalScroll', 'true'],
  15315. ['tabRatio', '600'],
  15316. ['xWindow', '0'],
  15317. ['yWindow', '0']
  15318. ];*/
  15319. function push_defaults_array(target, defaults) {
  15320. for(var j = 0; j != target.length; ++j) { var w = target[j];
  15321. for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
  15322. if(w[z[0]] == null) w[z[0]] = z[1];
  15323. else switch(z[2]) {
  15324. case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
  15325. case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
  15326. }
  15327. }
  15328. }
  15329. }
  15330. function push_defaults(target, defaults) {
  15331. for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
  15332. if(target[z[0]] == null) target[z[0]] = z[1];
  15333. else switch(z[2]) {
  15334. case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
  15335. case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
  15336. }
  15337. }
  15338. }
  15339. function parse_wb_defaults(wb) {
  15340. push_defaults(wb.WBProps, WBPropsDef);
  15341. push_defaults(wb.CalcPr, CalcPrDef);
  15342. push_defaults_array(wb.WBView, WBViewDef);
  15343. push_defaults_array(wb.Sheets, SheetDef);
  15344. _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
  15345. }
  15346. function safe1904(wb) {
  15347. /* TODO: store date1904 somewhere else */
  15348. if(!wb.Workbook) return "false";
  15349. if(!wb.Workbook.WBProps) return "false";
  15350. return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
  15351. }
  15352. var badchars = "][*?\/\\".split("");
  15353. function check_ws_name(n, safe) {
  15354. if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
  15355. var _good = true;
  15356. badchars.forEach(function(c) {
  15357. if(n.indexOf(c) == -1) return;
  15358. if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
  15359. _good = false;
  15360. });
  15361. return _good;
  15362. }
  15363. function check_wb_names(N, S, codes) {
  15364. N.forEach(function(n,i) {
  15365. check_ws_name(n);
  15366. for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
  15367. if(codes) {
  15368. var cn = (S && S[i] && S[i].CodeName) || n;
  15369. if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
  15370. }
  15371. });
  15372. }
  15373. function check_wb(wb) {
  15374. if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
  15375. if(!wb.SheetNames.length) throw new Error("Workbook is empty");
  15376. var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
  15377. check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
  15378. for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
  15379. /* TODO: validate workbook */
  15380. }
  15381. /* 18.2 Workbook */
  15382. var wbnsregex = /<\w+:workbook/;
  15383. function parse_wb_xml(data, opts) {
  15384. if(!data) throw new Error("Could not find file");
  15385. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" };
  15386. var pass = false, xmlns = "xmlns";
  15387. var dname = {}, dnstart = 0;
  15388. data.replace(tagregex, function xml_wb(x, idx) {
  15389. var y = parsexmltag(x);
  15390. switch(strip_ns(y[0])) {
  15391. case '<?xml': break;
  15392. /* 18.2.27 workbook CT_Workbook 1 */
  15393. case '<workbook':
  15394. if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
  15395. wb.xmlns = y[xmlns];
  15396. break;
  15397. case '</workbook>': break;
  15398. /* 18.2.13 fileVersion CT_FileVersion ? */
  15399. case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
  15400. case '<fileVersion/>': case '</fileVersion>': break;
  15401. /* 18.2.12 fileSharing CT_FileSharing ? */
  15402. case '<fileSharing':
  15403. break;
  15404. case '<fileSharing/>': break;
  15405. /* 18.2.28 workbookPr CT_WorkbookPr ? */
  15406. case '<workbookPr':
  15407. case '<workbookPr/>':
  15408. WBPropsDef.forEach(function(w) {
  15409. if(y[w[0]] == null) return;
  15410. switch(w[2]) {
  15411. case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
  15412. case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
  15413. default: wb.WBProps[w[0]] = y[w[0]];
  15414. }
  15415. });
  15416. if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
  15417. break;
  15418. case '</workbookPr>': break;
  15419. /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
  15420. case '<workbookProtection':
  15421. break;
  15422. case '<workbookProtection/>': break;
  15423. /* 18.2.1 bookViews CT_BookViews ? */
  15424. case '<bookViews': case '<bookViews>': case '</bookViews>': break;
  15425. /* 18.2.30 workbookView CT_BookView + */
  15426. case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
  15427. case '</workbookView>': break;
  15428. /* 18.2.20 sheets CT_Sheets 1 */
  15429. case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
  15430. /* 18.2.19 sheet CT_Sheet + */
  15431. case '<sheet':
  15432. switch(y.state) {
  15433. case "hidden": y.Hidden = 1; break;
  15434. case "veryHidden": y.Hidden = 2; break;
  15435. default: y.Hidden = 0;
  15436. }
  15437. delete y.state;
  15438. y.name = unescapexml(utf8read(y.name));
  15439. delete y[0]; wb.Sheets.push(y); break;
  15440. case '</sheet>': break;
  15441. /* 18.2.15 functionGroups CT_FunctionGroups ? */
  15442. case '<functionGroups': case '<functionGroups/>': break;
  15443. /* 18.2.14 functionGroup CT_FunctionGroup + */
  15444. case '<functionGroup': break;
  15445. /* 18.2.9 externalReferences CT_ExternalReferences ? */
  15446. case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
  15447. /* 18.2.8 externalReference CT_ExternalReference + */
  15448. case '<externalReference': break;
  15449. /* 18.2.6 definedNames CT_DefinedNames ? */
  15450. case '<definedNames/>': break;
  15451. case '<definedNames>': case '<definedNames': pass=true; break;
  15452. case '</definedNames>': pass=false; break;
  15453. /* 18.2.5 definedName CT_DefinedName + */
  15454. case '<definedName': {
  15455. dname = {};
  15456. dname.Name = utf8read(y.name);
  15457. if(y.comment) dname.Comment = y.comment;
  15458. if(y.localSheetId) dname.Sheet = +y.localSheetId;
  15459. if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
  15460. dnstart = idx + x.length;
  15461. } break;
  15462. case '</definedName>': {
  15463. dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
  15464. wb.Names.push(dname);
  15465. } break;
  15466. case '<definedName/>': break;
  15467. /* 18.2.2 calcPr CT_CalcPr ? */
  15468. case '<calcPr': delete y[0]; wb.CalcPr = y; break;
  15469. case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
  15470. case '</calcPr>': break;
  15471. /* 18.2.16 oleSize CT_OleSize ? (ref required) */
  15472. case '<oleSize': break;
  15473. /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
  15474. case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
  15475. /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
  15476. case '<customWorkbookView': case '</customWorkbookView>': break;
  15477. /* 18.2.18 pivotCaches CT_PivotCaches ? */
  15478. case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
  15479. /* 18.2.17 pivotCache CT_PivotCache ? */
  15480. case '<pivotCache': break;
  15481. /* 18.2.21 smartTagPr CT_SmartTagPr ? */
  15482. case '<smartTagPr': case '<smartTagPr/>': break;
  15483. /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
  15484. case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
  15485. /* 18.2.22 smartTagType CT_SmartTagType ? */
  15486. case '<smartTagType': break;
  15487. /* 18.2.24 webPublishing CT_WebPublishing ? */
  15488. case '<webPublishing': case '<webPublishing/>': break;
  15489. /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
  15490. case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
  15491. /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
  15492. case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
  15493. /* 18.2.25 webPublishObject CT_WebPublishObject ? */
  15494. case '<webPublishObject': break;
  15495. /* 18.2.10 extLst CT_ExtensionList ? */
  15496. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  15497. /* 18.2.7 ext CT_Extension + */
  15498. case '<ext': pass=true; break; //TODO: check with versions of excel
  15499. case '</ext>': pass=false; break;
  15500. /* Others */
  15501. case '<ArchID': break;
  15502. case '<AlternateContent':
  15503. case '<AlternateContent>': pass=true; break;
  15504. case '</AlternateContent>': pass=false; break;
  15505. /* TODO */
  15506. case '<revisionPtr': break;
  15507. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
  15508. }
  15509. return x;
  15510. });
  15511. if(XMLNS_main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  15512. parse_wb_defaults(wb);
  15513. return wb;
  15514. }
  15515. function write_wb_xml(wb) {
  15516. var o = [XML_HEADER];
  15517. o[o.length] = writextag('workbook', null, {
  15518. 'xmlns': XMLNS_main[0],
  15519. //'xmlns:mx': XMLNS.mx,
  15520. //'xmlns:s': XMLNS_main[0],
  15521. 'xmlns:r': XMLNS.r
  15522. });
  15523. var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);
  15524. /* fileVersion */
  15525. /* fileSharing */
  15526. var workbookPr = ({codeName:"ThisWorkbook"});
  15527. if(wb.Workbook && wb.Workbook.WBProps) {
  15528. WBPropsDef.forEach(function(x) {
  15529. if((wb.Workbook.WBProps[x[0]]) == null) return;
  15530. if((wb.Workbook.WBProps[x[0]]) == x[1]) return;
  15531. workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]);
  15532. });
  15533. if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
  15534. }
  15535. o[o.length] = (writextag('workbookPr', null, workbookPr));
  15536. /* workbookProtection */
  15537. var sheets = wb.Workbook && wb.Workbook.Sheets || [];
  15538. var i = 0;
  15539. /* bookViews only written if first worksheet is hidden */
  15540. if(sheets && sheets[0] && !!sheets[0].Hidden) {
  15541. o[o.length] = "<bookViews>";
  15542. for(i = 0; i != wb.SheetNames.length; ++i) {
  15543. if(!sheets[i]) break;
  15544. if(!sheets[i].Hidden) break;
  15545. }
  15546. if(i == wb.SheetNames.length) i = 0;
  15547. o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
  15548. o[o.length] = "</bookViews>";
  15549. }
  15550. o[o.length] = "<sheets>";
  15551. for(i = 0; i != wb.SheetNames.length; ++i) {
  15552. var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))});
  15553. sht.sheetId = ""+(i+1);
  15554. sht["r:id"] = "rId"+(i+1);
  15555. if(sheets[i]) switch(sheets[i].Hidden) {
  15556. case 1: sht.state = "hidden"; break;
  15557. case 2: sht.state = "veryHidden"; break;
  15558. }
  15559. o[o.length] = (writextag('sheet',null,sht));
  15560. }
  15561. o[o.length] = "</sheets>";
  15562. /* functionGroups */
  15563. /* externalReferences */
  15564. if(write_names) {
  15565. o[o.length] = "<definedNames>";
  15566. if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
  15567. var d = {name:n.Name};
  15568. if(n.Comment) d.comment = n.Comment;
  15569. if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
  15570. if(n.Hidden) d.hidden = "1";
  15571. if(!n.Ref) return;
  15572. o[o.length] = writextag('definedName', escapexml(n.Ref), d);
  15573. });
  15574. o[o.length] = "</definedNames>";
  15575. }
  15576. /* calcPr */
  15577. /* oleSize */
  15578. /* customWorkbookViews */
  15579. /* pivotCaches */
  15580. /* smartTagPr */
  15581. /* smartTagTypes */
  15582. /* webPublishing */
  15583. /* fileRecoveryPr */
  15584. /* webPublishObjects */
  15585. /* extLst */
  15586. if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
  15587. return o.join("");
  15588. }
  15589. /* [MS-XLSB] 2.4.304 BrtBundleSh */
  15590. function parse_BrtBundleSh(data, length) {
  15591. var z = {};
  15592. z.Hidden = data.read_shift(4); //hsState ST_SheetState
  15593. z.iTabID = data.read_shift(4);
  15594. z.strRelID = parse_RelID(data,length-8);
  15595. z.name = parse_XLWideString(data);
  15596. return z;
  15597. }
  15598. function write_BrtBundleSh(data, o) {
  15599. if(!o) o = new_buf(127);
  15600. o.write_shift(4, data.Hidden);
  15601. o.write_shift(4, data.iTabID);
  15602. write_RelID(data.strRelID, o);
  15603. write_XLWideString(data.name.slice(0,31), o);
  15604. return o.length > o.l ? o.slice(0, o.l) : o;
  15605. }
  15606. /* [MS-XLSB] 2.4.815 BrtWbProp */
  15607. function parse_BrtWbProp(data, length) {
  15608. var o = ({});
  15609. var flags = data.read_shift(4);
  15610. o.defaultThemeVersion = data.read_shift(4);
  15611. var strName = (length > 8) ? parse_XLWideString(data) : "";
  15612. if(strName.length > 0) o.CodeName = strName;
  15613. o.autoCompressPictures = !!(flags & 0x10000);
  15614. o.backupFile = !!(flags & 0x40);
  15615. o.checkCompatibility = !!(flags & 0x1000);
  15616. o.date1904 = !!(flags & 0x01);
  15617. o.filterPrivacy = !!(flags & 0x08);
  15618. o.hidePivotFieldList = !!(flags & 0x400);
  15619. o.promptedSolutions = !!(flags & 0x10);
  15620. o.publishItems = !!(flags & 0x800);
  15621. o.refreshAllConnections = !!(flags & 0x40000);
  15622. o.saveExternalLinkValues = !!(flags & 0x80);
  15623. o.showBorderUnselectedTables = !!(flags & 0x04);
  15624. o.showInkAnnotation = !!(flags & 0x20);
  15625. o.showObjects = ["all", "placeholders", "none"][(flags >> 13) & 0x03];
  15626. o.showPivotChartFilter = !!(flags & 0x8000);
  15627. o.updateLinks = ["userSet", "never", "always"][(flags >> 8) & 0x03];
  15628. return o;
  15629. }
  15630. function write_BrtWbProp(data, o) {
  15631. if(!o) o = new_buf(72);
  15632. var flags = 0;
  15633. if(data) {
  15634. /* TODO: mirror parse_BrtWbProp fields */
  15635. if(data.filterPrivacy) flags |= 0x08;
  15636. }
  15637. o.write_shift(4, flags);
  15638. o.write_shift(4, 0);
  15639. write_XLSBCodeName(data && data.CodeName || "ThisWorkbook", o);
  15640. return o.slice(0, o.l);
  15641. }
  15642. function parse_BrtFRTArchID$(data, length) {
  15643. var o = {};
  15644. data.read_shift(4);
  15645. o.ArchID = data.read_shift(4);
  15646. data.l += length - 8;
  15647. return o;
  15648. }
  15649. /* [MS-XLSB] 2.4.687 BrtName */
  15650. function parse_BrtName(data, length, opts) {
  15651. var end = data.l + length;
  15652. data.l += 4; //var flags = data.read_shift(4);
  15653. data.l += 1; //var chKey = data.read_shift(1);
  15654. var itab = data.read_shift(4);
  15655. var name = parse_XLNameWideString(data);
  15656. var formula = parse_XLSBNameParsedFormula(data, 0, opts);
  15657. var comment = parse_XLNullableWideString(data);
  15658. //if(0 /* fProc */) {
  15659. // unusedstring1: XLNullableWideString
  15660. // description: XLNullableWideString
  15661. // helpTopic: XLNullableWideString
  15662. // unusedstring2: XLNullableWideString
  15663. //}
  15664. data.l = end;
  15665. var out = ({Name:name, Ptg:formula});
  15666. if(itab < 0xFFFFFFF) out.Sheet = itab;
  15667. if(comment) out.Comment = comment;
  15668. return out;
  15669. }
  15670. /* [MS-XLSB] 2.1.7.61 Workbook */
  15671. function parse_wb_bin(data, opts) {
  15672. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
  15673. var state = [];
  15674. var pass = false;
  15675. if(!opts) opts = {};
  15676. opts.biff = 12;
  15677. var Names = [];
  15678. var supbooks = ([[]]);
  15679. supbooks.SheetNames = [];
  15680. supbooks.XTI = [];
  15681. XLSBRecordEnum[0x0010] = { n:"BrtFRTArchID$", f:parse_BrtFRTArchID$ };
  15682. recordhopper(data, function hopper_wb(val, R, RT) {
  15683. switch(RT) {
  15684. case 0x009C: /* 'BrtBundleSh' */
  15685. supbooks.SheetNames.push(val.name);
  15686. wb.Sheets.push(val); break;
  15687. case 0x0099: /* 'BrtWbProp' */
  15688. wb.WBProps = val; break;
  15689. case 0x0027: /* 'BrtName' */
  15690. if(val.Sheet != null) opts.SID = val.Sheet;
  15691. val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
  15692. delete opts.SID;
  15693. delete val.Ptg;
  15694. Names.push(val);
  15695. break;
  15696. case 0x040C: /* 'BrtNameExt' */ break;
  15697. case 0x0165: /* 'BrtSupSelf' */
  15698. case 0x0166: /* 'BrtSupSame' */
  15699. case 0x0163: /* 'BrtSupBookSrc' */
  15700. case 0x029B: /* 'BrtSupAddin' */
  15701. if(!supbooks[0].length) supbooks[0] = [RT, val];
  15702. else supbooks.push([RT, val]);
  15703. supbooks[supbooks.length - 1].XTI = [];
  15704. break;
  15705. case 0x016A: /* 'BrtExternSheet' */
  15706. if(supbooks.length === 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  15707. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val);
  15708. supbooks.XTI = supbooks.XTI.concat(val);
  15709. break;
  15710. case 0x0169: /* 'BrtPlaceholderName' */
  15711. break;
  15712. case 0x0817: /* 'BrtAbsPath15' */
  15713. case 0x009E: /* 'BrtBookView' */
  15714. case 0x008F: /* 'BrtBeginBundleShs' */
  15715. case 0x0298: /* 'BrtBeginFnGroup' */
  15716. case 0x0161: /* 'BrtBeginExternals' */
  15717. break;
  15718. /* case 'BrtModelTimeGroupingCalcCol' */
  15719. case 0x0C00: /* 'BrtUid' */
  15720. case 0x0C01: /* 'BrtRevisionPtr' */
  15721. case 0x0216: /* 'BrtBookProtection' */
  15722. case 0x02A5: /* 'BrtBookProtectionIso' */
  15723. case 0x009D: /* 'BrtCalcProp' */
  15724. case 0x0262: /* 'BrtCrashRecErr' */
  15725. case 0x0802: /* 'BrtDecoupledPivotCacheID' */
  15726. case 0x009B: /* 'BrtFileRecover' */
  15727. case 0x0224: /* 'BrtFileSharing' */
  15728. case 0x02A4: /* 'BrtFileSharingIso' */
  15729. case 0x0080: /* 'BrtFileVersion' */
  15730. case 0x0299: /* 'BrtFnGroup' */
  15731. case 0x0850: /* 'BrtModelRelationship' */
  15732. case 0x084D: /* 'BrtModelTable' */
  15733. case 0x0225: /* 'BrtOleSize' */
  15734. case 0x0805: /* 'BrtPivotTableRef' */
  15735. case 0x0254: /* 'BrtSmartTagType' */
  15736. case 0x081C: /* 'BrtTableSlicerCacheID' */
  15737. case 0x081B: /* 'BrtTableSlicerCacheIDs' */
  15738. case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
  15739. case 0x018D: /* 'BrtUserBookView' */
  15740. case 0x009A: /* 'BrtWbFactoid' */
  15741. case 0x045D: /* 'BrtWbProp14' */
  15742. case 0x0229: /* 'BrtWebOpt' */
  15743. case 0x082B: /* 'BrtWorkBookPr15' */
  15744. break;
  15745. case 0x0023: /* 'BrtFRTBegin' */
  15746. state.push(RT); pass = true; break;
  15747. case 0x0024: /* 'BrtFRTEnd' */
  15748. state.pop(); pass = false; break;
  15749. case 0x0025: /* 'BrtACBegin' */
  15750. state.push(RT); pass = true; break;
  15751. case 0x0026: /* 'BrtACEnd' */
  15752. state.pop(); pass = false; break;
  15753. case 0x0010: /* 'BrtFRTArchID$' */ break;
  15754. default:
  15755. if(R.T){/* empty */}
  15756. 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));
  15757. }
  15758. }, opts);
  15759. parse_wb_defaults(wb);
  15760. // $FlowIgnore
  15761. wb.Names = Names;
  15762. (wb).supbooks = supbooks;
  15763. return wb;
  15764. }
  15765. function write_BUNDLESHS(ba, wb) {
  15766. write_record(ba, 0x008F /* BrtBeginBundleShs */);
  15767. for(var idx = 0; idx != wb.SheetNames.length; ++idx) {
  15768. var viz = wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx] && wb.Workbook.Sheets[idx].Hidden || 0;
  15769. var d = { Hidden: viz, iTabID: idx+1, strRelID: 'rId' + (idx+1), name: wb.SheetNames[idx] };
  15770. write_record(ba, 0x009C /* BrtBundleSh */, write_BrtBundleSh(d));
  15771. }
  15772. write_record(ba, 0x0090 /* BrtEndBundleShs */);
  15773. }
  15774. /* [MS-XLSB] 2.4.649 BrtFileVersion */
  15775. function write_BrtFileVersion(data, o) {
  15776. if(!o) o = new_buf(127);
  15777. for(var i = 0; i != 4; ++i) o.write_shift(4, 0);
  15778. write_XLWideString("SheetJS", o);
  15779. write_XLWideString(XLSX.version, o);
  15780. write_XLWideString(XLSX.version, o);
  15781. write_XLWideString("7262", o);
  15782. return o.length > o.l ? o.slice(0, o.l) : o;
  15783. }
  15784. /* [MS-XLSB] 2.4.301 BrtBookView */
  15785. function write_BrtBookView(idx, o) {
  15786. if(!o) o = new_buf(29);
  15787. o.write_shift(-4, 0);
  15788. o.write_shift(-4, 460);
  15789. o.write_shift(4, 28800);
  15790. o.write_shift(4, 17600);
  15791. o.write_shift(4, 500);
  15792. o.write_shift(4, idx);
  15793. o.write_shift(4, idx);
  15794. var flags = 0x78;
  15795. o.write_shift(1, flags);
  15796. return o.length > o.l ? o.slice(0, o.l) : o;
  15797. }
  15798. function write_BOOKVIEWS(ba, wb) {
  15799. /* required if hidden tab appears before visible tab */
  15800. if(!wb.Workbook || !wb.Workbook.Sheets) return;
  15801. var sheets = wb.Workbook.Sheets;
  15802. var i = 0, vistab = -1, hidden = -1;
  15803. for(; i < sheets.length; ++i) {
  15804. if(!sheets[i] || !sheets[i].Hidden && vistab == -1) vistab = i;
  15805. else if(sheets[i].Hidden == 1 && hidden == -1) hidden = i;
  15806. }
  15807. if(hidden > vistab) return;
  15808. write_record(ba, 0x0087 /* BrtBeginBookViews */);
  15809. write_record(ba, 0x009E /* BrtBookView */, write_BrtBookView(vistab));
  15810. /* 1*(BrtBookView *FRT) */
  15811. write_record(ba, 0x0088 /* BrtEndBookViews */);
  15812. }
  15813. /* [MS-XLSB] 2.4.305 BrtCalcProp */
  15814. /*function write_BrtCalcProp(data, o) {
  15815. if(!o) o = new_buf(26);
  15816. o.write_shift(4,0); // force recalc
  15817. o.write_shift(4,1);
  15818. o.write_shift(4,0);
  15819. write_Xnum(0, o);
  15820. o.write_shift(-4, 1023);
  15821. o.write_shift(1, 0x33);
  15822. o.write_shift(1, 0x00);
  15823. return o;
  15824. }*/
  15825. /* [MS-XLSB] 2.4.646 BrtFileRecover */
  15826. /*function write_BrtFileRecover(data, o) {
  15827. if(!o) o = new_buf(1);
  15828. o.write_shift(1,0);
  15829. return o;
  15830. }*/
  15831. /* [MS-XLSB] 2.1.7.61 Workbook */
  15832. function write_wb_bin(wb, opts) {
  15833. var ba = buf_array();
  15834. write_record(ba, 0x0083 /* BrtBeginBook */);
  15835. write_record(ba, 0x0080 /* BrtFileVersion */, write_BrtFileVersion());
  15836. /* [[BrtFileSharingIso] BrtFileSharing] */
  15837. write_record(ba, 0x0099 /* BrtWbProp */, write_BrtWbProp(wb.Workbook && wb.Workbook.WBProps || null));
  15838. /* [ACABSPATH] */
  15839. /* [[BrtBookProtectionIso] BrtBookProtection] */
  15840. write_BOOKVIEWS(ba, wb, opts);
  15841. write_BUNDLESHS(ba, wb, opts);
  15842. /* [FNGROUP] */
  15843. /* [EXTERNALS] */
  15844. /* *BrtName */
  15845. /* write_record(ba, 0x009D BrtCalcProp, write_BrtCalcProp()); */
  15846. /* [BrtOleSize] */
  15847. /* *(BrtUserBookView *FRT) */
  15848. /* [PIVOTCACHEIDS] */
  15849. /* [BrtWbFactoid] */
  15850. /* [SMARTTAGTYPES] */
  15851. /* [BrtWebOpt] */
  15852. /* write_record(ba, 0x009B BrtFileRecover, write_BrtFileRecover()); */
  15853. /* [WEBPUBITEMS] */
  15854. /* [CRERRS] */
  15855. /* FRTWORKBOOK */
  15856. write_record(ba, 0x0084 /* BrtEndBook */);
  15857. return ba.end();
  15858. }
  15859. function parse_wb(data, name, opts) {
  15860. if(name.slice(-4)===".bin") return parse_wb_bin((data), opts);
  15861. return parse_wb_xml((data), opts);
  15862. }
  15863. function parse_ws(data, name, idx, opts, rels, wb, themes, styles) {
  15864. if(name.slice(-4)===".bin") return parse_ws_bin((data), opts, idx, rels, wb, themes, styles);
  15865. return parse_ws_xml((data), opts, idx, rels, wb, themes, styles);
  15866. }
  15867. function parse_cs(data, name, idx, opts, rels, wb, themes, styles) {
  15868. if(name.slice(-4)===".bin") return parse_cs_bin((data), opts, idx, rels, wb, themes, styles);
  15869. return parse_cs_xml((data), opts, idx, rels, wb, themes, styles);
  15870. }
  15871. function parse_ms(data, name, idx, opts, rels, wb, themes, styles) {
  15872. if(name.slice(-4)===".bin") return parse_ms_bin((data), opts, idx, rels, wb, themes, styles);
  15873. return parse_ms_xml((data), opts, idx, rels, wb, themes, styles);
  15874. }
  15875. function parse_ds(data, name, idx, opts, rels, wb, themes, styles) {
  15876. if(name.slice(-4)===".bin") return parse_ds_bin((data), opts, idx, rels, wb, themes, styles);
  15877. return parse_ds_xml((data), opts, idx, rels, wb, themes, styles);
  15878. }
  15879. function parse_sty(data, name, themes, opts) {
  15880. if(name.slice(-4)===".bin") return parse_sty_bin((data), themes, opts);
  15881. return parse_sty_xml((data), themes, opts);
  15882. }
  15883. function parse_theme(data, name, opts) {
  15884. return parse_theme_xml(data, opts);
  15885. }
  15886. function parse_sst(data, name, opts) {
  15887. if(name.slice(-4)===".bin") return parse_sst_bin((data), opts);
  15888. return parse_sst_xml((data), opts);
  15889. }
  15890. function parse_cmnt(data, name, opts) {
  15891. if(name.slice(-4)===".bin") return parse_comments_bin((data), opts);
  15892. return parse_comments_xml((data), opts);
  15893. }
  15894. function parse_cc(data, name, opts) {
  15895. if(name.slice(-4)===".bin") return parse_cc_bin((data), name, opts);
  15896. return parse_cc_xml((data), name, opts);
  15897. }
  15898. function parse_xlink(data, rel, name, opts) {
  15899. if(name.slice(-4)===".bin") return parse_xlink_bin((data), rel, name, opts);
  15900. return parse_xlink_xml((data), rel, name, opts);
  15901. }
  15902. function parse_xlmeta(data, name, opts) {
  15903. if(name.slice(-4)===".bin") return parse_xlmeta_bin((data), name, opts);
  15904. return parse_xlmeta_xml((data), name, opts);
  15905. }
  15906. function write_wb(wb, name, opts) {
  15907. return (name.slice(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
  15908. }
  15909. function write_ws(data, name, opts, wb, rels) {
  15910. return (name.slice(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb, rels);
  15911. }
  15912. // eslint-disable-next-line no-unused-vars
  15913. function write_cs(data, name, opts, wb, rels) {
  15914. return (name.slice(-4)===".bin" ? write_cs_bin : write_cs_xml)(data, opts, wb, rels);
  15915. }
  15916. function write_sty(data, name, opts) {
  15917. return (name.slice(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
  15918. }
  15919. function write_sst(data, name, opts) {
  15920. return (name.slice(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
  15921. }
  15922. function write_cmnt(data, name, opts) {
  15923. return (name.slice(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
  15924. }
  15925. /*
  15926. function write_cc(data, name:string, opts) {
  15927. return (name.slice(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
  15928. }
  15929. */
  15930. function write_xlmeta(name) {
  15931. return (name.slice(-4)===".bin" ? write_xlmeta_bin : write_xlmeta_xml)();
  15932. }
  15933. var attregexg2=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
  15934. var attregex2=/([\w:]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
  15935. function xlml_parsexmltag(tag, skip_root) {
  15936. var words = tag.split(/\s+/);
  15937. var z = ([]); if(!skip_root) z[0] = words[0];
  15938. if(words.length === 1) return z;
  15939. var m = tag.match(attregexg2), y, j, w, i;
  15940. if(m) for(i = 0; i != m.length; ++i) {
  15941. y = m[i].match(attregex2);
  15942. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  15943. else {
  15944. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  15945. else w = y[1].slice(j+1);
  15946. z[w] = y[2].slice(1,y[2].length-1);
  15947. }
  15948. }
  15949. return z;
  15950. }
  15951. function xlml_parsexmltagobj(tag) {
  15952. var words = tag.split(/\s+/);
  15953. var z = {};
  15954. if(words.length === 1) return z;
  15955. var m = tag.match(attregexg2), y, j, w, i;
  15956. if(m) for(i = 0; i != m.length; ++i) {
  15957. y = m[i].match(attregex2);
  15958. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  15959. else {
  15960. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  15961. else w = y[1].slice(j+1);
  15962. z[w] = y[2].slice(1,y[2].length-1);
  15963. }
  15964. }
  15965. return z;
  15966. }
  15967. // ----
  15968. /* map from xlml named formats to SSF TODO: localize */
  15969. var XLMLFormatMap;
  15970. function xlml_format(format, value) {
  15971. var fmt = XLMLFormatMap[format] || unescapexml(format);
  15972. if(fmt === "General") return SSF_general(value);
  15973. return SSF_format(fmt, value);
  15974. }
  15975. function xlml_set_custprop(Custprops, key, cp, val) {
  15976. var oval = val;
  15977. switch((cp[0].match(/dt:dt="([\w.]+)"/)||["",""])[1]) {
  15978. case "boolean": oval = parsexmlbool(val); break;
  15979. case "i2": case "int": oval = parseInt(val, 10); break;
  15980. case "r4": case "float": oval = parseFloat(val); break;
  15981. case "date": case "dateTime.tz": oval = parseDate(val); break;
  15982. case "i8": case "string": case "fixed": case "uuid": case "bin.base64": break;
  15983. default: throw new Error("bad custprop:" + cp[0]);
  15984. }
  15985. Custprops[unescapexml(key)] = oval;
  15986. }
  15987. function safe_format_xlml(cell, nf, o) {
  15988. if(cell.t === 'z') return;
  15989. if(!o || o.cellText !== false) try {
  15990. if(cell.t === 'e') { cell.w = cell.w || BErr[cell.v]; }
  15991. else if(nf === "General") {
  15992. if(cell.t === 'n') {
  15993. if((cell.v|0) === cell.v) cell.w = cell.v.toString(10);
  15994. else cell.w = SSF_general_num(cell.v);
  15995. }
  15996. else cell.w = SSF_general(cell.v);
  15997. }
  15998. else cell.w = xlml_format(nf||"General", cell.v);
  15999. } catch(e) { if(o.WTF) throw e; }
  16000. try {
  16001. var z = XLMLFormatMap[nf]||nf||"General";
  16002. if(o.cellNF) cell.z = z;
  16003. if(o.cellDates && cell.t == 'n' && fmt_is_date(z)) {
  16004. 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); }
  16005. }
  16006. } catch(e) { if(o.WTF) throw e; }
  16007. }
  16008. function process_style_xlml(styles, stag, opts) {
  16009. if(opts.cellStyles) {
  16010. if(stag.Interior) {
  16011. var I = stag.Interior;
  16012. if(I.Pattern) I.patternType = XLMLPatternTypeMap[I.Pattern] || I.Pattern;
  16013. }
  16014. }
  16015. styles[stag.ID] = stag;
  16016. }
  16017. /* TODO: there must exist some form of OSP-blessed spec */
  16018. function parse_xlml_data(xml, ss, data, cell, base, styles, csty, row, arrayf, o) {
  16019. var nf = "General", sid = cell.StyleID, S = {}; o = o || {};
  16020. var interiors = [];
  16021. var i = 0;
  16022. if(sid === undefined && row) sid = row.StyleID;
  16023. if(sid === undefined && csty) sid = csty.StyleID;
  16024. while(styles[sid] !== undefined) {
  16025. if(styles[sid].nf) nf = styles[sid].nf;
  16026. if(styles[sid].Interior) interiors.push(styles[sid].Interior);
  16027. if(!styles[sid].Parent) break;
  16028. sid = styles[sid].Parent;
  16029. }
  16030. switch(data.Type) {
  16031. case 'Boolean':
  16032. cell.t = 'b';
  16033. cell.v = parsexmlbool(xml);
  16034. break;
  16035. case 'String':
  16036. cell.t = 's'; cell.r = xlml_fixstr(unescapexml(xml));
  16037. cell.v = (xml.indexOf("<") > -1 ? unescapexml(ss||xml).replace(/<.*?>/g, "") : cell.r); // todo: BR etc
  16038. break;
  16039. case 'DateTime':
  16040. if(xml.slice(-1) != "Z") xml += "Z";
  16041. cell.v = (parseDate(xml) - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  16042. if(cell.v !== cell.v) cell.v = unescapexml(xml);
  16043. else if(cell.v<60) cell.v = cell.v -1;
  16044. if(!nf || nf == "General") nf = "yyyy-mm-dd";
  16045. /* falls through */
  16046. case 'Number':
  16047. if(cell.v === undefined) cell.v=+xml;
  16048. if(!cell.t) cell.t = 'n';
  16049. break;
  16050. case 'Error': cell.t = 'e'; cell.v = RBErr[xml]; if(o.cellText !== false) cell.w = xml; break;
  16051. default:
  16052. if(xml == "" && ss == "") { cell.t = 'z'; }
  16053. else { cell.t = 's'; cell.v = xlml_fixstr(ss||xml); }
  16054. break;
  16055. }
  16056. safe_format_xlml(cell, nf, o);
  16057. if(o.cellFormula !== false) {
  16058. if(cell.Formula) {
  16059. var fstr = unescapexml(cell.Formula);
  16060. /* strictly speaking, the leading = is required but some writers omit */
  16061. if(fstr.charCodeAt(0) == 61 /* = */) fstr = fstr.slice(1);
  16062. cell.f = rc_to_a1(fstr, base);
  16063. delete cell.Formula;
  16064. if(cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
  16065. else if(cell.ArrayRange) {
  16066. cell.F = rc_to_a1(cell.ArrayRange, base);
  16067. arrayf.push([safe_decode_range(cell.F), cell.F]);
  16068. }
  16069. } else {
  16070. for(i = 0; i < arrayf.length; ++i)
  16071. if(base.r >= arrayf[i][0].s.r && base.r <= arrayf[i][0].e.r)
  16072. if(base.c >= arrayf[i][0].s.c && base.c <= arrayf[i][0].e.c)
  16073. cell.F = arrayf[i][1];
  16074. }
  16075. }
  16076. if(o.cellStyles) {
  16077. interiors.forEach(function(x) {
  16078. if(!S.patternType && x.patternType) S.patternType = x.patternType;
  16079. });
  16080. cell.s = S;
  16081. }
  16082. if(cell.StyleID !== undefined) cell.ixfe = cell.StyleID;
  16083. }
  16084. function xlml_clean_comment(comment) {
  16085. comment.t = comment.v || "";
  16086. comment.t = comment.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  16087. comment.v = comment.w = comment.ixfe = undefined;
  16088. }
  16089. /* TODO: Everything */
  16090. function parse_xlml_xml(d, _opts) {
  16091. var opts = _opts || {};
  16092. make_ssf();
  16093. var str = debom(xlml_normalize(d));
  16094. if(opts.type == 'binary' || opts.type == 'array' || opts.type == 'base64') {
  16095. if(typeof $cptable !== 'undefined') str = $cptable.utils.decode(65001, char_codes(str));
  16096. else str = utf8read(str);
  16097. }
  16098. var opening = str.slice(0, 1024).toLowerCase(), ishtml = false;
  16099. opening = opening.replace(/".*?"/g, "");
  16100. 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); }
  16101. if(opening.indexOf("<?xml") == -1) ["html", "table", "head", "meta", "script", "style", "div"].forEach(function(tag) { if(opening.indexOf("<" + tag) >= 0) ishtml = true; });
  16102. if(ishtml) return html_to_workbook(str, opts);
  16103. XLMLFormatMap = ({
  16104. "General Number": "General",
  16105. "General Date": table_fmt[22],
  16106. "Long Date": "dddd, mmmm dd, yyyy",
  16107. "Medium Date": table_fmt[15],
  16108. "Short Date": table_fmt[14],
  16109. "Long Time": table_fmt[19],
  16110. "Medium Time": table_fmt[18],
  16111. "Short Time": table_fmt[20],
  16112. "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  16113. "Fixed": table_fmt[2],
  16114. "Standard": table_fmt[4],
  16115. "Percent": table_fmt[10],
  16116. "Scientific": table_fmt[11],
  16117. "Yes/No": '"Yes";"Yes";"No";@',
  16118. "True/False": '"True";"True";"False";@',
  16119. "On/Off": '"Yes";"Yes";"No";@'
  16120. });
  16121. var Rn;
  16122. var state = [], tmp;
  16123. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  16124. var sheets = {}, sheetnames = [], cursheet = (opts.dense ? [] : {}), sheetname = "";
  16125. var cell = ({}), row = {};// eslint-disable-line no-unused-vars
  16126. var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
  16127. var c = 0, r = 0;
  16128. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  16129. var styles = {}, stag = {};
  16130. var ss = "", fidx = 0;
  16131. var merges = [];
  16132. var Props = {}, Custprops = {}, pidx = 0, cp = [];
  16133. var comments = [], comment = ({});
  16134. var cstys = [], csty, seencol = false;
  16135. var arrayf = [];
  16136. var rowinfo = [], rowobj = {}, cc = 0, rr = 0;
  16137. var Workbook = ({ Sheets:[], WBProps:{date1904:false} }), wsprops = {};
  16138. xlmlregex.lastIndex = 0;
  16139. str = str.replace(/<!--([\s\S]*?)-->/mg,"");
  16140. var raw_Rn3 = "";
  16141. while((Rn = xlmlregex.exec(str))) switch((Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase())) {
  16142. case 'data' /*case 'Data'*/:
  16143. if(raw_Rn3 == "data") {
  16144. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16145. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  16146. break;
  16147. }
  16148. if(state[state.length-1][1]) break;
  16149. 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);
  16150. else { ss = ""; dtag = xlml_parsexmltag(Rn[0]); didx = Rn.index + Rn[0].length; }
  16151. break;
  16152. case 'cell' /*case 'Cell'*/:
  16153. if(Rn[1]==='/'){
  16154. if(comments.length > 0) cell.c = comments;
  16155. if((!opts.sheetRows || opts.sheetRows > r) && cell.v !== undefined) {
  16156. if(opts.dense) {
  16157. if(!cursheet[r]) cursheet[r] = [];
  16158. cursheet[r][c] = cell;
  16159. } else cursheet[encode_col(c) + encode_row(r)] = cell;
  16160. }
  16161. if(cell.HRef) {
  16162. cell.l = ({Target:unescapexml(cell.HRef)});
  16163. if(cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
  16164. delete cell.HRef; delete cell.HRefScreenTip;
  16165. }
  16166. if(cell.MergeAcross || cell.MergeDown) {
  16167. cc = c + (parseInt(cell.MergeAcross,10)|0);
  16168. rr = r + (parseInt(cell.MergeDown,10)|0);
  16169. merges.push({s:{c:c,r:r},e:{c:cc,r:rr}});
  16170. }
  16171. if(!opts.sheetStubs) { if(cell.MergeAcross) c = cc + 1; else ++c; }
  16172. else if(cell.MergeAcross || cell.MergeDown) {
  16173. for(var cma = c; cma <= cc; ++cma) {
  16174. for(var cmd = r; cmd <= rr; ++cmd) {
  16175. if(cma > c || cmd > r) {
  16176. if(opts.dense) {
  16177. if(!cursheet[cmd]) cursheet[cmd] = [];
  16178. cursheet[cmd][cma] = {t:'z'};
  16179. } else cursheet[encode_col(cma) + encode_row(cmd)] = {t:'z'};
  16180. }
  16181. }
  16182. }
  16183. c = cc + 1;
  16184. }
  16185. else ++c;
  16186. } else {
  16187. cell = xlml_parsexmltagobj(Rn[0]);
  16188. if(cell.Index) c = +cell.Index - 1;
  16189. if(c < refguess.s.c) refguess.s.c = c;
  16190. if(c > refguess.e.c) refguess.e.c = c;
  16191. if(Rn[0].slice(-2) === "/>") ++c;
  16192. comments = [];
  16193. }
  16194. break;
  16195. case 'row' /*case 'Row'*/:
  16196. if(Rn[1]==='/' || Rn[0].slice(-2) === "/>") {
  16197. if(r < refguess.s.r) refguess.s.r = r;
  16198. if(r > refguess.e.r) refguess.e.r = r;
  16199. if(Rn[0].slice(-2) === "/>") {
  16200. row = xlml_parsexmltag(Rn[0]);
  16201. if(row.Index) r = +row.Index - 1;
  16202. }
  16203. c = 0; ++r;
  16204. } else {
  16205. row = xlml_parsexmltag(Rn[0]);
  16206. if(row.Index) r = +row.Index - 1;
  16207. rowobj = {};
  16208. if(row.AutoFitHeight == "0" || row.Height) {
  16209. rowobj.hpx = parseInt(row.Height, 10); rowobj.hpt = px2pt(rowobj.hpx);
  16210. rowinfo[r] = rowobj;
  16211. }
  16212. if(row.Hidden == "1") { rowobj.hidden = true; rowinfo[r] = rowobj; }
  16213. }
  16214. break;
  16215. case 'worksheet' /*case 'Worksheet'*/: /* TODO: read range from FullRows/FullColumns */
  16216. if(Rn[1]==='/'){
  16217. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  16218. sheetnames.push(sheetname);
  16219. if(refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
  16220. cursheet["!ref"] = encode_range(refguess);
  16221. if(opts.sheetRows && opts.sheetRows <= refguess.e.r) {
  16222. cursheet["!fullref"] = cursheet["!ref"];
  16223. refguess.e.r = opts.sheetRows - 1;
  16224. cursheet["!ref"] = encode_range(refguess);
  16225. }
  16226. }
  16227. if(merges.length) cursheet["!merges"] = merges;
  16228. if(cstys.length > 0) cursheet["!cols"] = cstys;
  16229. if(rowinfo.length > 0) cursheet["!rows"] = rowinfo;
  16230. sheets[sheetname] = cursheet;
  16231. } else {
  16232. refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  16233. r = c = 0;
  16234. state.push([Rn[3], false]);
  16235. tmp = xlml_parsexmltag(Rn[0]);
  16236. sheetname = unescapexml(tmp.Name);
  16237. cursheet = (opts.dense ? [] : {});
  16238. merges = [];
  16239. arrayf = [];
  16240. rowinfo = [];
  16241. wsprops = {name:sheetname, Hidden:0};
  16242. Workbook.Sheets.push(wsprops);
  16243. }
  16244. break;
  16245. case 'table' /*case 'Table'*/:
  16246. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16247. else if(Rn[0].slice(-2) == "/>") break;
  16248. else {
  16249. state.push([Rn[3], false]);
  16250. cstys = []; seencol = false;
  16251. }
  16252. break;
  16253. case 'style' /*case 'Style'*/:
  16254. if(Rn[1]==='/') process_style_xlml(styles, stag, opts);
  16255. else stag = xlml_parsexmltag(Rn[0]);
  16256. break;
  16257. case 'numberformat' /*case 'NumberFormat'*/:
  16258. stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
  16259. if(XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
  16260. for(var ssfidx = 0; ssfidx != 0x188; ++ssfidx) if(table_fmt[ssfidx] == stag.nf) break;
  16261. if(ssfidx == 0x188) for(ssfidx = 0x39; ssfidx != 0x188; ++ssfidx) if(table_fmt[ssfidx] == null) { SSF_load(stag.nf, ssfidx); break; }
  16262. break;
  16263. case 'column' /*case 'Column'*/:
  16264. if(state[state.length-1][0] !== /*'Table'*/'table') break;
  16265. csty = xlml_parsexmltag(Rn[0]);
  16266. if(csty.Hidden) { csty.hidden = true; delete csty.Hidden; }
  16267. if(csty.Width) csty.wpx = parseInt(csty.Width, 10);
  16268. if(!seencol && csty.wpx > 10) {
  16269. seencol = true; MDW = DEF_MDW; //find_mdw_wpx(csty.wpx);
  16270. for(var _col = 0; _col < cstys.length; ++_col) if(cstys[_col]) process_col(cstys[_col]);
  16271. }
  16272. if(seencol) process_col(csty);
  16273. cstys[(csty.Index-1||cstys.length)] = csty;
  16274. for(var i = 0; i < +csty.Span; ++i) cstys[cstys.length] = dup(csty);
  16275. break;
  16276. case 'namedrange' /*case 'NamedRange'*/:
  16277. if(Rn[1]==='/') break;
  16278. if(!Workbook.Names) Workbook.Names = [];
  16279. var _NamedRange = parsexmltag(Rn[0]);
  16280. var _DefinedName = ({
  16281. Name: _NamedRange.Name,
  16282. Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), {r:0, c:0})
  16283. });
  16284. if(Workbook.Sheets.length>0) _DefinedName.Sheet=Workbook.Sheets.length-1;
  16285. Workbook.Names.push(_DefinedName);
  16286. break;
  16287. case 'namedcell' /*case 'NamedCell'*/: break;
  16288. case 'b' /*case 'B'*/: break;
  16289. case 'i' /*case 'I'*/: break;
  16290. case 'u' /*case 'U'*/: break;
  16291. case 's' /*case 'S'*/: break;
  16292. case 'em' /*case 'EM'*/: break;
  16293. case 'h2' /*case 'H2'*/: break;
  16294. case 'h3' /*case 'H3'*/: break;
  16295. case 'sub' /*case 'Sub'*/: break;
  16296. case 'sup' /*case 'Sup'*/: break;
  16297. case 'span' /*case 'Span'*/: break;
  16298. case 'alignment' /*case 'Alignment'*/:
  16299. break;
  16300. case 'borders' /*case 'Borders'*/: break;
  16301. case 'border' /*case 'Border'*/: break;
  16302. case 'font' /*case 'Font'*/:
  16303. if(Rn[0].slice(-2) === "/>") break;
  16304. else if(Rn[1]==="/") ss += str.slice(fidx, Rn.index);
  16305. else fidx = Rn.index + Rn[0].length;
  16306. break;
  16307. case 'interior' /*case 'Interior'*/:
  16308. if(!opts.cellStyles) break;
  16309. stag.Interior = xlml_parsexmltag(Rn[0]);
  16310. break;
  16311. case 'protection' /*case 'Protection'*/: break;
  16312. case 'author' /*case 'Author'*/:
  16313. case 'title' /*case 'Title'*/:
  16314. case 'description' /*case 'Description'*/:
  16315. case 'created' /*case 'Created'*/:
  16316. case 'keywords' /*case 'Keywords'*/:
  16317. case 'subject' /*case 'Subject'*/:
  16318. case 'category' /*case 'Category'*/:
  16319. case 'company' /*case 'Company'*/:
  16320. case 'lastauthor' /*case 'LastAuthor'*/:
  16321. case 'lastsaved' /*case 'LastSaved'*/:
  16322. case 'lastprinted' /*case 'LastPrinted'*/:
  16323. case 'version' /*case 'Version'*/:
  16324. case 'revision' /*case 'Revision'*/:
  16325. case 'totaltime' /*case 'TotalTime'*/:
  16326. case 'hyperlinkbase' /*case 'HyperlinkBase'*/:
  16327. case 'manager' /*case 'Manager'*/:
  16328. case 'contentstatus' /*case 'ContentStatus'*/:
  16329. case 'identifier' /*case 'Identifier'*/:
  16330. case 'language' /*case 'Language'*/:
  16331. case 'appname' /*case 'AppName'*/:
  16332. if(Rn[0].slice(-2) === "/>") break;
  16333. else if(Rn[1]==="/") xlml_set_prop(Props, raw_Rn3, str.slice(pidx, Rn.index));
  16334. else pidx = Rn.index + Rn[0].length;
  16335. break;
  16336. case 'paragraphs' /*case 'Paragraphs'*/: break;
  16337. case 'styles' /*case 'Styles'*/:
  16338. case 'workbook' /*case 'Workbook'*/:
  16339. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16340. else state.push([Rn[3], false]);
  16341. break;
  16342. case 'comment' /*case 'Comment'*/:
  16343. if(Rn[1]==='/'){
  16344. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  16345. xlml_clean_comment(comment);
  16346. comments.push(comment);
  16347. } else {
  16348. state.push([Rn[3], false]);
  16349. tmp = xlml_parsexmltag(Rn[0]);
  16350. comment = ({a:tmp.Author});
  16351. }
  16352. break;
  16353. case 'autofilter' /*case 'AutoFilter'*/:
  16354. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16355. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  16356. var AutoFilter = xlml_parsexmltag(Rn[0]);
  16357. cursheet['!autofilter'] = { ref:rc_to_a1(AutoFilter.Range).replace(/\$/g,"") };
  16358. state.push([Rn[3], true]);
  16359. }
  16360. break;
  16361. case 'name' /*case 'Name'*/: break;
  16362. case 'datavalidation' /*case 'DataValidation'*/:
  16363. if(Rn[1]==='/'){
  16364. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  16365. } else {
  16366. if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  16367. }
  16368. break;
  16369. case 'pixelsperinch' /*case 'PixelsPerInch'*/:
  16370. break;
  16371. case 'componentoptions' /*case 'ComponentOptions'*/:
  16372. case 'documentproperties' /*case 'DocumentProperties'*/:
  16373. case 'customdocumentproperties' /*case 'CustomDocumentProperties'*/:
  16374. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/:
  16375. case 'pivottable' /*case 'PivotTable'*/:
  16376. case 'pivotcache' /*case 'PivotCache'*/:
  16377. case 'names' /*case 'Names'*/:
  16378. case 'mapinfo' /*case 'MapInfo'*/:
  16379. case 'pagebreaks' /*case 'PageBreaks'*/:
  16380. case 'querytable' /*case 'QueryTable'*/:
  16381. case 'sorting' /*case 'Sorting'*/:
  16382. case 'schema' /*case 'Schema'*/: //case 'data' /*case 'data'*/:
  16383. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  16384. case 'smarttagtype' /*case 'SmartTagType'*/:
  16385. case 'smarttags' /*case 'SmartTags'*/:
  16386. case 'excelworkbook' /*case 'ExcelWorkbook'*/:
  16387. case 'workbookoptions' /*case 'WorkbookOptions'*/:
  16388. case 'worksheetoptions' /*case 'WorksheetOptions'*/:
  16389. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  16390. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  16391. break;
  16392. case 'null' /*case 'Null'*/: break;
  16393. default:
  16394. /* FODS file root is <office:document> */
  16395. if(state.length == 0 && Rn[3] == "document") return parse_fods(str, opts);
  16396. /* UOS file root is <uof:UOF> */
  16397. if(state.length == 0 && Rn[3] == "uof"/*"UOF"*/) return parse_fods(str, opts);
  16398. var seen = true;
  16399. switch(state[state.length-1][0]) {
  16400. /* OfficeDocumentSettings */
  16401. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/: switch(Rn[3]) {
  16402. case 'allowpng' /*case 'AllowPNG'*/: break;
  16403. case 'removepersonalinformation' /*case 'RemovePersonalInformation'*/: break;
  16404. case 'downloadcomponents' /*case 'DownloadComponents'*/: break;
  16405. case 'locationofcomponents' /*case 'LocationOfComponents'*/: break;
  16406. case 'colors' /*case 'Colors'*/: break;
  16407. case 'color' /*case 'Color'*/: break;
  16408. case 'index' /*case 'Index'*/: break;
  16409. case 'rgb' /*case 'RGB'*/: break;
  16410. case 'targetscreensize' /*case 'TargetScreenSize'*/: break;
  16411. case 'readonlyrecommended' /*case 'ReadOnlyRecommended'*/: break;
  16412. default: seen = false;
  16413. } break;
  16414. /* ComponentOptions */
  16415. case 'componentoptions' /*case 'ComponentOptions'*/: switch(Rn[3]) {
  16416. case 'toolbar' /*case 'Toolbar'*/: break;
  16417. case 'hideofficelogo' /*case 'HideOfficeLogo'*/: break;
  16418. case 'spreadsheetautofit' /*case 'SpreadsheetAutoFit'*/: break;
  16419. case 'label' /*case 'Label'*/: break;
  16420. case 'caption' /*case 'Caption'*/: break;
  16421. case 'maxheight' /*case 'MaxHeight'*/: break;
  16422. case 'maxwidth' /*case 'MaxWidth'*/: break;
  16423. case 'nextsheetnumber' /*case 'NextSheetNumber'*/: break;
  16424. default: seen = false;
  16425. } break;
  16426. /* ExcelWorkbook */
  16427. case 'excelworkbook' /*case 'ExcelWorkbook'*/: switch(Rn[3]) {
  16428. case 'date1904' /*case 'Date1904'*/:
  16429. Workbook.WBProps.date1904 = true;
  16430. break;
  16431. case 'windowheight' /*case 'WindowHeight'*/: break;
  16432. case 'windowwidth' /*case 'WindowWidth'*/: break;
  16433. case 'windowtopx' /*case 'WindowTopX'*/: break;
  16434. case 'windowtopy' /*case 'WindowTopY'*/: break;
  16435. case 'tabratio' /*case 'TabRatio'*/: break;
  16436. case 'protectstructure' /*case 'ProtectStructure'*/: break;
  16437. case 'protectwindow' /*case 'ProtectWindow'*/: break;
  16438. case 'protectwindows' /*case 'ProtectWindows'*/: break;
  16439. case 'activesheet' /*case 'ActiveSheet'*/: break;
  16440. case 'displayinknotes' /*case 'DisplayInkNotes'*/: break;
  16441. case 'firstvisiblesheet' /*case 'FirstVisibleSheet'*/: break;
  16442. case 'supbook' /*case 'SupBook'*/: break;
  16443. case 'sheetname' /*case 'SheetName'*/: break;
  16444. case 'sheetindex' /*case 'SheetIndex'*/: break;
  16445. case 'sheetindexfirst' /*case 'SheetIndexFirst'*/: break;
  16446. case 'sheetindexlast' /*case 'SheetIndexLast'*/: break;
  16447. case 'dll' /*case 'Dll'*/: break;
  16448. case 'acceptlabelsinformulas' /*case 'AcceptLabelsInFormulas'*/: break;
  16449. case 'donotsavelinkvalues' /*case 'DoNotSaveLinkValues'*/: break;
  16450. case 'iteration' /*case 'Iteration'*/: break;
  16451. case 'maxiterations' /*case 'MaxIterations'*/: break;
  16452. case 'maxchange' /*case 'MaxChange'*/: break;
  16453. case 'path' /*case 'Path'*/: break;
  16454. case 'xct' /*case 'Xct'*/: break;
  16455. case 'count' /*case 'Count'*/: break;
  16456. case 'selectedsheets' /*case 'SelectedSheets'*/: break;
  16457. case 'calculation' /*case 'Calculation'*/: break;
  16458. case 'uncalced' /*case 'Uncalced'*/: break;
  16459. case 'startupprompt' /*case 'StartupPrompt'*/: break;
  16460. case 'crn' /*case 'Crn'*/: break;
  16461. case 'externname' /*case 'ExternName'*/: break;
  16462. case 'formula' /*case 'Formula'*/: break;
  16463. case 'colfirst' /*case 'ColFirst'*/: break;
  16464. case 'collast' /*case 'ColLast'*/: break;
  16465. case 'wantadvise' /*case 'WantAdvise'*/: break;
  16466. case 'boolean' /*case 'Boolean'*/: break;
  16467. case 'error' /*case 'Error'*/: break;
  16468. case 'text' /*case 'Text'*/: break;
  16469. case 'ole' /*case 'OLE'*/: break;
  16470. case 'noautorecover' /*case 'NoAutoRecover'*/: break;
  16471. case 'publishobjects' /*case 'PublishObjects'*/: break;
  16472. case 'donotcalculatebeforesave' /*case 'DoNotCalculateBeforeSave'*/: break;
  16473. case 'number' /*case 'Number'*/: break;
  16474. case 'refmoder1c1' /*case 'RefModeR1C1'*/: break;
  16475. case 'embedsavesmarttags' /*case 'EmbedSaveSmartTags'*/: break;
  16476. default: seen = false;
  16477. } break;
  16478. /* WorkbookOptions */
  16479. case 'workbookoptions' /*case 'WorkbookOptions'*/: switch(Rn[3]) {
  16480. case 'owcversion' /*case 'OWCVersion'*/: break;
  16481. case 'height' /*case 'Height'*/: break;
  16482. case 'width' /*case 'Width'*/: break;
  16483. default: seen = false;
  16484. } break;
  16485. /* WorksheetOptions */
  16486. case 'worksheetoptions' /*case 'WorksheetOptions'*/: switch(Rn[3]) {
  16487. case 'visible' /*case 'Visible'*/:
  16488. if(Rn[0].slice(-2) === "/>"){/* empty */}
  16489. else if(Rn[1]==="/") switch(str.slice(pidx, Rn.index)) {
  16490. case "SheetHidden": wsprops.Hidden = 1; break;
  16491. case "SheetVeryHidden": wsprops.Hidden = 2; break;
  16492. }
  16493. else pidx = Rn.index + Rn[0].length;
  16494. break;
  16495. case 'header' /*case 'Header'*/:
  16496. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  16497. if(!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet['!margins'].header = +parsexmltag(Rn[0]).Margin;
  16498. break;
  16499. case 'footer' /*case 'Footer'*/:
  16500. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  16501. if(!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet['!margins'].footer = +parsexmltag(Rn[0]).Margin;
  16502. break;
  16503. case 'pagemargins' /*case 'PageMargins'*/:
  16504. var pagemargins = parsexmltag(Rn[0]);
  16505. if(!cursheet['!margins']) default_margins(cursheet['!margins']={},'xlml');
  16506. if(!isNaN(+pagemargins.Top)) cursheet['!margins'].top = +pagemargins.Top;
  16507. if(!isNaN(+pagemargins.Left)) cursheet['!margins'].left = +pagemargins.Left;
  16508. if(!isNaN(+pagemargins.Right)) cursheet['!margins'].right = +pagemargins.Right;
  16509. if(!isNaN(+pagemargins.Bottom)) cursheet['!margins'].bottom = +pagemargins.Bottom;
  16510. break;
  16511. case 'displayrighttoleft' /*case 'DisplayRightToLeft'*/:
  16512. if(!Workbook.Views) Workbook.Views = [];
  16513. if(!Workbook.Views[0]) Workbook.Views[0] = {};
  16514. Workbook.Views[0].RTL = true;
  16515. break;
  16516. case 'freezepanes' /*case 'FreezePanes'*/: break;
  16517. case 'frozennosplit' /*case 'FrozenNoSplit'*/: break;
  16518. case 'splithorizontal' /*case 'SplitHorizontal'*/:
  16519. case 'splitvertical' /*case 'SplitVertical'*/:
  16520. break;
  16521. case 'donotdisplaygridlines' /*case 'DoNotDisplayGridlines'*/:
  16522. break;
  16523. case 'activerow' /*case 'ActiveRow'*/: break;
  16524. case 'activecol' /*case 'ActiveCol'*/: break;
  16525. case 'toprowbottompane' /*case 'TopRowBottomPane'*/: break;
  16526. case 'leftcolumnrightpane' /*case 'LeftColumnRightPane'*/: break;
  16527. case 'unsynced' /*case 'Unsynced'*/: break;
  16528. case 'print' /*case 'Print'*/: break;
  16529. case 'printerrors' /*case 'PrintErrors'*/: break;
  16530. case 'panes' /*case 'Panes'*/: break;
  16531. case 'scale' /*case 'Scale'*/: break;
  16532. case 'pane' /*case 'Pane'*/: break;
  16533. case 'number' /*case 'Number'*/: break;
  16534. case 'layout' /*case 'Layout'*/: break;
  16535. case 'pagesetup' /*case 'PageSetup'*/: break;
  16536. case 'selected' /*case 'Selected'*/: break;
  16537. case 'protectobjects' /*case 'ProtectObjects'*/: break;
  16538. case 'enableselection' /*case 'EnableSelection'*/: break;
  16539. case 'protectscenarios' /*case 'ProtectScenarios'*/: break;
  16540. case 'validprinterinfo' /*case 'ValidPrinterInfo'*/: break;
  16541. case 'horizontalresolution' /*case 'HorizontalResolution'*/: break;
  16542. case 'verticalresolution' /*case 'VerticalResolution'*/: break;
  16543. case 'numberofcopies' /*case 'NumberofCopies'*/: break;
  16544. case 'activepane' /*case 'ActivePane'*/: break;
  16545. case 'toprowvisible' /*case 'TopRowVisible'*/: break;
  16546. case 'leftcolumnvisible' /*case 'LeftColumnVisible'*/: break;
  16547. case 'fittopage' /*case 'FitToPage'*/: break;
  16548. case 'rangeselection' /*case 'RangeSelection'*/: break;
  16549. case 'papersizeindex' /*case 'PaperSizeIndex'*/: break;
  16550. case 'pagelayoutzoom' /*case 'PageLayoutZoom'*/: break;
  16551. case 'pagebreakzoom' /*case 'PageBreakZoom'*/: break;
  16552. case 'filteron' /*case 'FilterOn'*/: break;
  16553. case 'fitwidth' /*case 'FitWidth'*/: break;
  16554. case 'fitheight' /*case 'FitHeight'*/: break;
  16555. case 'commentslayout' /*case 'CommentsLayout'*/: break;
  16556. case 'zoom' /*case 'Zoom'*/: break;
  16557. case 'lefttoright' /*case 'LeftToRight'*/: break;
  16558. case 'gridlines' /*case 'Gridlines'*/: break;
  16559. case 'allowsort' /*case 'AllowSort'*/: break;
  16560. case 'allowfilter' /*case 'AllowFilter'*/: break;
  16561. case 'allowinsertrows' /*case 'AllowInsertRows'*/: break;
  16562. case 'allowdeleterows' /*case 'AllowDeleteRows'*/: break;
  16563. case 'allowinsertcols' /*case 'AllowInsertCols'*/: break;
  16564. case 'allowdeletecols' /*case 'AllowDeleteCols'*/: break;
  16565. case 'allowinserthyperlinks' /*case 'AllowInsertHyperlinks'*/: break;
  16566. case 'allowformatcells' /*case 'AllowFormatCells'*/: break;
  16567. case 'allowsizecols' /*case 'AllowSizeCols'*/: break;
  16568. case 'allowsizerows' /*case 'AllowSizeRows'*/: break;
  16569. case 'nosummaryrowsbelowdetail' /*case 'NoSummaryRowsBelowDetail'*/:
  16570. if(!cursheet["!outline"]) cursheet["!outline"] = {};
  16571. cursheet["!outline"].above = true;
  16572. break;
  16573. case 'tabcolorindex' /*case 'TabColorIndex'*/: break;
  16574. case 'donotdisplayheadings' /*case 'DoNotDisplayHeadings'*/: break;
  16575. case 'showpagelayoutzoom' /*case 'ShowPageLayoutZoom'*/: break;
  16576. case 'nosummarycolumnsrightdetail' /*case 'NoSummaryColumnsRightDetail'*/:
  16577. if(!cursheet["!outline"]) cursheet["!outline"] = {};
  16578. cursheet["!outline"].left = true;
  16579. break;
  16580. case 'blackandwhite' /*case 'BlackAndWhite'*/: break;
  16581. case 'donotdisplayzeros' /*case 'DoNotDisplayZeros'*/: break;
  16582. case 'displaypagebreak' /*case 'DisplayPageBreak'*/: break;
  16583. case 'rowcolheadings' /*case 'RowColHeadings'*/: break;
  16584. case 'donotdisplayoutline' /*case 'DoNotDisplayOutline'*/: break;
  16585. case 'noorientation' /*case 'NoOrientation'*/: break;
  16586. case 'allowusepivottables' /*case 'AllowUsePivotTables'*/: break;
  16587. case 'zeroheight' /*case 'ZeroHeight'*/: break;
  16588. case 'viewablerange' /*case 'ViewableRange'*/: break;
  16589. case 'selection' /*case 'Selection'*/: break;
  16590. case 'protectcontents' /*case 'ProtectContents'*/: break;
  16591. default: seen = false;
  16592. } break;
  16593. /* PivotTable */
  16594. case 'pivottable' /*case 'PivotTable'*/: case 'pivotcache' /*case 'PivotCache'*/: switch(Rn[3]) {
  16595. case 'immediateitemsondrop' /*case 'ImmediateItemsOnDrop'*/: break;
  16596. case 'showpagemultipleitemlabel' /*case 'ShowPageMultipleItemLabel'*/: break;
  16597. case 'compactrowindent' /*case 'CompactRowIndent'*/: break;
  16598. case 'location' /*case 'Location'*/: break;
  16599. case 'pivotfield' /*case 'PivotField'*/: break;
  16600. case 'orientation' /*case 'Orientation'*/: break;
  16601. case 'layoutform' /*case 'LayoutForm'*/: break;
  16602. case 'layoutsubtotallocation' /*case 'LayoutSubtotalLocation'*/: break;
  16603. case 'layoutcompactrow' /*case 'LayoutCompactRow'*/: break;
  16604. case 'position' /*case 'Position'*/: break;
  16605. case 'pivotitem' /*case 'PivotItem'*/: break;
  16606. case 'datatype' /*case 'DataType'*/: break;
  16607. case 'datafield' /*case 'DataField'*/: break;
  16608. case 'sourcename' /*case 'SourceName'*/: break;
  16609. case 'parentfield' /*case 'ParentField'*/: break;
  16610. case 'ptlineitems' /*case 'PTLineItems'*/: break;
  16611. case 'ptlineitem' /*case 'PTLineItem'*/: break;
  16612. case 'countofsameitems' /*case 'CountOfSameItems'*/: break;
  16613. case 'item' /*case 'Item'*/: break;
  16614. case 'itemtype' /*case 'ItemType'*/: break;
  16615. case 'ptsource' /*case 'PTSource'*/: break;
  16616. case 'cacheindex' /*case 'CacheIndex'*/: break;
  16617. case 'consolidationreference' /*case 'ConsolidationReference'*/: break;
  16618. case 'filename' /*case 'FileName'*/: break;
  16619. case 'reference' /*case 'Reference'*/: break;
  16620. case 'nocolumngrand' /*case 'NoColumnGrand'*/: break;
  16621. case 'norowgrand' /*case 'NoRowGrand'*/: break;
  16622. case 'blanklineafteritems' /*case 'BlankLineAfterItems'*/: break;
  16623. case 'hidden' /*case 'Hidden'*/: break;
  16624. case 'subtotal' /*case 'Subtotal'*/: break;
  16625. case 'basefield' /*case 'BaseField'*/: break;
  16626. case 'mapchilditems' /*case 'MapChildItems'*/: break;
  16627. case 'function' /*case 'Function'*/: break;
  16628. case 'refreshonfileopen' /*case 'RefreshOnFileOpen'*/: break;
  16629. case 'printsettitles' /*case 'PrintSetTitles'*/: break;
  16630. case 'mergelabels' /*case 'MergeLabels'*/: break;
  16631. case 'defaultversion' /*case 'DefaultVersion'*/: break;
  16632. case 'refreshname' /*case 'RefreshName'*/: break;
  16633. case 'refreshdate' /*case 'RefreshDate'*/: break;
  16634. case 'refreshdatecopy' /*case 'RefreshDateCopy'*/: break;
  16635. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  16636. case 'versionlastupdate' /*case 'VersionLastUpdate'*/: break;
  16637. case 'versionupdateablemin' /*case 'VersionUpdateableMin'*/: break;
  16638. case 'versionrefreshablemin' /*case 'VersionRefreshableMin'*/: break;
  16639. case 'calculation' /*case 'Calculation'*/: break;
  16640. default: seen = false;
  16641. } break;
  16642. /* PageBreaks */
  16643. case 'pagebreaks' /*case 'PageBreaks'*/: switch(Rn[3]) {
  16644. case 'colbreaks' /*case 'ColBreaks'*/: break;
  16645. case 'colbreak' /*case 'ColBreak'*/: break;
  16646. case 'rowbreaks' /*case 'RowBreaks'*/: break;
  16647. case 'rowbreak' /*case 'RowBreak'*/: break;
  16648. case 'colstart' /*case 'ColStart'*/: break;
  16649. case 'colend' /*case 'ColEnd'*/: break;
  16650. case 'rowend' /*case 'RowEnd'*/: break;
  16651. default: seen = false;
  16652. } break;
  16653. /* AutoFilter */
  16654. case 'autofilter' /*case 'AutoFilter'*/: switch(Rn[3]) {
  16655. case 'autofiltercolumn' /*case 'AutoFilterColumn'*/: break;
  16656. case 'autofiltercondition' /*case 'AutoFilterCondition'*/: break;
  16657. case 'autofilterand' /*case 'AutoFilterAnd'*/: break;
  16658. case 'autofilteror' /*case 'AutoFilterOr'*/: break;
  16659. default: seen = false;
  16660. } break;
  16661. /* QueryTable */
  16662. case 'querytable' /*case 'QueryTable'*/: switch(Rn[3]) {
  16663. case 'id' /*case 'Id'*/: break;
  16664. case 'autoformatfont' /*case 'AutoFormatFont'*/: break;
  16665. case 'autoformatpattern' /*case 'AutoFormatPattern'*/: break;
  16666. case 'querysource' /*case 'QuerySource'*/: break;
  16667. case 'querytype' /*case 'QueryType'*/: break;
  16668. case 'enableredirections' /*case 'EnableRedirections'*/: break;
  16669. case 'refreshedinxl9' /*case 'RefreshedInXl9'*/: break;
  16670. case 'urlstring' /*case 'URLString'*/: break;
  16671. case 'htmltables' /*case 'HTMLTables'*/: break;
  16672. case 'connection' /*case 'Connection'*/: break;
  16673. case 'commandtext' /*case 'CommandText'*/: break;
  16674. case 'refreshinfo' /*case 'RefreshInfo'*/: break;
  16675. case 'notitles' /*case 'NoTitles'*/: break;
  16676. case 'nextid' /*case 'NextId'*/: break;
  16677. case 'columninfo' /*case 'ColumnInfo'*/: break;
  16678. case 'overwritecells' /*case 'OverwriteCells'*/: break;
  16679. case 'donotpromptforfile' /*case 'DoNotPromptForFile'*/: break;
  16680. case 'textwizardsettings' /*case 'TextWizardSettings'*/: break;
  16681. case 'source' /*case 'Source'*/: break;
  16682. case 'number' /*case 'Number'*/: break;
  16683. case 'decimal' /*case 'Decimal'*/: break;
  16684. case 'thousandseparator' /*case 'ThousandSeparator'*/: break;
  16685. case 'trailingminusnumbers' /*case 'TrailingMinusNumbers'*/: break;
  16686. case 'formatsettings' /*case 'FormatSettings'*/: break;
  16687. case 'fieldtype' /*case 'FieldType'*/: break;
  16688. case 'delimiters' /*case 'Delimiters'*/: break;
  16689. case 'tab' /*case 'Tab'*/: break;
  16690. case 'comma' /*case 'Comma'*/: break;
  16691. case 'autoformatname' /*case 'AutoFormatName'*/: break;
  16692. case 'versionlastedit' /*case 'VersionLastEdit'*/: break;
  16693. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  16694. default: seen = false;
  16695. } break;
  16696. case 'datavalidation' /*case 'DataValidation'*/:
  16697. switch(Rn[3]) {
  16698. case 'range' /*case 'Range'*/: break;
  16699. case 'type' /*case 'Type'*/: break;
  16700. case 'min' /*case 'Min'*/: break;
  16701. case 'max' /*case 'Max'*/: break;
  16702. case 'sort' /*case 'Sort'*/: break;
  16703. case 'descending' /*case 'Descending'*/: break;
  16704. case 'order' /*case 'Order'*/: break;
  16705. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  16706. case 'value' /*case 'Value'*/: break;
  16707. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  16708. case 'errormessage' /*case 'ErrorMessage'*/: break;
  16709. case 'errortitle' /*case 'ErrorTitle'*/: break;
  16710. case 'inputmessage' /*case 'InputMessage'*/: break;
  16711. case 'inputtitle' /*case 'InputTitle'*/: break;
  16712. case 'combohide' /*case 'ComboHide'*/: break;
  16713. case 'inputhide' /*case 'InputHide'*/: break;
  16714. case 'condition' /*case 'Condition'*/: break;
  16715. case 'qualifier' /*case 'Qualifier'*/: break;
  16716. case 'useblank' /*case 'UseBlank'*/: break;
  16717. case 'value1' /*case 'Value1'*/: break;
  16718. case 'value2' /*case 'Value2'*/: break;
  16719. case 'format' /*case 'Format'*/: break;
  16720. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  16721. default: seen = false;
  16722. } break;
  16723. case 'sorting' /*case 'Sorting'*/:
  16724. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  16725. switch(Rn[3]) {
  16726. case 'range' /*case 'Range'*/: break;
  16727. case 'type' /*case 'Type'*/: break;
  16728. case 'min' /*case 'Min'*/: break;
  16729. case 'max' /*case 'Max'*/: break;
  16730. case 'sort' /*case 'Sort'*/: break;
  16731. case 'descending' /*case 'Descending'*/: break;
  16732. case 'order' /*case 'Order'*/: break;
  16733. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  16734. case 'value' /*case 'Value'*/: break;
  16735. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  16736. case 'errormessage' /*case 'ErrorMessage'*/: break;
  16737. case 'errortitle' /*case 'ErrorTitle'*/: break;
  16738. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  16739. case 'inputmessage' /*case 'InputMessage'*/: break;
  16740. case 'inputtitle' /*case 'InputTitle'*/: break;
  16741. case 'combohide' /*case 'ComboHide'*/: break;
  16742. case 'inputhide' /*case 'InputHide'*/: break;
  16743. case 'condition' /*case 'Condition'*/: break;
  16744. case 'qualifier' /*case 'Qualifier'*/: break;
  16745. case 'useblank' /*case 'UseBlank'*/: break;
  16746. case 'value1' /*case 'Value1'*/: break;
  16747. case 'value2' /*case 'Value2'*/: break;
  16748. case 'format' /*case 'Format'*/: break;
  16749. default: seen = false;
  16750. } break;
  16751. /* MapInfo (schema) */
  16752. case 'mapinfo' /*case 'MapInfo'*/: case 'schema' /*case 'Schema'*/: case 'data' /*case 'data'*/: switch(Rn[3]) {
  16753. case 'map' /*case 'Map'*/: break;
  16754. case 'entry' /*case 'Entry'*/: break;
  16755. case 'range' /*case 'Range'*/: break;
  16756. case 'xpath' /*case 'XPath'*/: break;
  16757. case 'field' /*case 'Field'*/: break;
  16758. case 'xsdtype' /*case 'XSDType'*/: break;
  16759. case 'filteron' /*case 'FilterOn'*/: break;
  16760. case 'aggregate' /*case 'Aggregate'*/: break;
  16761. case 'elementtype' /*case 'ElementType'*/: break;
  16762. case 'attributetype' /*case 'AttributeType'*/: break;
  16763. /* These are from xsd (XML Schema Definition) */
  16764. case 'schema' /*case 'schema'*/:
  16765. case 'element' /*case 'element'*/:
  16766. case 'complextype' /*case 'complexType'*/:
  16767. case 'datatype' /*case 'datatype'*/:
  16768. case 'all' /*case 'all'*/:
  16769. case 'attribute' /*case 'attribute'*/:
  16770. case 'extends' /*case 'extends'*/: break;
  16771. case 'row' /*case 'row'*/: break;
  16772. default: seen = false;
  16773. } break;
  16774. /* SmartTags (can be anything) */
  16775. case 'smarttags' /*case 'SmartTags'*/: break;
  16776. default: seen = false; break;
  16777. }
  16778. if(seen) break;
  16779. /* CustomDocumentProperties */
  16780. if(Rn[3].match(/!\[CDATA/)) break;
  16781. if(!state[state.length-1][1]) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  16782. if(state[state.length-1][0]===/*'CustomDocumentProperties'*/'customdocumentproperties') {
  16783. if(Rn[0].slice(-2) === "/>") break;
  16784. else if(Rn[1]==="/") xlml_set_custprop(Custprops, raw_Rn3, cp, str.slice(pidx, Rn.index));
  16785. else { cp = Rn; pidx = Rn.index + Rn[0].length; }
  16786. break;
  16787. }
  16788. if(opts.WTF) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  16789. }
  16790. var out = ({});
  16791. if(!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
  16792. out.SheetNames = sheetnames;
  16793. out.Workbook = Workbook;
  16794. out.SSF = dup(table_fmt);
  16795. out.Props = Props;
  16796. out.Custprops = Custprops;
  16797. return out;
  16798. }
  16799. function parse_xlml(data, opts) {
  16800. fix_read_opts(opts=opts||{});
  16801. switch(opts.type||"base64") {
  16802. case "base64": return parse_xlml_xml(Base64_decode(data), opts);
  16803. case "binary": case "buffer": case "file": return parse_xlml_xml(data, opts);
  16804. case "array": return parse_xlml_xml(a2s(data), opts);
  16805. }
  16806. }
  16807. /* TODO */
  16808. function write_props_xlml(wb, opts) {
  16809. var o = [];
  16810. /* DocumentProperties */
  16811. if(wb.Props) o.push(xlml_write_docprops(wb.Props, opts));
  16812. /* CustomDocumentProperties */
  16813. if(wb.Custprops) o.push(xlml_write_custprops(wb.Props, wb.Custprops, opts));
  16814. return o.join("");
  16815. }
  16816. /* TODO */
  16817. function write_wb_xlml() {
  16818. /* OfficeDocumentSettings */
  16819. /* ExcelWorkbook */
  16820. return "";
  16821. }
  16822. /* TODO */
  16823. function write_sty_xlml(wb, opts) {
  16824. /* Styles */
  16825. var styles = ['<Style ss:ID="Default" ss:Name="Normal"><NumberFormat/></Style>'];
  16826. opts.cellXfs.forEach(function(xf, id) {
  16827. var payload = [];
  16828. payload.push(writextag('NumberFormat', null, {"ss:Format": escapexml(table_fmt[xf.numFmtId])}));
  16829. var o = {"ss:ID": "s" + (21+id)};
  16830. styles.push(writextag('Style', payload.join(""), o));
  16831. });
  16832. return writextag("Styles", styles.join(""));
  16833. }
  16834. function write_name_xlml(n) { return writextag("NamedRange", null, {"ss:Name": n.Name, "ss:RefersTo":"=" + a1_to_rc(n.Ref, {r:0,c:0})}); }
  16835. function write_names_xlml(wb) {
  16836. if(!((wb||{}).Workbook||{}).Names) return "";
  16837. var names = wb.Workbook.Names;
  16838. var out = [];
  16839. for(var i = 0; i < names.length; ++i) {
  16840. var n = names[i];
  16841. if(n.Sheet != null) continue;
  16842. if(n.Name.match(/^_xlfn\./)) continue;
  16843. out.push(write_name_xlml(n));
  16844. }
  16845. return writextag("Names", out.join(""));
  16846. }
  16847. function write_ws_xlml_names(ws, opts, idx, wb) {
  16848. if(!ws) return "";
  16849. if(!((wb||{}).Workbook||{}).Names) return "";
  16850. var names = wb.Workbook.Names;
  16851. var out = [];
  16852. for(var i = 0; i < names.length; ++i) {
  16853. var n = names[i];
  16854. if(n.Sheet != idx) continue;
  16855. /*switch(n.Name) {
  16856. case "_": continue;
  16857. }*/
  16858. if(n.Name.match(/^_xlfn\./)) continue;
  16859. out.push(write_name_xlml(n));
  16860. }
  16861. return out.join("");
  16862. }
  16863. /* WorksheetOptions */
  16864. function write_ws_xlml_wsopts(ws, opts, idx, wb) {
  16865. if(!ws) return "";
  16866. var o = [];
  16867. /* NOTE: spec technically allows any order, but stick with implied order */
  16868. /* FitToPage */
  16869. /* DoNotDisplayColHeaders */
  16870. /* DoNotDisplayRowHeaders */
  16871. /* ViewableRange */
  16872. /* Selection */
  16873. /* GridlineColor */
  16874. /* Name */
  16875. /* ExcelWorksheetType */
  16876. /* IntlMacro */
  16877. /* Unsynced */
  16878. /* Selected */
  16879. /* CodeName */
  16880. if(ws['!margins']) {
  16881. o.push("<PageSetup>");
  16882. if(ws['!margins'].header) o.push(writextag("Header", null, {'x:Margin':ws['!margins'].header}));
  16883. if(ws['!margins'].footer) o.push(writextag("Footer", null, {'x:Margin':ws['!margins'].footer}));
  16884. o.push(writextag("PageMargins", null, {
  16885. 'x:Bottom': ws['!margins'].bottom || "0.75",
  16886. 'x:Left': ws['!margins'].left || "0.7",
  16887. 'x:Right': ws['!margins'].right || "0.7",
  16888. 'x:Top': ws['!margins'].top || "0.75"
  16889. }));
  16890. o.push("</PageSetup>");
  16891. }
  16892. /* PageSetup */
  16893. /* DisplayPageBreak */
  16894. /* TransitionExpressionEvaluation */
  16895. /* TransitionFormulaEntry */
  16896. /* Print */
  16897. /* Zoom */
  16898. /* PageLayoutZoom */
  16899. /* PageBreakZoom */
  16900. /* ShowPageBreakZoom */
  16901. /* DefaultRowHeight */
  16902. /* DefaultColumnWidth */
  16903. /* StandardWidth */
  16904. if(wb && wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx]) {
  16905. /* Visible */
  16906. if(wb.Workbook.Sheets[idx].Hidden) o.push(writextag("Visible", (wb.Workbook.Sheets[idx].Hidden == 1 ? "SheetHidden" : "SheetVeryHidden"), {}));
  16907. else {
  16908. /* Selected */
  16909. for(var i = 0; i < idx; ++i) if(wb.Workbook.Sheets[i] && !wb.Workbook.Sheets[i].Hidden) break;
  16910. if(i == idx) o.push("<Selected/>");
  16911. }
  16912. }
  16913. /* LeftColumnVisible */
  16914. if(((((wb||{}).Workbook||{}).Views||[])[0]||{}).RTL) o.push("<DisplayRightToLeft/>");
  16915. /* GridlineColorIndex */
  16916. /* DisplayFormulas */
  16917. /* DoNotDisplayGridlines */
  16918. /* DoNotDisplayHeadings */
  16919. /* DoNotDisplayOutline */
  16920. /* ApplyAutomaticOutlineStyles */
  16921. /* NoSummaryRowsBelowDetail */
  16922. /* NoSummaryColumnsRightDetail */
  16923. /* DoNotDisplayZeros */
  16924. /* ActiveRow */
  16925. /* ActiveColumn */
  16926. /* FilterOn */
  16927. /* RangeSelection */
  16928. /* TopRowVisible */
  16929. /* TopRowBottomPane */
  16930. /* LeftColumnRightPane */
  16931. /* ActivePane */
  16932. /* SplitHorizontal */
  16933. /* SplitVertical */
  16934. /* FreezePanes */
  16935. /* FrozenNoSplit */
  16936. /* TabColorIndex */
  16937. /* Panes */
  16938. /* NOTE: Password not supported in XLML Format */
  16939. if(ws['!protect']) {
  16940. o.push(writetag("ProtectContents", "True"));
  16941. if(ws['!protect'].objects) o.push(writetag("ProtectObjects", "True"));
  16942. if(ws['!protect'].scenarios) o.push(writetag("ProtectScenarios", "True"));
  16943. if(ws['!protect'].selectLockedCells != null && !ws['!protect'].selectLockedCells) o.push(writetag("EnableSelection", "NoSelection"));
  16944. else if(ws['!protect'].selectUnlockedCells != null && !ws['!protect'].selectUnlockedCells) o.push(writetag("EnableSelection", "UnlockedCells"));
  16945. [
  16946. [ "formatCells", "AllowFormatCells" ],
  16947. [ "formatColumns", "AllowSizeCols" ],
  16948. [ "formatRows", "AllowSizeRows" ],
  16949. [ "insertColumns", "AllowInsertCols" ],
  16950. [ "insertRows", "AllowInsertRows" ],
  16951. [ "insertHyperlinks", "AllowInsertHyperlinks" ],
  16952. [ "deleteColumns", "AllowDeleteCols" ],
  16953. [ "deleteRows", "AllowDeleteRows" ],
  16954. [ "sort", "AllowSort" ],
  16955. [ "autoFilter", "AllowFilter" ],
  16956. [ "pivotTables", "AllowUsePivotTables" ]
  16957. ].forEach(function(x) { if(ws['!protect'][x[0]]) o.push("<"+x[1]+"/>"); });
  16958. }
  16959. if(o.length == 0) return "";
  16960. return writextag("WorksheetOptions", o.join(""), {xmlns:XLMLNS.x});
  16961. }
  16962. function write_ws_xlml_comment(comments) {
  16963. return comments.map(function(c) {
  16964. // TODO: formatted text
  16965. var t = xlml_unfixstr(c.t||"");
  16966. var d =writextag("ss:Data", t, {"xmlns":"http://www.w3.org/TR/REC-html40"});
  16967. return writextag("Comment", d, {"ss:Author":c.a});
  16968. }).join("");
  16969. }
  16970. function write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr){
  16971. if(!cell || (cell.v == undefined && cell.f == undefined)) return "";
  16972. var attr = {};
  16973. if(cell.f) attr["ss:Formula"] = "=" + escapexml(a1_to_rc(cell.f, addr));
  16974. if(cell.F && cell.F.slice(0, ref.length) == ref) {
  16975. var end = decode_cell(cell.F.slice(ref.length + 1));
  16976. attr["ss:ArrayRange"] = "RC:R" + (end.r == addr.r ? "" : "[" + (end.r - addr.r) + "]") + "C" + (end.c == addr.c ? "" : "[" + (end.c - addr.c) + "]");
  16977. }
  16978. if(cell.l && cell.l.Target) {
  16979. attr["ss:HRef"] = escapexml(cell.l.Target);
  16980. if(cell.l.Tooltip) attr["x:HRefScreenTip"] = escapexml(cell.l.Tooltip);
  16981. }
  16982. if(ws['!merges']) {
  16983. var marr = ws['!merges'];
  16984. for(var mi = 0; mi != marr.length; ++mi) {
  16985. if(marr[mi].s.c != addr.c || marr[mi].s.r != addr.r) continue;
  16986. if(marr[mi].e.c > marr[mi].s.c) attr['ss:MergeAcross'] = marr[mi].e.c - marr[mi].s.c;
  16987. if(marr[mi].e.r > marr[mi].s.r) attr['ss:MergeDown'] = marr[mi].e.r - marr[mi].s.r;
  16988. }
  16989. }
  16990. var t = "", p = "";
  16991. switch(cell.t) {
  16992. case 'z': if(!opts.sheetStubs) return ""; break;
  16993. case 'n': t = 'Number'; p = String(cell.v); break;
  16994. case 'b': t = 'Boolean'; p = (cell.v ? "1" : "0"); break;
  16995. case 'e': t = 'Error'; p = BErr[cell.v]; break;
  16996. case 'd': t = 'DateTime'; p = new Date(cell.v).toISOString(); if(cell.z == null) cell.z = cell.z || table_fmt[14]; break;
  16997. case 's': t = 'String'; p = escapexlml(cell.v||""); break;
  16998. }
  16999. /* TODO: cell style */
  17000. var os = get_cell_style(opts.cellXfs, cell, opts);
  17001. attr["ss:StyleID"] = "s" + (21+os);
  17002. attr["ss:Index"] = addr.c + 1;
  17003. var _v = (cell.v != null ? p : "");
  17004. var m = cell.t == 'z' ? "" : ('<Data ss:Type="' + t + '">' + _v + '</Data>');
  17005. if((cell.c||[]).length > 0) m += write_ws_xlml_comment(cell.c);
  17006. return writextag("Cell", m, attr);
  17007. }
  17008. function write_ws_xlml_row(R, row) {
  17009. var o = '<Row ss:Index="' + (R+1) + '"';
  17010. if(row) {
  17011. if(row.hpt && !row.hpx) row.hpx = pt2px(row.hpt);
  17012. if(row.hpx) o += ' ss:AutoFitHeight="0" ss:Height="' + row.hpx + '"';
  17013. if(row.hidden) o += ' ss:Hidden="1"';
  17014. }
  17015. return o + '>';
  17016. }
  17017. /* TODO */
  17018. function write_ws_xlml_table(ws, opts, idx, wb) {
  17019. if(!ws['!ref']) return "";
  17020. var range = safe_decode_range(ws['!ref']);
  17021. var marr = ws['!merges'] || [], mi = 0;
  17022. var o = [];
  17023. if(ws['!cols']) ws['!cols'].forEach(function(n, i) {
  17024. process_col(n);
  17025. var w = !!n.width;
  17026. var p = col_obj_w(i, n);
  17027. var k = {"ss:Index":i+1};
  17028. if(w) k['ss:Width'] = width2px(p.width);
  17029. if(n.hidden) k['ss:Hidden']="1";
  17030. o.push(writextag("Column",null,k));
  17031. });
  17032. var dense = Array.isArray(ws);
  17033. for(var R = range.s.r; R <= range.e.r; ++R) {
  17034. var row = [write_ws_xlml_row(R, (ws['!rows']||[])[R])];
  17035. for(var C = range.s.c; C <= range.e.c; ++C) {
  17036. var skip = false;
  17037. for(mi = 0; mi != marr.length; ++mi) {
  17038. if(marr[mi].s.c > C) continue;
  17039. if(marr[mi].s.r > R) continue;
  17040. if(marr[mi].e.c < C) continue;
  17041. if(marr[mi].e.r < R) continue;
  17042. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  17043. break;
  17044. }
  17045. if(skip) continue;
  17046. var addr = {r:R,c:C};
  17047. var ref = encode_cell(addr), cell = dense ? (ws[R]||[])[C] : ws[ref];
  17048. row.push(write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr));
  17049. }
  17050. row.push("</Row>");
  17051. if(row.length > 2) o.push(row.join(""));
  17052. }
  17053. return o.join("");
  17054. }
  17055. function write_ws_xlml(idx, opts, wb) {
  17056. var o = [];
  17057. var s = wb.SheetNames[idx];
  17058. var ws = wb.Sheets[s];
  17059. var t = ws ? write_ws_xlml_names(ws, opts, idx, wb) : "";
  17060. if(t.length > 0) o.push("<Names>" + t + "</Names>");
  17061. /* Table */
  17062. t = ws ? write_ws_xlml_table(ws, opts, idx, wb) : "";
  17063. if(t.length > 0) o.push("<Table>" + t + "</Table>");
  17064. /* WorksheetOptions */
  17065. o.push(write_ws_xlml_wsopts(ws, opts, idx, wb));
  17066. return o.join("");
  17067. }
  17068. function write_xlml(wb, opts) {
  17069. if(!opts) opts = {};
  17070. if(!wb.SSF) wb.SSF = dup(table_fmt);
  17071. if(wb.SSF) {
  17072. make_ssf(); SSF_load_table(wb.SSF);
  17073. // $FlowIgnore
  17074. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  17075. opts.ssf = wb.SSF;
  17076. opts.cellXfs = [];
  17077. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  17078. }
  17079. var d = [];
  17080. d.push(write_props_xlml(wb, opts));
  17081. d.push(write_wb_xlml(wb, opts));
  17082. d.push("");
  17083. d.push("");
  17084. for(var i = 0; i < wb.SheetNames.length; ++i)
  17085. d.push(writextag("Worksheet", write_ws_xlml(i, opts, wb), {"ss:Name":escapexml(wb.SheetNames[i])}));
  17086. d[2] = write_sty_xlml(wb, opts);
  17087. d[3] = write_names_xlml(wb, opts);
  17088. return XML_HEADER + writextag("Workbook", d.join(""), {
  17089. 'xmlns': XLMLNS.ss,
  17090. 'xmlns:o': XLMLNS.o,
  17091. 'xmlns:x': XLMLNS.x,
  17092. 'xmlns:ss': XLMLNS.ss,
  17093. 'xmlns:dt': XLMLNS.dt,
  17094. 'xmlns:html': XLMLNS.html
  17095. });
  17096. }
  17097. /* [MS-OLEDS] 2.3.8 CompObjStream */
  17098. function parse_compobj(obj) {
  17099. var v = {};
  17100. var o = obj.content;
  17101. /* [MS-OLEDS] 2.3.7 CompObjHeader -- All fields MUST be ignored */
  17102. o.l = 28;
  17103. v.AnsiUserType = o.read_shift(0, "lpstr-ansi");
  17104. v.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o);
  17105. if(o.length - o.l <= 4) return v;
  17106. var m = o.read_shift(4);
  17107. if(m == 0 || m > 40) return v;
  17108. o.l-=4; v.Reserved1 = o.read_shift(0, "lpstr-ansi");
  17109. if(o.length - o.l <= 4) return v;
  17110. m = o.read_shift(4);
  17111. if(m !== 0x71b239f4) return v;
  17112. v.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o);
  17113. m = o.read_shift(4);
  17114. if(m == 0 || m > 40) return v;
  17115. o.l-=4; v.Reserved2 = o.read_shift(0, "lpwstr");
  17116. }
  17117. /*
  17118. Continue logic for:
  17119. - 2.4.58 Continue 0x003c
  17120. - 2.4.59 ContinueBigName 0x043c
  17121. - 2.4.60 ContinueFrt 0x0812
  17122. - 2.4.61 ContinueFrt11 0x0875
  17123. - 2.4.62 ContinueFrt12 0x087f
  17124. */
  17125. var CONTINUE_RT = [ 0x003c, 0x043c, 0x0812, 0x0875, 0x087f ];
  17126. function slurp(RecordType, R, blob, length, opts) {
  17127. var l = length;
  17128. var bufs = [];
  17129. var d = blob.slice(blob.l,blob.l+l);
  17130. if(opts && opts.enc && opts.enc.insitu && d.length > 0) switch(RecordType) {
  17131. 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 */:
  17132. break;
  17133. case 0x0085 /* BoundSheet8 */:
  17134. break;
  17135. default:
  17136. opts.enc.insitu(d);
  17137. }
  17138. bufs.push(d);
  17139. blob.l += l;
  17140. var nextrt = __readUInt16LE(blob,blob.l), next = XLSRecordEnum[nextrt];
  17141. var start = 0;
  17142. while(next != null && CONTINUE_RT.indexOf(nextrt) > -1) {
  17143. l = __readUInt16LE(blob,blob.l+2);
  17144. start = blob.l + 4;
  17145. if(nextrt == 0x0812 /* ContinueFrt */) start += 4;
  17146. else if(nextrt == 0x0875 || nextrt == 0x087f) {
  17147. start += 12;
  17148. }
  17149. d = blob.slice(start,blob.l+4+l);
  17150. bufs.push(d);
  17151. blob.l += 4+l;
  17152. next = (XLSRecordEnum[nextrt = __readUInt16LE(blob, blob.l)]);
  17153. }
  17154. var b = (bconcat(bufs));
  17155. prep_blob(b, 0);
  17156. var ll = 0; b.lens = [];
  17157. for(var j = 0; j < bufs.length; ++j) { b.lens.push(ll); ll += bufs[j].length; }
  17158. if(b.length < length) throw "XLS Record 0x" + RecordType.toString(16) + " Truncated: " + b.length + " < " + length;
  17159. return R.f(b, b.length, opts);
  17160. }
  17161. function safe_format_xf(p, opts, date1904) {
  17162. if(p.t === 'z') return;
  17163. if(!p.XF) return;
  17164. var fmtid = 0;
  17165. try {
  17166. fmtid = p.z || p.XF.numFmtId || 0;
  17167. if(opts.cellNF) p.z = table_fmt[fmtid];
  17168. } catch(e) { if(opts.WTF) throw e; }
  17169. if(!opts || opts.cellText !== false) try {
  17170. if(p.t === 'e') { p.w = p.w || BErr[p.v]; }
  17171. else if(fmtid === 0 || fmtid == "General") {
  17172. if(p.t === 'n') {
  17173. if((p.v|0) === p.v) p.w = p.v.toString(10);
  17174. else p.w = SSF_general_num(p.v);
  17175. }
  17176. else p.w = SSF_general(p.v);
  17177. }
  17178. else p.w = SSF_format(fmtid,p.v, {date1904:!!date1904, dateNF: opts && opts.dateNF});
  17179. } catch(e) { if(opts.WTF) throw e; }
  17180. if(opts.cellDates && fmtid && p.t == 'n' && fmt_is_date(table_fmt[fmtid] || String(fmtid))) {
  17181. 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); }
  17182. }
  17183. }
  17184. function make_cell(val, ixfe, t) {
  17185. return ({v:val, ixfe:ixfe, t:t});
  17186. }
  17187. // 2.3.2
  17188. function parse_workbook(blob, options) {
  17189. var wb = ({opts:{}});
  17190. var Sheets = {};
  17191. if(DENSE != null && options.dense == null) options.dense = DENSE;
  17192. var out = ((options.dense ? [] : {}));
  17193. var Directory = {};
  17194. var range = ({});
  17195. var last_formula = null;
  17196. var sst = ([]);
  17197. var cur_sheet = "";
  17198. var Preamble = {};
  17199. var lastcell, last_cell = "", cc, cmnt, rngC, rngR;
  17200. var sharedf = {};
  17201. var arrayf = [];
  17202. var temp_val;
  17203. var country;
  17204. var XFs = []; /* XF records */
  17205. var palette = [];
  17206. var Workbook = ({ Sheets:[], WBProps:{date1904:false}, Views:[{}] }), wsprops = {};
  17207. var get_rgb = function getrgb(icv) {
  17208. if(icv < 8) return XLSIcv[icv];
  17209. if(icv < 64) return palette[icv-8] || XLSIcv[icv];
  17210. return XLSIcv[icv];
  17211. };
  17212. var process_cell_style = function pcs(cell, line, options) {
  17213. var xfd = line.XF.data;
  17214. if(!xfd || !xfd.patternType || !options || !options.cellStyles) return;
  17215. line.s = ({});
  17216. line.s.patternType = xfd.patternType;
  17217. var t;
  17218. if((t = rgb2Hex(get_rgb(xfd.icvFore)))) { line.s.fgColor = {rgb:t}; }
  17219. if((t = rgb2Hex(get_rgb(xfd.icvBack)))) { line.s.bgColor = {rgb:t}; }
  17220. };
  17221. var addcell = function addcell(cell, line, options) {
  17222. if(file_depth > 1) return;
  17223. if(options.sheetRows && cell.r >= options.sheetRows) return;
  17224. if(options.cellStyles && line.XF && line.XF.data) process_cell_style(cell, line, options);
  17225. delete line.ixfe; delete line.XF;
  17226. lastcell = cell;
  17227. last_cell = encode_cell(cell);
  17228. if(!range || !range.s || !range.e) range = {s:{r:0,c:0},e:{r:0,c:0}};
  17229. if(cell.r < range.s.r) range.s.r = cell.r;
  17230. if(cell.c < range.s.c) range.s.c = cell.c;
  17231. if(cell.r + 1 > range.e.r) range.e.r = cell.r + 1;
  17232. if(cell.c + 1 > range.e.c) range.e.c = cell.c + 1;
  17233. if(options.cellFormula && line.f) {
  17234. for(var afi = 0; afi < arrayf.length; ++afi) {
  17235. if(arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
  17236. if(arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
  17237. line.F = encode_range(arrayf[afi][0]);
  17238. if(arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
  17239. if(line.f) line.f = "" + stringify_formula(arrayf[afi][1], range, cell, supbooks, opts);
  17240. break;
  17241. }
  17242. }
  17243. {
  17244. if(options.dense) {
  17245. if(!out[cell.r]) out[cell.r] = [];
  17246. out[cell.r][cell.c] = line;
  17247. } else out[last_cell] = line;
  17248. }
  17249. };
  17250. var opts = ({
  17251. enc: false, // encrypted
  17252. sbcch: 0, // cch in the preceding SupBook
  17253. snames: [], // sheetnames
  17254. sharedf: sharedf, // shared formulae by address
  17255. arrayf: arrayf, // array formulae array
  17256. rrtabid: [], // RRTabId
  17257. lastuser: "", // Last User from WriteAccess
  17258. biff: 8, // BIFF version
  17259. codepage: 0, // CP from CodePage record
  17260. winlocked: 0, // fLockWn from WinProtect
  17261. cellStyles: !!options && !!options.cellStyles,
  17262. WTF: !!options && !!options.wtf
  17263. });
  17264. if(options.password) opts.password = options.password;
  17265. var themes;
  17266. var merges = [];
  17267. var objects = [];
  17268. var colinfo = [], rowinfo = [];
  17269. var seencol = false;
  17270. var supbooks = ([]); // 1-indexed, will hold extern names
  17271. supbooks.SheetNames = opts.snames;
  17272. supbooks.sharedf = opts.sharedf;
  17273. supbooks.arrayf = opts.arrayf;
  17274. supbooks.names = [];
  17275. supbooks.XTI = [];
  17276. var last_RT = 0;
  17277. var file_depth = 0; /* TODO: make a real stack */
  17278. var BIFF2Fmt = 0, BIFF2FmtTable = [];
  17279. var FilterDatabases = []; /* TODO: sort out supbooks and undefined elsewhere */
  17280. var last_lbl;
  17281. /* explicit override for some broken writers */
  17282. opts.codepage = 1200;
  17283. set_cp(1200);
  17284. var seen_codepage = false;
  17285. while(blob.l < blob.length - 1) {
  17286. var s = blob.l;
  17287. var RecordType = blob.read_shift(2);
  17288. if(RecordType === 0 && last_RT === 0x000a /* EOF */) break;
  17289. var length = (blob.l === blob.length ? 0 : blob.read_shift(2));
  17290. var R = XLSRecordEnum[RecordType];
  17291. //console.log(RecordType.toString(16), RecordType, R, blob.l, length, blob.length);
  17292. //if(!R) console.log(blob.slice(blob.l, blob.l + length));
  17293. if(R && R.f) {
  17294. if(options.bookSheets) {
  17295. if(last_RT === 0x0085 /* BoundSheet8 */ && RecordType !== 0x0085 /* R.n !== 'BoundSheet8' */) break;
  17296. }
  17297. last_RT = RecordType;
  17298. if(R.r === 2 || R.r == 12) {
  17299. var rt = blob.read_shift(2); length -= 2;
  17300. if(!opts.enc && rt !== RecordType && (((rt&0xFF)<<8)|(rt>>8)) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
  17301. if(R.r == 12){
  17302. blob.l += 10; length -= 10;
  17303. } // skip FRT
  17304. }
  17305. //console.error(R,blob.l,length,blob.length);
  17306. var val = ({});
  17307. if(RecordType === 0x000a /* EOF */) val = R.f(blob, length, opts);
  17308. else val = slurp(RecordType, R, blob, length, opts);
  17309. if(file_depth == 0 && [0x0009, 0x0209, 0x0409, 0x0809].indexOf(last_RT) === -1 /* 'BOF' */) continue;
  17310. switch(RecordType) {
  17311. case 0x0022 /* Date1904 */:
  17312. wb.opts.Date1904 = Workbook.WBProps.date1904 = val; break;
  17313. case 0x0086 /* WriteProtect */: wb.opts.WriteProtect = true; break;
  17314. case 0x002f /* FilePass */:
  17315. if(!opts.enc) blob.l = 0;
  17316. opts.enc = val;
  17317. if(!options.password) throw new Error("File is password-protected");
  17318. if(val.valid == null) throw new Error("Encryption scheme unsupported");
  17319. if(!val.valid) throw new Error("Password is incorrect");
  17320. break;
  17321. case 0x005c /* WriteAccess */: opts.lastuser = val; break;
  17322. case 0x0042 /* CodePage */:
  17323. var cpval = Number(val);
  17324. /* overrides based on test cases */
  17325. switch(cpval) {
  17326. case 0x5212: cpval = 1200; break;
  17327. case 0x8000: cpval = 10000; break;
  17328. case 0x8001: cpval = 1252; break;
  17329. }
  17330. set_cp(opts.codepage = cpval);
  17331. seen_codepage = true;
  17332. break;
  17333. case 0x013d /* RRTabId */: opts.rrtabid = val; break;
  17334. case 0x0019 /* WinProtect */: opts.winlocked = val; break;
  17335. case 0x01b7 /* RefreshAll */: wb.opts["RefreshAll"] = val; break;
  17336. case 0x000c /* CalcCount */: wb.opts["CalcCount"] = val; break;
  17337. case 0x0010 /* CalcDelta */: wb.opts["CalcDelta"] = val; break;
  17338. case 0x0011 /* CalcIter */: wb.opts["CalcIter"] = val; break;
  17339. case 0x000d /* CalcMode */: wb.opts["CalcMode"] = val; break;
  17340. case 0x000e /* CalcPrecision */: wb.opts["CalcPrecision"] = val; break;
  17341. case 0x005f /* CalcSaveRecalc */: wb.opts["CalcSaveRecalc"] = val; break;
  17342. case 0x000f /* CalcRefMode */: opts.CalcRefMode = val; break; // TODO: implement R1C1
  17343. case 0x08a3 /* ForceFullCalculation */: wb.opts.FullCalc = val; break;
  17344. case 0x0081 /* WsBool */:
  17345. if(val.fDialog) out["!type"] = "dialog";
  17346. if(!val.fBelow) (out["!outline"] || (out["!outline"] = {})).above = true;
  17347. if(!val.fRight) (out["!outline"] || (out["!outline"] = {})).left = true;
  17348. break; // TODO
  17349. case 0x00e0 /* XF */:
  17350. XFs.push(val); break;
  17351. case 0x01ae /* SupBook */:
  17352. supbooks.push([val]);
  17353. supbooks[supbooks.length-1].XTI = [];
  17354. break;
  17355. case 0x0023: case 0x0223 /* ExternName */:
  17356. supbooks[supbooks.length-1].push(val);
  17357. break;
  17358. case 0x0018: case 0x0218 /* Lbl */:
  17359. last_lbl = ({
  17360. Name: val.Name,
  17361. Ref: stringify_formula(val.rgce,range,null,supbooks,opts)
  17362. });
  17363. if(val.itab > 0) last_lbl.Sheet = val.itab - 1;
  17364. supbooks.names.push(last_lbl);
  17365. if(!supbooks[0]) { supbooks[0] = []; supbooks[0].XTI = []; }
  17366. supbooks[supbooks.length-1].push(val);
  17367. if(val.Name == "_xlnm._FilterDatabase" && val.itab > 0)
  17368. if(val.rgce && val.rgce[0] && val.rgce[0][0] && val.rgce[0][0][0] == 'PtgArea3d')
  17369. FilterDatabases[val.itab - 1] = { ref: encode_range(val.rgce[0][0][1][2]) };
  17370. break;
  17371. case 0x0016 /* ExternCount */: opts.ExternCount = val; break;
  17372. case 0x0017 /* ExternSheet */:
  17373. if(supbooks.length == 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  17374. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val); supbooks.XTI = supbooks.XTI.concat(val); break;
  17375. case 0x0894 /* NameCmt */:
  17376. /* TODO: search for correct name */
  17377. if(opts.biff < 8) break;
  17378. if(last_lbl != null) last_lbl.Comment = val[1];
  17379. break;
  17380. case 0x0012 /* Protect */: out["!protect"] = val; break; /* for sheet or book */
  17381. case 0x0013 /* Password */: if(val !== 0 && opts.WTF) console.error("Password verifier: " + val); break;
  17382. case 0x0085 /* BoundSheet8 */: {
  17383. Directory[val.pos] = val;
  17384. opts.snames.push(val.name);
  17385. } break;
  17386. case 0x000a /* EOF */: {
  17387. if(--file_depth) break;
  17388. if(range.e) {
  17389. if(range.e.r > 0 && range.e.c > 0) {
  17390. range.e.r--; range.e.c--;
  17391. out["!ref"] = encode_range(range);
  17392. if(options.sheetRows && options.sheetRows <= range.e.r) {
  17393. var tmpri = range.e.r;
  17394. range.e.r = options.sheetRows - 1;
  17395. out["!fullref"] = out["!ref"];
  17396. out["!ref"] = encode_range(range);
  17397. range.e.r = tmpri;
  17398. }
  17399. range.e.r++; range.e.c++;
  17400. }
  17401. if(merges.length > 0) out["!merges"] = merges;
  17402. if(objects.length > 0) out["!objects"] = objects;
  17403. if(colinfo.length > 0) out["!cols"] = colinfo;
  17404. if(rowinfo.length > 0) out["!rows"] = rowinfo;
  17405. Workbook.Sheets.push(wsprops);
  17406. }
  17407. if(cur_sheet === "") Preamble = out; else Sheets[cur_sheet] = out;
  17408. out = ((options.dense ? [] : {}));
  17409. } break;
  17410. case 0x0009: case 0x0209: case 0x0409: case 0x0809 /* BOF */: {
  17411. if(opts.biff === 8) opts.biff = {
  17412. 0x0009:2,
  17413. 0x0209:3,
  17414. 0x0409:4
  17415. }[RecordType] || {
  17416. 0x0200:2,
  17417. 0x0300:3,
  17418. 0x0400:4,
  17419. 0x0500:5,
  17420. 0x0600:8,
  17421. 0x0002:2,
  17422. 0x0007:2
  17423. }[val.BIFFVer] || 8;
  17424. opts.biffguess = val.BIFFVer == 0;
  17425. if(val.BIFFVer == 0 && val.dt == 0x1000) { opts.biff = 5; seen_codepage = true; set_cp(opts.codepage = 28591); }
  17426. if(opts.biff == 8 && val.BIFFVer == 0 && val.dt == 16) opts.biff = 2;
  17427. if(file_depth++) break;
  17428. out = ((options.dense ? [] : {}));
  17429. if(opts.biff < 8 && !seen_codepage) { seen_codepage = true; set_cp(opts.codepage = options.codepage || 1252); }
  17430. if(opts.biff < 5 || val.BIFFVer == 0 && val.dt == 0x1000) {
  17431. if(cur_sheet === "") cur_sheet = "Sheet1";
  17432. range = {s:{r:0,c:0},e:{r:0,c:0}};
  17433. /* fake BoundSheet8 */
  17434. var fakebs8 = {pos: blob.l - length, name:cur_sheet};
  17435. Directory[fakebs8.pos] = fakebs8;
  17436. opts.snames.push(cur_sheet);
  17437. }
  17438. else cur_sheet = (Directory[s] || {name:""}).name;
  17439. if(val.dt == 0x20) out["!type"] = "chart";
  17440. if(val.dt == 0x40) out["!type"] = "macro";
  17441. merges = [];
  17442. objects = [];
  17443. opts.arrayf = arrayf = [];
  17444. colinfo = []; rowinfo = [];
  17445. seencol = false;
  17446. wsprops = {Hidden:(Directory[s]||{hs:0}).hs, name:cur_sheet };
  17447. } break;
  17448. case 0x0203 /* Number */: case 0x0003 /* BIFF2NUM */: case 0x0002 /* BIFF2INT */: {
  17449. if(out["!type"] == "chart") if(options.dense ? (out[val.r]||[])[val.c]: out[encode_cell({c:val.c, r:val.r})]) ++val.c;
  17450. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe]||{}, v:val.val, t:'n'});
  17451. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17452. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17453. addcell({c:val.c, r:val.r}, temp_val, options);
  17454. } break;
  17455. case 0x0005: case 0x0205 /* BoolErr */: {
  17456. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:val.t});
  17457. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17458. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17459. addcell({c:val.c, r:val.r}, temp_val, options);
  17460. } break;
  17461. case 0x027e /* RK */: {
  17462. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.rknum, t:'n'});
  17463. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17464. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17465. addcell({c:val.c, r:val.r}, temp_val, options);
  17466. } break;
  17467. case 0x00bd /* MulRk */: {
  17468. for(var j = val.c; j <= val.C; ++j) {
  17469. var ixfe = val.rkrec[j-val.c][0];
  17470. temp_val= ({ixfe:ixfe, XF:XFs[ixfe], v:val.rkrec[j-val.c][1], t:'n'});
  17471. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17472. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17473. addcell({c:j, r:val.r}, temp_val, options);
  17474. }
  17475. } break;
  17476. case 0x0006: case 0x0206: case 0x0406 /* Formula */: {
  17477. if(val.val == 'String') { last_formula = val; break; }
  17478. temp_val = make_cell(val.val, val.cell.ixfe, val.tt);
  17479. temp_val.XF = XFs[temp_val.ixfe];
  17480. if(options.cellFormula) {
  17481. var _f = val.formula;
  17482. if(_f && _f[0] && _f[0][0] && _f[0][0][0] == 'PtgExp') {
  17483. var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
  17484. var _fe = encode_cell({r:_fr, c:_fc});
  17485. if(sharedf[_fe]) temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  17486. else temp_val.F = ((options.dense ? (out[_fr]||[])[_fc]: out[_fe]) || {}).F;
  17487. } else temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  17488. }
  17489. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17490. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17491. addcell(val.cell, temp_val, options);
  17492. last_formula = val;
  17493. } break;
  17494. case 0x0007: case 0x0207 /* String */: {
  17495. if(last_formula) { /* technically always true */
  17496. last_formula.val = val;
  17497. temp_val = make_cell(val, last_formula.cell.ixfe, 's');
  17498. temp_val.XF = XFs[temp_val.ixfe];
  17499. if(options.cellFormula) {
  17500. temp_val.f = ""+stringify_formula(last_formula.formula, range, last_formula.cell, supbooks, opts);
  17501. }
  17502. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17503. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17504. addcell(last_formula.cell, temp_val, options);
  17505. last_formula = null;
  17506. } else throw new Error("String record expects Formula");
  17507. } break;
  17508. case 0x0021: case 0x0221 /* Array */: {
  17509. arrayf.push(val);
  17510. var _arraystart = encode_cell(val[0].s);
  17511. cc = options.dense ? (out[val[0].s.r]||[])[val[0].s.c] : out[_arraystart];
  17512. if(options.cellFormula && cc) {
  17513. if(!last_formula) break; /* technically unreachable */
  17514. if(!_arraystart || !cc) break;
  17515. cc.f = ""+stringify_formula(val[1], range, val[0], supbooks, opts);
  17516. cc.F = encode_range(val[0]);
  17517. }
  17518. } break;
  17519. case 0x04bc /* ShrFmla */: {
  17520. if(!options.cellFormula) break;
  17521. if(last_cell) {
  17522. /* TODO: capture range */
  17523. if(!last_formula) break; /* technically unreachable */
  17524. sharedf[encode_cell(last_formula.cell)]= val[0];
  17525. cc = options.dense ? (out[last_formula.cell.r]||[])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
  17526. (cc||{}).f = ""+stringify_formula(val[0], range, lastcell, supbooks, opts);
  17527. }
  17528. } break;
  17529. case 0x00fd /* LabelSst */:
  17530. temp_val=make_cell(sst[val.isst].t, val.ixfe, 's');
  17531. if(sst[val.isst].h) temp_val.h = sst[val.isst].h;
  17532. temp_val.XF = XFs[temp_val.ixfe];
  17533. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17534. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17535. addcell({c:val.c, r:val.r}, temp_val, options);
  17536. break;
  17537. case 0x0201 /* Blank */: if(options.sheetStubs) {
  17538. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], t:'z'});
  17539. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17540. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17541. addcell({c:val.c, r:val.r}, temp_val, options);
  17542. } break;
  17543. case 0x00be /* MulBlank */: if(options.sheetStubs) {
  17544. for(var _j = val.c; _j <= val.C; ++_j) {
  17545. var _ixfe = val.ixfe[_j-val.c];
  17546. temp_val= ({ixfe:_ixfe, XF:XFs[_ixfe], t:'z'});
  17547. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17548. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17549. addcell({c:_j, r:val.r}, temp_val, options);
  17550. }
  17551. } break;
  17552. case 0x00d6 /* RString */:
  17553. case 0x0204 /* Label */: case 0x0004 /* BIFF2STR */:
  17554. temp_val=make_cell(val.val, val.ixfe, 's');
  17555. temp_val.XF = XFs[temp_val.ixfe];
  17556. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x3F];
  17557. safe_format_xf(temp_val, options, wb.opts.Date1904);
  17558. addcell({c:val.c, r:val.r}, temp_val, options);
  17559. break;
  17560. case 0x0000: case 0x0200 /* Dimensions */: {
  17561. if(file_depth === 1) range = val; /* TODO: stack */
  17562. } break;
  17563. case 0x00fc /* SST */: {
  17564. sst = val;
  17565. } break;
  17566. case 0x041e /* Format */: { /* val = [id, fmt] */
  17567. if(opts.biff == 4) {
  17568. BIFF2FmtTable[BIFF2Fmt++] = val[1];
  17569. for(var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if(table_fmt[b4idx] == val[1]) break;
  17570. if(b4idx >= 163) SSF_load(val[1], BIFF2Fmt + 163);
  17571. }
  17572. else SSF_load(val[1], val[0]);
  17573. } break;
  17574. case 0x001e /* BIFF2FORMAT */: {
  17575. BIFF2FmtTable[BIFF2Fmt++] = val;
  17576. for(var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if(table_fmt[b2idx] == val) break;
  17577. if(b2idx >= 163) SSF_load(val, BIFF2Fmt + 163);
  17578. } break;
  17579. case 0x00e5 /* MergeCells */: merges = merges.concat(val); break;
  17580. case 0x005d /* Obj */: objects[val.cmo[0]] = opts.lastobj = val; break;
  17581. case 0x01b6 /* TxO */: opts.lastobj.TxO = val; break;
  17582. case 0x007f /* ImData */: opts.lastobj.ImData = val; break;
  17583. case 0x01b8 /* HLink */: {
  17584. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  17585. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  17586. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  17587. if(cc) cc.l = val[1];
  17588. }
  17589. } break;
  17590. case 0x0800 /* HLinkTooltip */: {
  17591. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  17592. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  17593. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  17594. if(cc && cc.l) cc.l.Tooltip = val[1];
  17595. }
  17596. } break;
  17597. case 0x001c /* Note */: {
  17598. if(opts.biff <= 5 && opts.biff >= 2) break; /* TODO: BIFF5 */
  17599. cc = options.dense ? (out[val[0].r]||[])[val[0].c] : out[encode_cell(val[0])];
  17600. var noteobj = objects[val[2]];
  17601. if(!cc) {
  17602. if(options.dense) {
  17603. if(!out[val[0].r]) out[val[0].r] = [];
  17604. cc = out[val[0].r][val[0].c] = ({t:"z"});
  17605. } else {
  17606. cc = out[encode_cell(val[0])] = ({t:"z"});
  17607. }
  17608. range.e.r = Math.max(range.e.r, val[0].r);
  17609. range.s.r = Math.min(range.s.r, val[0].r);
  17610. range.e.c = Math.max(range.e.c, val[0].c);
  17611. range.s.c = Math.min(range.s.c, val[0].c);
  17612. }
  17613. if(!cc.c) cc.c = [];
  17614. cmnt = {a:val[1],t:noteobj.TxO.t};
  17615. cc.c.push(cmnt);
  17616. } break;
  17617. case 0x087d /* XFExt */: update_xfext(XFs[val.ixfe], val.ext); break;
  17618. case 0x007d /* ColInfo */: {
  17619. if(!opts.cellStyles) break;
  17620. while(val.e >= val.s) {
  17621. colinfo[val.e--] = { width: val.w/256, level: (val.level || 0), hidden: !!(val.flags & 1) };
  17622. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  17623. process_col(colinfo[val.e+1]);
  17624. }
  17625. } break;
  17626. case 0x0208 /* Row */: {
  17627. var rowobj = {};
  17628. if(val.level != null) { rowinfo[val.r] = rowobj; rowobj.level = val.level; }
  17629. if(val.hidden) { rowinfo[val.r] = rowobj; rowobj.hidden = true; }
  17630. if(val.hpt) {
  17631. rowinfo[val.r] = rowobj;
  17632. rowobj.hpt = val.hpt; rowobj.hpx = pt2px(val.hpt);
  17633. }
  17634. } break;
  17635. case 0x0026 /* LeftMargin */:
  17636. case 0x0027 /* RightMargin */:
  17637. case 0x0028 /* TopMargin */:
  17638. case 0x0029 /* BottomMargin */:
  17639. if(!out['!margins']) default_margins(out['!margins'] = {});
  17640. out['!margins'][({0x26: "left", 0x27:"right", 0x28:"top", 0x29:"bottom"})[RecordType]] = val;
  17641. break;
  17642. case 0x00a1 /* Setup */: // TODO
  17643. if(!out['!margins']) default_margins(out['!margins'] = {});
  17644. out['!margins'].header = val.header;
  17645. out['!margins'].footer = val.footer;
  17646. break;
  17647. case 0x023e /* Window2 */: // TODO
  17648. // $FlowIgnore
  17649. if(val.RTL) Workbook.Views[0].RTL = true;
  17650. break;
  17651. case 0x0092 /* Palette */: palette = val; break;
  17652. case 0x0896 /* Theme */: themes = val; break;
  17653. case 0x008c /* Country */: country = val; break;
  17654. case 0x01ba /* CodeName */: {
  17655. if(!cur_sheet) Workbook.WBProps.CodeName = val || "ThisWorkbook";
  17656. else wsprops.CodeName = val || wsprops.name;
  17657. } break;
  17658. }
  17659. } else {
  17660. if(!R) console.error("Missing Info for XLS Record 0x" + RecordType.toString(16));
  17661. blob.l += length;
  17662. }
  17663. }
  17664. wb.SheetNames=keys(Directory).sort(function(a,b) { return Number(a) - Number(b); }).map(function(x){return Directory[x].name;});
  17665. if(!options.bookSheets) wb.Sheets=Sheets;
  17666. if(!wb.SheetNames.length && Preamble["!ref"]) {
  17667. wb.SheetNames.push("Sheet1");
  17668. /*jshint -W069 */
  17669. if(wb.Sheets) wb.Sheets["Sheet1"] = Preamble;
  17670. /*jshint +W069 */
  17671. } else wb.Preamble=Preamble;
  17672. if(wb.Sheets) FilterDatabases.forEach(function(r,i) { wb.Sheets[wb.SheetNames[i]]['!autofilter'] = r; });
  17673. wb.Strings = sst;
  17674. wb.SSF = dup(table_fmt);
  17675. if(opts.enc) wb.Encryption = opts.enc;
  17676. if(themes) wb.Themes = themes;
  17677. wb.Metadata = {};
  17678. if(country !== undefined) wb.Metadata.Country = country;
  17679. if(supbooks.names.length > 0) Workbook.Names = supbooks.names;
  17680. wb.Workbook = Workbook;
  17681. return wb;
  17682. }
  17683. /* TODO: split props*/
  17684. var PSCLSID = {
  17685. SI: "e0859ff2f94f6810ab9108002b27b3d9",
  17686. DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
  17687. UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
  17688. };
  17689. function parse_xls_props(cfb, props, o) {
  17690. /* [MS-OSHARED] 2.3.3.2.2 Document Summary Information Property Set */
  17691. var DSI = CFB.find(cfb, '/!DocumentSummaryInformation');
  17692. if(DSI && DSI.size > 0) try {
  17693. var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
  17694. for(var d in DocSummary) props[d] = DocSummary[d];
  17695. } catch(e) {if(o.WTF) throw e;/* empty */}
  17696. /* [MS-OSHARED] 2.3.3.2.1 Summary Information Property Set*/
  17697. var SI = CFB.find(cfb, '/!SummaryInformation');
  17698. if(SI && SI.size > 0) try {
  17699. var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
  17700. for(var s in Summary) if(props[s] == null) props[s] = Summary[s];
  17701. } catch(e) {if(o.WTF) throw e;/* empty */}
  17702. if(props.HeadingPairs && props.TitlesOfParts) {
  17703. load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o);
  17704. delete props.HeadingPairs; delete props.TitlesOfParts;
  17705. }
  17706. }
  17707. function write_xls_props(wb, cfb) {
  17708. var DSEntries = [], SEntries = [], CEntries = [];
  17709. var i = 0, Keys;
  17710. var DocSummaryRE = evert_key(DocSummaryPIDDSI, "n");
  17711. var SummaryRE = evert_key(SummaryPIDSI, "n");
  17712. if(wb.Props) {
  17713. Keys = keys(wb.Props);
  17714. // $FlowIgnore
  17715. 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]]]);
  17716. }
  17717. if(wb.Custprops) {
  17718. Keys = keys(wb.Custprops);
  17719. // $FlowIgnore
  17720. 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]]]);
  17721. }
  17722. var CEntries2 = [];
  17723. for(i = 0; i < CEntries.length; ++i) {
  17724. if(XLSPSSkip.indexOf(CEntries[i][0]) > -1 || PseudoPropsPairs.indexOf(CEntries[i][0]) > -1) continue;
  17725. if(CEntries[i][1] == null) continue;
  17726. CEntries2.push(CEntries[i]);
  17727. }
  17728. if(SEntries.length) CFB.utils.cfb_add(cfb, "/\u0005SummaryInformation", write_PropertySetStream(SEntries, PSCLSID.SI, SummaryRE, SummaryPIDSI));
  17729. if(DSEntries.length || CEntries2.length) CFB.utils.cfb_add(cfb, "/\u0005DocumentSummaryInformation", write_PropertySetStream(DSEntries, PSCLSID.DSI, DocSummaryRE, DocSummaryPIDDSI, CEntries2.length ? CEntries2 : null, PSCLSID.UDI));
  17730. }
  17731. function parse_xlscfb(cfb, options) {
  17732. if(!options) options = {};
  17733. fix_read_opts(options);
  17734. reset_cp();
  17735. if(options.codepage) set_ansi(options.codepage);
  17736. var CompObj, WB;
  17737. if(cfb.FullPaths) {
  17738. if(CFB.find(cfb, '/encryption')) throw new Error("File is password-protected");
  17739. CompObj = CFB.find(cfb, '!CompObj');
  17740. WB = CFB.find(cfb, '/Workbook') || CFB.find(cfb, '/Book');
  17741. } else {
  17742. switch(options.type) {
  17743. case 'base64': cfb = s2a(Base64_decode(cfb)); break;
  17744. case 'binary': cfb = s2a(cfb); break;
  17745. case 'buffer': break;
  17746. case 'array': if(!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb); break;
  17747. }
  17748. prep_blob(cfb, 0);
  17749. WB = ({content: cfb});
  17750. }
  17751. var WorkbookP;
  17752. var _data;
  17753. if(CompObj) parse_compobj(CompObj);
  17754. if(options.bookProps && !options.bookSheets) WorkbookP = ({});
  17755. else {
  17756. var T = has_buf ? 'buffer' : 'array';
  17757. if(WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
  17758. /* Quattro Pro 7-8 */
  17759. else if((_data=CFB.find(cfb, 'PerfectOffice_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  17760. /* Quattro Pro 9 */
  17761. else if((_data=CFB.find(cfb, 'NativeContent_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  17762. /* Works 4 for Mac */
  17763. else if((_data=CFB.find(cfb, 'MN0')) && _data.content) throw new Error("Unsupported Works 4 for Mac file");
  17764. else throw new Error("Cannot find Workbook stream");
  17765. if(options.bookVBA && cfb.FullPaths && CFB.find(cfb, '/_VBA_PROJECT_CUR/VBA/dir')) WorkbookP.vbaraw = make_vba_xls(cfb);
  17766. }
  17767. var props = {};
  17768. if(cfb.FullPaths) parse_xls_props(cfb, props, options);
  17769. WorkbookP.Props = WorkbookP.Custprops = props; /* TODO: split up properties */
  17770. if(options.bookFiles) WorkbookP.cfb = cfb;
  17771. /*WorkbookP.CompObjP = CompObjP; // TODO: storage? */
  17772. return WorkbookP;
  17773. }
  17774. function write_xlscfb(wb, opts) {
  17775. var o = opts || {};
  17776. var cfb = CFB.utils.cfb_new({root:"R"});
  17777. var wbpath = "/Workbook";
  17778. switch(o.bookType || "xls") {
  17779. case "xls": o.bookType = "biff8";
  17780. /* falls through */
  17781. case "xla": if(!o.bookType) o.bookType = "xla";
  17782. /* falls through */
  17783. case "biff8": wbpath = "/Workbook"; o.biff = 8; break;
  17784. case "biff5": wbpath = "/Book"; o.biff = 5; break;
  17785. default: throw new Error("invalid type " + o.bookType + " for XLS CFB");
  17786. }
  17787. CFB.utils.cfb_add(cfb, wbpath, write_biff_buf(wb, o));
  17788. if(o.biff == 8 && (wb.Props || wb.Custprops)) write_xls_props(wb, cfb);
  17789. // TODO: SI, DSI, CO
  17790. if(o.biff == 8 && wb.vbaraw) fill_vba_xls(cfb, CFB.read(wb.vbaraw, {type: typeof wb.vbaraw == "string" ? "binary" : "buffer"}));
  17791. return cfb;
  17792. }
  17793. /* [MS-XLSB] 2.3 Record Enumeration */
  17794. var XLSBRecordEnum = {
  17795. 0x0000: { /* n:"BrtRowHdr", */ f:parse_BrtRowHdr },
  17796. 0x0001: { /* n:"BrtCellBlank", */ f:parse_BrtCellBlank },
  17797. 0x0002: { /* n:"BrtCellRk", */ f:parse_BrtCellRk },
  17798. 0x0003: { /* n:"BrtCellError", */ f:parse_BrtCellError },
  17799. 0x0004: { /* n:"BrtCellBool", */ f:parse_BrtCellBool },
  17800. 0x0005: { /* n:"BrtCellReal", */ f:parse_BrtCellReal },
  17801. 0x0006: { /* n:"BrtCellSt", */ f:parse_BrtCellSt },
  17802. 0x0007: { /* n:"BrtCellIsst", */ f:parse_BrtCellIsst },
  17803. 0x0008: { /* n:"BrtFmlaString", */ f:parse_BrtFmlaString },
  17804. 0x0009: { /* n:"BrtFmlaNum", */ f:parse_BrtFmlaNum },
  17805. 0x000A: { /* n:"BrtFmlaBool", */ f:parse_BrtFmlaBool },
  17806. 0x000B: { /* n:"BrtFmlaError", */ f:parse_BrtFmlaError },
  17807. 0x000C: { /* n:"BrtShortBlank", */ f:parse_BrtShortBlank },
  17808. 0x000D: { /* n:"BrtShortRk", */ f:parse_BrtShortRk },
  17809. 0x000E: { /* n:"BrtShortError", */ f:parse_BrtShortError },
  17810. 0x000F: { /* n:"BrtShortBool", */ f:parse_BrtShortBool },
  17811. 0x0010: { /* n:"BrtShortReal", */ f:parse_BrtShortReal },
  17812. 0x0011: { /* n:"BrtShortSt", */ f:parse_BrtShortSt },
  17813. 0x0012: { /* n:"BrtShortIsst", */ f:parse_BrtShortIsst },
  17814. 0x0013: { /* n:"BrtSSTItem", */ f:parse_RichStr },
  17815. 0x0014: { /* n:"BrtPCDIMissing" */ },
  17816. 0x0015: { /* n:"BrtPCDINumber" */ },
  17817. 0x0016: { /* n:"BrtPCDIBoolean" */ },
  17818. 0x0017: { /* n:"BrtPCDIError" */ },
  17819. 0x0018: { /* n:"BrtPCDIString" */ },
  17820. 0x0019: { /* n:"BrtPCDIDatetime" */ },
  17821. 0x001A: { /* n:"BrtPCDIIndex" */ },
  17822. 0x001B: { /* n:"BrtPCDIAMissing" */ },
  17823. 0x001C: { /* n:"BrtPCDIANumber" */ },
  17824. 0x001D: { /* n:"BrtPCDIABoolean" */ },
  17825. 0x001E: { /* n:"BrtPCDIAError" */ },
  17826. 0x001F: { /* n:"BrtPCDIAString" */ },
  17827. 0x0020: { /* n:"BrtPCDIADatetime" */ },
  17828. 0x0021: { /* n:"BrtPCRRecord" */ },
  17829. 0x0022: { /* n:"BrtPCRRecordDt" */ },
  17830. 0x0023: { /* n:"BrtFRTBegin", */ T:1 },
  17831. 0x0024: { /* n:"BrtFRTEnd", */ T:-1 },
  17832. 0x0025: { /* n:"BrtACBegin", */ T:1 },
  17833. 0x0026: { /* n:"BrtACEnd", */ T:-1 },
  17834. 0x0027: { /* n:"BrtName", */ f:parse_BrtName },
  17835. 0x0028: { /* n:"BrtIndexRowBlock" */ },
  17836. 0x002A: { /* n:"BrtIndexBlock" */ },
  17837. 0x002B: { /* n:"BrtFont", */ f:parse_BrtFont },
  17838. 0x002C: { /* n:"BrtFmt", */ f:parse_BrtFmt },
  17839. 0x002D: { /* n:"BrtFill", */ f:parse_BrtFill },
  17840. 0x002E: { /* n:"BrtBorder", */ f:parse_BrtBorder },
  17841. 0x002F: { /* n:"BrtXF", */ f:parse_BrtXF },
  17842. 0x0030: { /* n:"BrtStyle" */ },
  17843. 0x0031: { /* n:"BrtCellMeta", */ f:parse_Int32LE },
  17844. 0x0032: { /* n:"BrtValueMeta" */ },
  17845. 0x0033: { /* n:"BrtMdb" */ f:parse_BrtMdb },
  17846. 0x0034: { /* n:"BrtBeginFmd", */ T:1 },
  17847. 0x0035: { /* n:"BrtEndFmd", */ T:-1 },
  17848. 0x0036: { /* n:"BrtBeginMdx", */ T:1 },
  17849. 0x0037: { /* n:"BrtEndMdx", */ T:-1 },
  17850. 0x0038: { /* n:"BrtBeginMdxTuple", */ T:1 },
  17851. 0x0039: { /* n:"BrtEndMdxTuple", */ T:-1 },
  17852. 0x003A: { /* n:"BrtMdxMbrIstr" */ },
  17853. 0x003B: { /* n:"BrtStr" */ },
  17854. 0x003C: { /* n:"BrtColInfo", */ f:parse_ColInfo },
  17855. 0x003E: { /* n:"BrtCellRString", */ f:parse_BrtCellRString },
  17856. 0x003F: { /* n:"BrtCalcChainItem$", */ f:parse_BrtCalcChainItem$ },
  17857. 0x0040: { /* n:"BrtDVal", */ f:parse_BrtDVal },
  17858. 0x0041: { /* n:"BrtSxvcellNum" */ },
  17859. 0x0042: { /* n:"BrtSxvcellStr" */ },
  17860. 0x0043: { /* n:"BrtSxvcellBool" */ },
  17861. 0x0044: { /* n:"BrtSxvcellErr" */ },
  17862. 0x0045: { /* n:"BrtSxvcellDate" */ },
  17863. 0x0046: { /* n:"BrtSxvcellNil" */ },
  17864. 0x0080: { /* n:"BrtFileVersion" */ },
  17865. 0x0081: { /* n:"BrtBeginSheet", */ T:1 },
  17866. 0x0082: { /* n:"BrtEndSheet", */ T:-1 },
  17867. 0x0083: { /* n:"BrtBeginBook", */ T:1, f:parsenoop, p:0 },
  17868. 0x0084: { /* n:"BrtEndBook", */ T:-1 },
  17869. 0x0085: { /* n:"BrtBeginWsViews", */ T:1 },
  17870. 0x0086: { /* n:"BrtEndWsViews", */ T:-1 },
  17871. 0x0087: { /* n:"BrtBeginBookViews", */ T:1 },
  17872. 0x0088: { /* n:"BrtEndBookViews", */ T:-1 },
  17873. 0x0089: { /* n:"BrtBeginWsView", */ T:1, f:parse_BrtBeginWsView },
  17874. 0x008A: { /* n:"BrtEndWsView", */ T:-1 },
  17875. 0x008B: { /* n:"BrtBeginCsViews", */ T:1 },
  17876. 0x008C: { /* n:"BrtEndCsViews", */ T:-1 },
  17877. 0x008D: { /* n:"BrtBeginCsView", */ T:1 },
  17878. 0x008E: { /* n:"BrtEndCsView", */ T:-1 },
  17879. 0x008F: { /* n:"BrtBeginBundleShs", */ T:1 },
  17880. 0x0090: { /* n:"BrtEndBundleShs", */ T:-1 },
  17881. 0x0091: { /* n:"BrtBeginSheetData", */ T:1 },
  17882. 0x0092: { /* n:"BrtEndSheetData", */ T:-1 },
  17883. 0x0093: { /* n:"BrtWsProp", */ f:parse_BrtWsProp },
  17884. 0x0094: { /* n:"BrtWsDim", */ f:parse_BrtWsDim, p:16 },
  17885. 0x0097: { /* n:"BrtPane", */ f:parse_BrtPane },
  17886. 0x0098: { /* n:"BrtSel" */ },
  17887. 0x0099: { /* n:"BrtWbProp", */ f:parse_BrtWbProp },
  17888. 0x009A: { /* n:"BrtWbFactoid" */ },
  17889. 0x009B: { /* n:"BrtFileRecover" */ },
  17890. 0x009C: { /* n:"BrtBundleSh", */ f:parse_BrtBundleSh },
  17891. 0x009D: { /* n:"BrtCalcProp" */ },
  17892. 0x009E: { /* n:"BrtBookView" */ },
  17893. 0x009F: { /* n:"BrtBeginSst", */ T:1, f:parse_BrtBeginSst },
  17894. 0x00A0: { /* n:"BrtEndSst", */ T:-1 },
  17895. 0x00A1: { /* n:"BrtBeginAFilter", */ T:1, f:parse_UncheckedRfX },
  17896. 0x00A2: { /* n:"BrtEndAFilter", */ T:-1 },
  17897. 0x00A3: { /* n:"BrtBeginFilterColumn", */ T:1 },
  17898. 0x00A4: { /* n:"BrtEndFilterColumn", */ T:-1 },
  17899. 0x00A5: { /* n:"BrtBeginFilters", */ T:1 },
  17900. 0x00A6: { /* n:"BrtEndFilters", */ T:-1 },
  17901. 0x00A7: { /* n:"BrtFilter" */ },
  17902. 0x00A8: { /* n:"BrtColorFilter" */ },
  17903. 0x00A9: { /* n:"BrtIconFilter" */ },
  17904. 0x00AA: { /* n:"BrtTop10Filter" */ },
  17905. 0x00AB: { /* n:"BrtDynamicFilter" */ },
  17906. 0x00AC: { /* n:"BrtBeginCustomFilters", */ T:1 },
  17907. 0x00AD: { /* n:"BrtEndCustomFilters", */ T:-1 },
  17908. 0x00AE: { /* n:"BrtCustomFilter" */ },
  17909. 0x00AF: { /* n:"BrtAFilterDateGroupItem" */ },
  17910. 0x00B0: { /* n:"BrtMergeCell", */ f:parse_BrtMergeCell },
  17911. 0x00B1: { /* n:"BrtBeginMergeCells", */ T:1 },
  17912. 0x00B2: { /* n:"BrtEndMergeCells", */ T:-1 },
  17913. 0x00B3: { /* n:"BrtBeginPivotCacheDef", */ T:1 },
  17914. 0x00B4: { /* n:"BrtEndPivotCacheDef", */ T:-1 },
  17915. 0x00B5: { /* n:"BrtBeginPCDFields", */ T:1 },
  17916. 0x00B6: { /* n:"BrtEndPCDFields", */ T:-1 },
  17917. 0x00B7: { /* n:"BrtBeginPCDField", */ T:1 },
  17918. 0x00B8: { /* n:"BrtEndPCDField", */ T:-1 },
  17919. 0x00B9: { /* n:"BrtBeginPCDSource", */ T:1 },
  17920. 0x00BA: { /* n:"BrtEndPCDSource", */ T:-1 },
  17921. 0x00BB: { /* n:"BrtBeginPCDSRange", */ T:1 },
  17922. 0x00BC: { /* n:"BrtEndPCDSRange", */ T:-1 },
  17923. 0x00BD: { /* n:"BrtBeginPCDFAtbl", */ T:1 },
  17924. 0x00BE: { /* n:"BrtEndPCDFAtbl", */ T:-1 },
  17925. 0x00BF: { /* n:"BrtBeginPCDIRun", */ T:1 },
  17926. 0x00C0: { /* n:"BrtEndPCDIRun", */ T:-1 },
  17927. 0x00C1: { /* n:"BrtBeginPivotCacheRecords", */ T:1 },
  17928. 0x00C2: { /* n:"BrtEndPivotCacheRecords", */ T:-1 },
  17929. 0x00C3: { /* n:"BrtBeginPCDHierarchies", */ T:1 },
  17930. 0x00C4: { /* n:"BrtEndPCDHierarchies", */ T:-1 },
  17931. 0x00C5: { /* n:"BrtBeginPCDHierarchy", */ T:1 },
  17932. 0x00C6: { /* n:"BrtEndPCDHierarchy", */ T:-1 },
  17933. 0x00C7: { /* n:"BrtBeginPCDHFieldsUsage", */ T:1 },
  17934. 0x00C8: { /* n:"BrtEndPCDHFieldsUsage", */ T:-1 },
  17935. 0x00C9: { /* n:"BrtBeginExtConnection", */ T:1 },
  17936. 0x00CA: { /* n:"BrtEndExtConnection", */ T:-1 },
  17937. 0x00CB: { /* n:"BrtBeginECDbProps", */ T:1 },
  17938. 0x00CC: { /* n:"BrtEndECDbProps", */ T:-1 },
  17939. 0x00CD: { /* n:"BrtBeginECOlapProps", */ T:1 },
  17940. 0x00CE: { /* n:"BrtEndECOlapProps", */ T:-1 },
  17941. 0x00CF: { /* n:"BrtBeginPCDSConsol", */ T:1 },
  17942. 0x00D0: { /* n:"BrtEndPCDSConsol", */ T:-1 },
  17943. 0x00D1: { /* n:"BrtBeginPCDSCPages", */ T:1 },
  17944. 0x00D2: { /* n:"BrtEndPCDSCPages", */ T:-1 },
  17945. 0x00D3: { /* n:"BrtBeginPCDSCPage", */ T:1 },
  17946. 0x00D4: { /* n:"BrtEndPCDSCPage", */ T:-1 },
  17947. 0x00D5: { /* n:"BrtBeginPCDSCPItem", */ T:1 },
  17948. 0x00D6: { /* n:"BrtEndPCDSCPItem", */ T:-1 },
  17949. 0x00D7: { /* n:"BrtBeginPCDSCSets", */ T:1 },
  17950. 0x00D8: { /* n:"BrtEndPCDSCSets", */ T:-1 },
  17951. 0x00D9: { /* n:"BrtBeginPCDSCSet", */ T:1 },
  17952. 0x00DA: { /* n:"BrtEndPCDSCSet", */ T:-1 },
  17953. 0x00DB: { /* n:"BrtBeginPCDFGroup", */ T:1 },
  17954. 0x00DC: { /* n:"BrtEndPCDFGroup", */ T:-1 },
  17955. 0x00DD: { /* n:"BrtBeginPCDFGItems", */ T:1 },
  17956. 0x00DE: { /* n:"BrtEndPCDFGItems", */ T:-1 },
  17957. 0x00DF: { /* n:"BrtBeginPCDFGRange", */ T:1 },
  17958. 0x00E0: { /* n:"BrtEndPCDFGRange", */ T:-1 },
  17959. 0x00E1: { /* n:"BrtBeginPCDFGDiscrete", */ T:1 },
  17960. 0x00E2: { /* n:"BrtEndPCDFGDiscrete", */ T:-1 },
  17961. 0x00E3: { /* n:"BrtBeginPCDSDTupleCache", */ T:1 },
  17962. 0x00E4: { /* n:"BrtEndPCDSDTupleCache", */ T:-1 },
  17963. 0x00E5: { /* n:"BrtBeginPCDSDTCEntries", */ T:1 },
  17964. 0x00E6: { /* n:"BrtEndPCDSDTCEntries", */ T:-1 },
  17965. 0x00E7: { /* n:"BrtBeginPCDSDTCEMembers", */ T:1 },
  17966. 0x00E8: { /* n:"BrtEndPCDSDTCEMembers", */ T:-1 },
  17967. 0x00E9: { /* n:"BrtBeginPCDSDTCEMember", */ T:1 },
  17968. 0x00EA: { /* n:"BrtEndPCDSDTCEMember", */ T:-1 },
  17969. 0x00EB: { /* n:"BrtBeginPCDSDTCQueries", */ T:1 },
  17970. 0x00EC: { /* n:"BrtEndPCDSDTCQueries", */ T:-1 },
  17971. 0x00ED: { /* n:"BrtBeginPCDSDTCQuery", */ T:1 },
  17972. 0x00EE: { /* n:"BrtEndPCDSDTCQuery", */ T:-1 },
  17973. 0x00EF: { /* n:"BrtBeginPCDSDTCSets", */ T:1 },
  17974. 0x00F0: { /* n:"BrtEndPCDSDTCSets", */ T:-1 },
  17975. 0x00F1: { /* n:"BrtBeginPCDSDTCSet", */ T:1 },
  17976. 0x00F2: { /* n:"BrtEndPCDSDTCSet", */ T:-1 },
  17977. 0x00F3: { /* n:"BrtBeginPCDCalcItems", */ T:1 },
  17978. 0x00F4: { /* n:"BrtEndPCDCalcItems", */ T:-1 },
  17979. 0x00F5: { /* n:"BrtBeginPCDCalcItem", */ T:1 },
  17980. 0x00F6: { /* n:"BrtEndPCDCalcItem", */ T:-1 },
  17981. 0x00F7: { /* n:"BrtBeginPRule", */ T:1 },
  17982. 0x00F8: { /* n:"BrtEndPRule", */ T:-1 },
  17983. 0x00F9: { /* n:"BrtBeginPRFilters", */ T:1 },
  17984. 0x00FA: { /* n:"BrtEndPRFilters", */ T:-1 },
  17985. 0x00FB: { /* n:"BrtBeginPRFilter", */ T:1 },
  17986. 0x00FC: { /* n:"BrtEndPRFilter", */ T:-1 },
  17987. 0x00FD: { /* n:"BrtBeginPNames", */ T:1 },
  17988. 0x00FE: { /* n:"BrtEndPNames", */ T:-1 },
  17989. 0x00FF: { /* n:"BrtBeginPName", */ T:1 },
  17990. 0x0100: { /* n:"BrtEndPName", */ T:-1 },
  17991. 0x0101: { /* n:"BrtBeginPNPairs", */ T:1 },
  17992. 0x0102: { /* n:"BrtEndPNPairs", */ T:-1 },
  17993. 0x0103: { /* n:"BrtBeginPNPair", */ T:1 },
  17994. 0x0104: { /* n:"BrtEndPNPair", */ T:-1 },
  17995. 0x0105: { /* n:"BrtBeginECWebProps", */ T:1 },
  17996. 0x0106: { /* n:"BrtEndECWebProps", */ T:-1 },
  17997. 0x0107: { /* n:"BrtBeginEcWpTables", */ T:1 },
  17998. 0x0108: { /* n:"BrtEndECWPTables", */ T:-1 },
  17999. 0x0109: { /* n:"BrtBeginECParams", */ T:1 },
  18000. 0x010A: { /* n:"BrtEndECParams", */ T:-1 },
  18001. 0x010B: { /* n:"BrtBeginECParam", */ T:1 },
  18002. 0x010C: { /* n:"BrtEndECParam", */ T:-1 },
  18003. 0x010D: { /* n:"BrtBeginPCDKPIs", */ T:1 },
  18004. 0x010E: { /* n:"BrtEndPCDKPIs", */ T:-1 },
  18005. 0x010F: { /* n:"BrtBeginPCDKPI", */ T:1 },
  18006. 0x0110: { /* n:"BrtEndPCDKPI", */ T:-1 },
  18007. 0x0111: { /* n:"BrtBeginDims", */ T:1 },
  18008. 0x0112: { /* n:"BrtEndDims", */ T:-1 },
  18009. 0x0113: { /* n:"BrtBeginDim", */ T:1 },
  18010. 0x0114: { /* n:"BrtEndDim", */ T:-1 },
  18011. 0x0115: { /* n:"BrtIndexPartEnd" */ },
  18012. 0x0116: { /* n:"BrtBeginStyleSheet", */ T:1 },
  18013. 0x0117: { /* n:"BrtEndStyleSheet", */ T:-1 },
  18014. 0x0118: { /* n:"BrtBeginSXView", */ T:1 },
  18015. 0x0119: { /* n:"BrtEndSXVI", */ T:-1 },
  18016. 0x011A: { /* n:"BrtBeginSXVI", */ T:1 },
  18017. 0x011B: { /* n:"BrtBeginSXVIs", */ T:1 },
  18018. 0x011C: { /* n:"BrtEndSXVIs", */ T:-1 },
  18019. 0x011D: { /* n:"BrtBeginSXVD", */ T:1 },
  18020. 0x011E: { /* n:"BrtEndSXVD", */ T:-1 },
  18021. 0x011F: { /* n:"BrtBeginSXVDs", */ T:1 },
  18022. 0x0120: { /* n:"BrtEndSXVDs", */ T:-1 },
  18023. 0x0121: { /* n:"BrtBeginSXPI", */ T:1 },
  18024. 0x0122: { /* n:"BrtEndSXPI", */ T:-1 },
  18025. 0x0123: { /* n:"BrtBeginSXPIs", */ T:1 },
  18026. 0x0124: { /* n:"BrtEndSXPIs", */ T:-1 },
  18027. 0x0125: { /* n:"BrtBeginSXDI", */ T:1 },
  18028. 0x0126: { /* n:"BrtEndSXDI", */ T:-1 },
  18029. 0x0127: { /* n:"BrtBeginSXDIs", */ T:1 },
  18030. 0x0128: { /* n:"BrtEndSXDIs", */ T:-1 },
  18031. 0x0129: { /* n:"BrtBeginSXLI", */ T:1 },
  18032. 0x012A: { /* n:"BrtEndSXLI", */ T:-1 },
  18033. 0x012B: { /* n:"BrtBeginSXLIRws", */ T:1 },
  18034. 0x012C: { /* n:"BrtEndSXLIRws", */ T:-1 },
  18035. 0x012D: { /* n:"BrtBeginSXLICols", */ T:1 },
  18036. 0x012E: { /* n:"BrtEndSXLICols", */ T:-1 },
  18037. 0x012F: { /* n:"BrtBeginSXFormat", */ T:1 },
  18038. 0x0130: { /* n:"BrtEndSXFormat", */ T:-1 },
  18039. 0x0131: { /* n:"BrtBeginSXFormats", */ T:1 },
  18040. 0x0132: { /* n:"BrtEndSxFormats", */ T:-1 },
  18041. 0x0133: { /* n:"BrtBeginSxSelect", */ T:1 },
  18042. 0x0134: { /* n:"BrtEndSxSelect", */ T:-1 },
  18043. 0x0135: { /* n:"BrtBeginISXVDRws", */ T:1 },
  18044. 0x0136: { /* n:"BrtEndISXVDRws", */ T:-1 },
  18045. 0x0137: { /* n:"BrtBeginISXVDCols", */ T:1 },
  18046. 0x0138: { /* n:"BrtEndISXVDCols", */ T:-1 },
  18047. 0x0139: { /* n:"BrtEndSXLocation", */ T:-1 },
  18048. 0x013A: { /* n:"BrtBeginSXLocation", */ T:1 },
  18049. 0x013B: { /* n:"BrtEndSXView", */ T:-1 },
  18050. 0x013C: { /* n:"BrtBeginSXTHs", */ T:1 },
  18051. 0x013D: { /* n:"BrtEndSXTHs", */ T:-1 },
  18052. 0x013E: { /* n:"BrtBeginSXTH", */ T:1 },
  18053. 0x013F: { /* n:"BrtEndSXTH", */ T:-1 },
  18054. 0x0140: { /* n:"BrtBeginISXTHRws", */ T:1 },
  18055. 0x0141: { /* n:"BrtEndISXTHRws", */ T:-1 },
  18056. 0x0142: { /* n:"BrtBeginISXTHCols", */ T:1 },
  18057. 0x0143: { /* n:"BrtEndISXTHCols", */ T:-1 },
  18058. 0x0144: { /* n:"BrtBeginSXTDMPS", */ T:1 },
  18059. 0x0145: { /* n:"BrtEndSXTDMPs", */ T:-1 },
  18060. 0x0146: { /* n:"BrtBeginSXTDMP", */ T:1 },
  18061. 0x0147: { /* n:"BrtEndSXTDMP", */ T:-1 },
  18062. 0x0148: { /* n:"BrtBeginSXTHItems", */ T:1 },
  18063. 0x0149: { /* n:"BrtEndSXTHItems", */ T:-1 },
  18064. 0x014A: { /* n:"BrtBeginSXTHItem", */ T:1 },
  18065. 0x014B: { /* n:"BrtEndSXTHItem", */ T:-1 },
  18066. 0x014C: { /* n:"BrtBeginMetadata", */ T:1 },
  18067. 0x014D: { /* n:"BrtEndMetadata", */ T:-1 },
  18068. 0x014E: { /* n:"BrtBeginEsmdtinfo", */ T:1 },
  18069. 0x014F: { /* n:"BrtMdtinfo", */ f:parse_BrtMdtinfo },
  18070. 0x0150: { /* n:"BrtEndEsmdtinfo", */ T:-1 },
  18071. 0x0151: { /* n:"BrtBeginEsmdb", */ f:parse_BrtBeginEsmdb, T:1 },
  18072. 0x0152: { /* n:"BrtEndEsmdb", */ T:-1 },
  18073. 0x0153: { /* n:"BrtBeginEsfmd", */ T:1 },
  18074. 0x0154: { /* n:"BrtEndEsfmd", */ T:-1 },
  18075. 0x0155: { /* n:"BrtBeginSingleCells", */ T:1 },
  18076. 0x0156: { /* n:"BrtEndSingleCells", */ T:-1 },
  18077. 0x0157: { /* n:"BrtBeginList", */ T:1 },
  18078. 0x0158: { /* n:"BrtEndList", */ T:-1 },
  18079. 0x0159: { /* n:"BrtBeginListCols", */ T:1 },
  18080. 0x015A: { /* n:"BrtEndListCols", */ T:-1 },
  18081. 0x015B: { /* n:"BrtBeginListCol", */ T:1 },
  18082. 0x015C: { /* n:"BrtEndListCol", */ T:-1 },
  18083. 0x015D: { /* n:"BrtBeginListXmlCPr", */ T:1 },
  18084. 0x015E: { /* n:"BrtEndListXmlCPr", */ T:-1 },
  18085. 0x015F: { /* n:"BrtListCCFmla" */ },
  18086. 0x0160: { /* n:"BrtListTrFmla" */ },
  18087. 0x0161: { /* n:"BrtBeginExternals", */ T:1 },
  18088. 0x0162: { /* n:"BrtEndExternals", */ T:-1 },
  18089. 0x0163: { /* n:"BrtSupBookSrc", */ f:parse_RelID},
  18090. 0x0165: { /* n:"BrtSupSelf" */ },
  18091. 0x0166: { /* n:"BrtSupSame" */ },
  18092. 0x0167: { /* n:"BrtSupTabs" */ },
  18093. 0x0168: { /* n:"BrtBeginSupBook", */ T:1 },
  18094. 0x0169: { /* n:"BrtPlaceholderName" */ },
  18095. 0x016A: { /* n:"BrtExternSheet", */ f:parse_ExternSheet },
  18096. 0x016B: { /* n:"BrtExternTableStart" */ },
  18097. 0x016C: { /* n:"BrtExternTableEnd" */ },
  18098. 0x016E: { /* n:"BrtExternRowHdr" */ },
  18099. 0x016F: { /* n:"BrtExternCellBlank" */ },
  18100. 0x0170: { /* n:"BrtExternCellReal" */ },
  18101. 0x0171: { /* n:"BrtExternCellBool" */ },
  18102. 0x0172: { /* n:"BrtExternCellError" */ },
  18103. 0x0173: { /* n:"BrtExternCellString" */ },
  18104. 0x0174: { /* n:"BrtBeginEsmdx", */ T:1 },
  18105. 0x0175: { /* n:"BrtEndEsmdx", */ T:-1 },
  18106. 0x0176: { /* n:"BrtBeginMdxSet", */ T:1 },
  18107. 0x0177: { /* n:"BrtEndMdxSet", */ T:-1 },
  18108. 0x0178: { /* n:"BrtBeginMdxMbrProp", */ T:1 },
  18109. 0x0179: { /* n:"BrtEndMdxMbrProp", */ T:-1 },
  18110. 0x017A: { /* n:"BrtBeginMdxKPI", */ T:1 },
  18111. 0x017B: { /* n:"BrtEndMdxKPI", */ T:-1 },
  18112. 0x017C: { /* n:"BrtBeginEsstr", */ T:1 },
  18113. 0x017D: { /* n:"BrtEndEsstr", */ T:-1 },
  18114. 0x017E: { /* n:"BrtBeginPRFItem", */ T:1 },
  18115. 0x017F: { /* n:"BrtEndPRFItem", */ T:-1 },
  18116. 0x0180: { /* n:"BrtBeginPivotCacheIDs", */ T:1 },
  18117. 0x0181: { /* n:"BrtEndPivotCacheIDs", */ T:-1 },
  18118. 0x0182: { /* n:"BrtBeginPivotCacheID", */ T:1 },
  18119. 0x0183: { /* n:"BrtEndPivotCacheID", */ T:-1 },
  18120. 0x0184: { /* n:"BrtBeginISXVIs", */ T:1 },
  18121. 0x0185: { /* n:"BrtEndISXVIs", */ T:-1 },
  18122. 0x0186: { /* n:"BrtBeginColInfos", */ T:1 },
  18123. 0x0187: { /* n:"BrtEndColInfos", */ T:-1 },
  18124. 0x0188: { /* n:"BrtBeginRwBrk", */ T:1 },
  18125. 0x0189: { /* n:"BrtEndRwBrk", */ T:-1 },
  18126. 0x018A: { /* n:"BrtBeginColBrk", */ T:1 },
  18127. 0x018B: { /* n:"BrtEndColBrk", */ T:-1 },
  18128. 0x018C: { /* n:"BrtBrk" */ },
  18129. 0x018D: { /* n:"BrtUserBookView" */ },
  18130. 0x018E: { /* n:"BrtInfo" */ },
  18131. 0x018F: { /* n:"BrtCUsr" */ },
  18132. 0x0190: { /* n:"BrtUsr" */ },
  18133. 0x0191: { /* n:"BrtBeginUsers", */ T:1 },
  18134. 0x0193: { /* n:"BrtEOF" */ },
  18135. 0x0194: { /* n:"BrtUCR" */ },
  18136. 0x0195: { /* n:"BrtRRInsDel" */ },
  18137. 0x0196: { /* n:"BrtRREndInsDel" */ },
  18138. 0x0197: { /* n:"BrtRRMove" */ },
  18139. 0x0198: { /* n:"BrtRREndMove" */ },
  18140. 0x0199: { /* n:"BrtRRChgCell" */ },
  18141. 0x019A: { /* n:"BrtRREndChgCell" */ },
  18142. 0x019B: { /* n:"BrtRRHeader" */ },
  18143. 0x019C: { /* n:"BrtRRUserView" */ },
  18144. 0x019D: { /* n:"BrtRRRenSheet" */ },
  18145. 0x019E: { /* n:"BrtRRInsertSh" */ },
  18146. 0x019F: { /* n:"BrtRRDefName" */ },
  18147. 0x01A0: { /* n:"BrtRRNote" */ },
  18148. 0x01A1: { /* n:"BrtRRConflict" */ },
  18149. 0x01A2: { /* n:"BrtRRTQSIF" */ },
  18150. 0x01A3: { /* n:"BrtRRFormat" */ },
  18151. 0x01A4: { /* n:"BrtRREndFormat" */ },
  18152. 0x01A5: { /* n:"BrtRRAutoFmt" */ },
  18153. 0x01A6: { /* n:"BrtBeginUserShViews", */ T:1 },
  18154. 0x01A7: { /* n:"BrtBeginUserShView", */ T:1 },
  18155. 0x01A8: { /* n:"BrtEndUserShView", */ T:-1 },
  18156. 0x01A9: { /* n:"BrtEndUserShViews", */ T:-1 },
  18157. 0x01AA: { /* n:"BrtArrFmla", */ f:parse_BrtArrFmla },
  18158. 0x01AB: { /* n:"BrtShrFmla", */ f:parse_BrtShrFmla },
  18159. 0x01AC: { /* n:"BrtTable" */ },
  18160. 0x01AD: { /* n:"BrtBeginExtConnections", */ T:1 },
  18161. 0x01AE: { /* n:"BrtEndExtConnections", */ T:-1 },
  18162. 0x01AF: { /* n:"BrtBeginPCDCalcMems", */ T:1 },
  18163. 0x01B0: { /* n:"BrtEndPCDCalcMems", */ T:-1 },
  18164. 0x01B1: { /* n:"BrtBeginPCDCalcMem", */ T:1 },
  18165. 0x01B2: { /* n:"BrtEndPCDCalcMem", */ T:-1 },
  18166. 0x01B3: { /* n:"BrtBeginPCDHGLevels", */ T:1 },
  18167. 0x01B4: { /* n:"BrtEndPCDHGLevels", */ T:-1 },
  18168. 0x01B5: { /* n:"BrtBeginPCDHGLevel", */ T:1 },
  18169. 0x01B6: { /* n:"BrtEndPCDHGLevel", */ T:-1 },
  18170. 0x01B7: { /* n:"BrtBeginPCDHGLGroups", */ T:1 },
  18171. 0x01B8: { /* n:"BrtEndPCDHGLGroups", */ T:-1 },
  18172. 0x01B9: { /* n:"BrtBeginPCDHGLGroup", */ T:1 },
  18173. 0x01BA: { /* n:"BrtEndPCDHGLGroup", */ T:-1 },
  18174. 0x01BB: { /* n:"BrtBeginPCDHGLGMembers", */ T:1 },
  18175. 0x01BC: { /* n:"BrtEndPCDHGLGMembers", */ T:-1 },
  18176. 0x01BD: { /* n:"BrtBeginPCDHGLGMember", */ T:1 },
  18177. 0x01BE: { /* n:"BrtEndPCDHGLGMember", */ T:-1 },
  18178. 0x01BF: { /* n:"BrtBeginQSI", */ T:1 },
  18179. 0x01C0: { /* n:"BrtEndQSI", */ T:-1 },
  18180. 0x01C1: { /* n:"BrtBeginQSIR", */ T:1 },
  18181. 0x01C2: { /* n:"BrtEndQSIR", */ T:-1 },
  18182. 0x01C3: { /* n:"BrtBeginDeletedNames", */ T:1 },
  18183. 0x01C4: { /* n:"BrtEndDeletedNames", */ T:-1 },
  18184. 0x01C5: { /* n:"BrtBeginDeletedName", */ T:1 },
  18185. 0x01C6: { /* n:"BrtEndDeletedName", */ T:-1 },
  18186. 0x01C7: { /* n:"BrtBeginQSIFs", */ T:1 },
  18187. 0x01C8: { /* n:"BrtEndQSIFs", */ T:-1 },
  18188. 0x01C9: { /* n:"BrtBeginQSIF", */ T:1 },
  18189. 0x01CA: { /* n:"BrtEndQSIF", */ T:-1 },
  18190. 0x01CB: { /* n:"BrtBeginAutoSortScope", */ T:1 },
  18191. 0x01CC: { /* n:"BrtEndAutoSortScope", */ T:-1 },
  18192. 0x01CD: { /* n:"BrtBeginConditionalFormatting", */ T:1 },
  18193. 0x01CE: { /* n:"BrtEndConditionalFormatting", */ T:-1 },
  18194. 0x01CF: { /* n:"BrtBeginCFRule", */ T:1 },
  18195. 0x01D0: { /* n:"BrtEndCFRule", */ T:-1 },
  18196. 0x01D1: { /* n:"BrtBeginIconSet", */ T:1 },
  18197. 0x01D2: { /* n:"BrtEndIconSet", */ T:-1 },
  18198. 0x01D3: { /* n:"BrtBeginDatabar", */ T:1 },
  18199. 0x01D4: { /* n:"BrtEndDatabar", */ T:-1 },
  18200. 0x01D5: { /* n:"BrtBeginColorScale", */ T:1 },
  18201. 0x01D6: { /* n:"BrtEndColorScale", */ T:-1 },
  18202. 0x01D7: { /* n:"BrtCFVO" */ },
  18203. 0x01D8: { /* n:"BrtExternValueMeta" */ },
  18204. 0x01D9: { /* n:"BrtBeginColorPalette", */ T:1 },
  18205. 0x01DA: { /* n:"BrtEndColorPalette", */ T:-1 },
  18206. 0x01DB: { /* n:"BrtIndexedColor" */ },
  18207. 0x01DC: { /* n:"BrtMargins", */ f:parse_BrtMargins },
  18208. 0x01DD: { /* n:"BrtPrintOptions" */ },
  18209. 0x01DE: { /* n:"BrtPageSetup" */ },
  18210. 0x01DF: { /* n:"BrtBeginHeaderFooter", */ T:1 },
  18211. 0x01E0: { /* n:"BrtEndHeaderFooter", */ T:-1 },
  18212. 0x01E1: { /* n:"BrtBeginSXCrtFormat", */ T:1 },
  18213. 0x01E2: { /* n:"BrtEndSXCrtFormat", */ T:-1 },
  18214. 0x01E3: { /* n:"BrtBeginSXCrtFormats", */ T:1 },
  18215. 0x01E4: { /* n:"BrtEndSXCrtFormats", */ T:-1 },
  18216. 0x01E5: { /* n:"BrtWsFmtInfo", */ f:parse_BrtWsFmtInfo },
  18217. 0x01E6: { /* n:"BrtBeginMgs", */ T:1 },
  18218. 0x01E7: { /* n:"BrtEndMGs", */ T:-1 },
  18219. 0x01E8: { /* n:"BrtBeginMGMaps", */ T:1 },
  18220. 0x01E9: { /* n:"BrtEndMGMaps", */ T:-1 },
  18221. 0x01EA: { /* n:"BrtBeginMG", */ T:1 },
  18222. 0x01EB: { /* n:"BrtEndMG", */ T:-1 },
  18223. 0x01EC: { /* n:"BrtBeginMap", */ T:1 },
  18224. 0x01ED: { /* n:"BrtEndMap", */ T:-1 },
  18225. 0x01EE: { /* n:"BrtHLink", */ f:parse_BrtHLink },
  18226. 0x01EF: { /* n:"BrtBeginDCon", */ T:1 },
  18227. 0x01F0: { /* n:"BrtEndDCon", */ T:-1 },
  18228. 0x01F1: { /* n:"BrtBeginDRefs", */ T:1 },
  18229. 0x01F2: { /* n:"BrtEndDRefs", */ T:-1 },
  18230. 0x01F3: { /* n:"BrtDRef" */ },
  18231. 0x01F4: { /* n:"BrtBeginScenMan", */ T:1 },
  18232. 0x01F5: { /* n:"BrtEndScenMan", */ T:-1 },
  18233. 0x01F6: { /* n:"BrtBeginSct", */ T:1 },
  18234. 0x01F7: { /* n:"BrtEndSct", */ T:-1 },
  18235. 0x01F8: { /* n:"BrtSlc" */ },
  18236. 0x01F9: { /* n:"BrtBeginDXFs", */ T:1 },
  18237. 0x01FA: { /* n:"BrtEndDXFs", */ T:-1 },
  18238. 0x01FB: { /* n:"BrtDXF" */ },
  18239. 0x01FC: { /* n:"BrtBeginTableStyles", */ T:1 },
  18240. 0x01FD: { /* n:"BrtEndTableStyles", */ T:-1 },
  18241. 0x01FE: { /* n:"BrtBeginTableStyle", */ T:1 },
  18242. 0x01FF: { /* n:"BrtEndTableStyle", */ T:-1 },
  18243. 0x0200: { /* n:"BrtTableStyleElement" */ },
  18244. 0x0201: { /* n:"BrtTableStyleClient" */ },
  18245. 0x0202: { /* n:"BrtBeginVolDeps", */ T:1 },
  18246. 0x0203: { /* n:"BrtEndVolDeps", */ T:-1 },
  18247. 0x0204: { /* n:"BrtBeginVolType", */ T:1 },
  18248. 0x0205: { /* n:"BrtEndVolType", */ T:-1 },
  18249. 0x0206: { /* n:"BrtBeginVolMain", */ T:1 },
  18250. 0x0207: { /* n:"BrtEndVolMain", */ T:-1 },
  18251. 0x0208: { /* n:"BrtBeginVolTopic", */ T:1 },
  18252. 0x0209: { /* n:"BrtEndVolTopic", */ T:-1 },
  18253. 0x020A: { /* n:"BrtVolSubtopic" */ },
  18254. 0x020B: { /* n:"BrtVolRef" */ },
  18255. 0x020C: { /* n:"BrtVolNum" */ },
  18256. 0x020D: { /* n:"BrtVolErr" */ },
  18257. 0x020E: { /* n:"BrtVolStr" */ },
  18258. 0x020F: { /* n:"BrtVolBool" */ },
  18259. 0x0210: { /* n:"BrtBeginCalcChain$", */ T:1 },
  18260. 0x0211: { /* n:"BrtEndCalcChain$", */ T:-1 },
  18261. 0x0212: { /* n:"BrtBeginSortState", */ T:1 },
  18262. 0x0213: { /* n:"BrtEndSortState", */ T:-1 },
  18263. 0x0214: { /* n:"BrtBeginSortCond", */ T:1 },
  18264. 0x0215: { /* n:"BrtEndSortCond", */ T:-1 },
  18265. 0x0216: { /* n:"BrtBookProtection" */ },
  18266. 0x0217: { /* n:"BrtSheetProtection" */ },
  18267. 0x0218: { /* n:"BrtRangeProtection" */ },
  18268. 0x0219: { /* n:"BrtPhoneticInfo" */ },
  18269. 0x021A: { /* n:"BrtBeginECTxtWiz", */ T:1 },
  18270. 0x021B: { /* n:"BrtEndECTxtWiz", */ T:-1 },
  18271. 0x021C: { /* n:"BrtBeginECTWFldInfoLst", */ T:1 },
  18272. 0x021D: { /* n:"BrtEndECTWFldInfoLst", */ T:-1 },
  18273. 0x021E: { /* n:"BrtBeginECTwFldInfo", */ T:1 },
  18274. 0x0224: { /* n:"BrtFileSharing" */ },
  18275. 0x0225: { /* n:"BrtOleSize" */ },
  18276. 0x0226: { /* n:"BrtDrawing", */ f:parse_RelID },
  18277. 0x0227: { /* n:"BrtLegacyDrawing" */ },
  18278. 0x0228: { /* n:"BrtLegacyDrawingHF" */ },
  18279. 0x0229: { /* n:"BrtWebOpt" */ },
  18280. 0x022A: { /* n:"BrtBeginWebPubItems", */ T:1 },
  18281. 0x022B: { /* n:"BrtEndWebPubItems", */ T:-1 },
  18282. 0x022C: { /* n:"BrtBeginWebPubItem", */ T:1 },
  18283. 0x022D: { /* n:"BrtEndWebPubItem", */ T:-1 },
  18284. 0x022E: { /* n:"BrtBeginSXCondFmt", */ T:1 },
  18285. 0x022F: { /* n:"BrtEndSXCondFmt", */ T:-1 },
  18286. 0x0230: { /* n:"BrtBeginSXCondFmts", */ T:1 },
  18287. 0x0231: { /* n:"BrtEndSXCondFmts", */ T:-1 },
  18288. 0x0232: { /* n:"BrtBkHim" */ },
  18289. 0x0234: { /* n:"BrtColor" */ },
  18290. 0x0235: { /* n:"BrtBeginIndexedColors", */ T:1 },
  18291. 0x0236: { /* n:"BrtEndIndexedColors", */ T:-1 },
  18292. 0x0239: { /* n:"BrtBeginMRUColors", */ T:1 },
  18293. 0x023A: { /* n:"BrtEndMRUColors", */ T:-1 },
  18294. 0x023C: { /* n:"BrtMRUColor" */ },
  18295. 0x023D: { /* n:"BrtBeginDVals", */ T:1 },
  18296. 0x023E: { /* n:"BrtEndDVals", */ T:-1 },
  18297. 0x0241: { /* n:"BrtSupNameStart" */ },
  18298. 0x0242: { /* n:"BrtSupNameValueStart" */ },
  18299. 0x0243: { /* n:"BrtSupNameValueEnd" */ },
  18300. 0x0244: { /* n:"BrtSupNameNum" */ },
  18301. 0x0245: { /* n:"BrtSupNameErr" */ },
  18302. 0x0246: { /* n:"BrtSupNameSt" */ },
  18303. 0x0247: { /* n:"BrtSupNameNil" */ },
  18304. 0x0248: { /* n:"BrtSupNameBool" */ },
  18305. 0x0249: { /* n:"BrtSupNameFmla" */ },
  18306. 0x024A: { /* n:"BrtSupNameBits" */ },
  18307. 0x024B: { /* n:"BrtSupNameEnd" */ },
  18308. 0x024C: { /* n:"BrtEndSupBook", */ T:-1 },
  18309. 0x024D: { /* n:"BrtCellSmartTagProperty" */ },
  18310. 0x024E: { /* n:"BrtBeginCellSmartTag", */ T:1 },
  18311. 0x024F: { /* n:"BrtEndCellSmartTag", */ T:-1 },
  18312. 0x0250: { /* n:"BrtBeginCellSmartTags", */ T:1 },
  18313. 0x0251: { /* n:"BrtEndCellSmartTags", */ T:-1 },
  18314. 0x0252: { /* n:"BrtBeginSmartTags", */ T:1 },
  18315. 0x0253: { /* n:"BrtEndSmartTags", */ T:-1 },
  18316. 0x0254: { /* n:"BrtSmartTagType" */ },
  18317. 0x0255: { /* n:"BrtBeginSmartTagTypes", */ T:1 },
  18318. 0x0256: { /* n:"BrtEndSmartTagTypes", */ T:-1 },
  18319. 0x0257: { /* n:"BrtBeginSXFilters", */ T:1 },
  18320. 0x0258: { /* n:"BrtEndSXFilters", */ T:-1 },
  18321. 0x0259: { /* n:"BrtBeginSXFILTER", */ T:1 },
  18322. 0x025A: { /* n:"BrtEndSXFilter", */ T:-1 },
  18323. 0x025B: { /* n:"BrtBeginFills", */ T:1 },
  18324. 0x025C: { /* n:"BrtEndFills", */ T:-1 },
  18325. 0x025D: { /* n:"BrtBeginCellWatches", */ T:1 },
  18326. 0x025E: { /* n:"BrtEndCellWatches", */ T:-1 },
  18327. 0x025F: { /* n:"BrtCellWatch" */ },
  18328. 0x0260: { /* n:"BrtBeginCRErrs", */ T:1 },
  18329. 0x0261: { /* n:"BrtEndCRErrs", */ T:-1 },
  18330. 0x0262: { /* n:"BrtCrashRecErr" */ },
  18331. 0x0263: { /* n:"BrtBeginFonts", */ T:1 },
  18332. 0x0264: { /* n:"BrtEndFonts", */ T:-1 },
  18333. 0x0265: { /* n:"BrtBeginBorders", */ T:1 },
  18334. 0x0266: { /* n:"BrtEndBorders", */ T:-1 },
  18335. 0x0267: { /* n:"BrtBeginFmts", */ T:1 },
  18336. 0x0268: { /* n:"BrtEndFmts", */ T:-1 },
  18337. 0x0269: { /* n:"BrtBeginCellXFs", */ T:1 },
  18338. 0x026A: { /* n:"BrtEndCellXFs", */ T:-1 },
  18339. 0x026B: { /* n:"BrtBeginStyles", */ T:1 },
  18340. 0x026C: { /* n:"BrtEndStyles", */ T:-1 },
  18341. 0x0271: { /* n:"BrtBigName" */ },
  18342. 0x0272: { /* n:"BrtBeginCellStyleXFs", */ T:1 },
  18343. 0x0273: { /* n:"BrtEndCellStyleXFs", */ T:-1 },
  18344. 0x0274: { /* n:"BrtBeginComments", */ T:1 },
  18345. 0x0275: { /* n:"BrtEndComments", */ T:-1 },
  18346. 0x0276: { /* n:"BrtBeginCommentAuthors", */ T:1 },
  18347. 0x0277: { /* n:"BrtEndCommentAuthors", */ T:-1 },
  18348. 0x0278: { /* n:"BrtCommentAuthor", */ f:parse_BrtCommentAuthor },
  18349. 0x0279: { /* n:"BrtBeginCommentList", */ T:1 },
  18350. 0x027A: { /* n:"BrtEndCommentList", */ T:-1 },
  18351. 0x027B: { /* n:"BrtBeginComment", */ T:1, f:parse_BrtBeginComment},
  18352. 0x027C: { /* n:"BrtEndComment", */ T:-1 },
  18353. 0x027D: { /* n:"BrtCommentText", */ f:parse_BrtCommentText },
  18354. 0x027E: { /* n:"BrtBeginOleObjects", */ T:1 },
  18355. 0x027F: { /* n:"BrtOleObject" */ },
  18356. 0x0280: { /* n:"BrtEndOleObjects", */ T:-1 },
  18357. 0x0281: { /* n:"BrtBeginSxrules", */ T:1 },
  18358. 0x0282: { /* n:"BrtEndSxRules", */ T:-1 },
  18359. 0x0283: { /* n:"BrtBeginActiveXControls", */ T:1 },
  18360. 0x0284: { /* n:"BrtActiveX" */ },
  18361. 0x0285: { /* n:"BrtEndActiveXControls", */ T:-1 },
  18362. 0x0286: { /* n:"BrtBeginPCDSDTCEMembersSortBy", */ T:1 },
  18363. 0x0288: { /* n:"BrtBeginCellIgnoreECs", */ T:1 },
  18364. 0x0289: { /* n:"BrtCellIgnoreEC" */ },
  18365. 0x028A: { /* n:"BrtEndCellIgnoreECs", */ T:-1 },
  18366. 0x028B: { /* n:"BrtCsProp", */ f:parse_BrtCsProp },
  18367. 0x028C: { /* n:"BrtCsPageSetup" */ },
  18368. 0x028D: { /* n:"BrtBeginUserCsViews", */ T:1 },
  18369. 0x028E: { /* n:"BrtEndUserCsViews", */ T:-1 },
  18370. 0x028F: { /* n:"BrtBeginUserCsView", */ T:1 },
  18371. 0x0290: { /* n:"BrtEndUserCsView", */ T:-1 },
  18372. 0x0291: { /* n:"BrtBeginPcdSFCIEntries", */ T:1 },
  18373. 0x0292: { /* n:"BrtEndPCDSFCIEntries", */ T:-1 },
  18374. 0x0293: { /* n:"BrtPCDSFCIEntry" */ },
  18375. 0x0294: { /* n:"BrtBeginListParts", */ T:1 },
  18376. 0x0295: { /* n:"BrtListPart" */ },
  18377. 0x0296: { /* n:"BrtEndListParts", */ T:-1 },
  18378. 0x0297: { /* n:"BrtSheetCalcProp" */ },
  18379. 0x0298: { /* n:"BrtBeginFnGroup", */ T:1 },
  18380. 0x0299: { /* n:"BrtFnGroup" */ },
  18381. 0x029A: { /* n:"BrtEndFnGroup", */ T:-1 },
  18382. 0x029B: { /* n:"BrtSupAddin" */ },
  18383. 0x029C: { /* n:"BrtSXTDMPOrder" */ },
  18384. 0x029D: { /* n:"BrtCsProtection" */ },
  18385. 0x029F: { /* n:"BrtBeginWsSortMap", */ T:1 },
  18386. 0x02A0: { /* n:"BrtEndWsSortMap", */ T:-1 },
  18387. 0x02A1: { /* n:"BrtBeginRRSort", */ T:1 },
  18388. 0x02A2: { /* n:"BrtEndRRSort", */ T:-1 },
  18389. 0x02A3: { /* n:"BrtRRSortItem" */ },
  18390. 0x02A4: { /* n:"BrtFileSharingIso" */ },
  18391. 0x02A5: { /* n:"BrtBookProtectionIso" */ },
  18392. 0x02A6: { /* n:"BrtSheetProtectionIso" */ },
  18393. 0x02A7: { /* n:"BrtCsProtectionIso" */ },
  18394. 0x02A8: { /* n:"BrtRangeProtectionIso" */ },
  18395. 0x02A9: { /* n:"BrtDValList" */ },
  18396. 0x0400: { /* n:"BrtRwDescent" */ },
  18397. 0x0401: { /* n:"BrtKnownFonts" */ },
  18398. 0x0402: { /* n:"BrtBeginSXTupleSet", */ T:1 },
  18399. 0x0403: { /* n:"BrtEndSXTupleSet", */ T:-1 },
  18400. 0x0404: { /* n:"BrtBeginSXTupleSetHeader", */ T:1 },
  18401. 0x0405: { /* n:"BrtEndSXTupleSetHeader", */ T:-1 },
  18402. 0x0406: { /* n:"BrtSXTupleSetHeaderItem" */ },
  18403. 0x0407: { /* n:"BrtBeginSXTupleSetData", */ T:1 },
  18404. 0x0408: { /* n:"BrtEndSXTupleSetData", */ T:-1 },
  18405. 0x0409: { /* n:"BrtBeginSXTupleSetRow", */ T:1 },
  18406. 0x040A: { /* n:"BrtEndSXTupleSetRow", */ T:-1 },
  18407. 0x040B: { /* n:"BrtSXTupleSetRowItem" */ },
  18408. 0x040C: { /* n:"BrtNameExt" */ },
  18409. 0x040D: { /* n:"BrtPCDH14" */ },
  18410. 0x040E: { /* n:"BrtBeginPCDCalcMem14", */ T:1 },
  18411. 0x040F: { /* n:"BrtEndPCDCalcMem14", */ T:-1 },
  18412. 0x0410: { /* n:"BrtSXTH14" */ },
  18413. 0x0411: { /* n:"BrtBeginSparklineGroup", */ T:1 },
  18414. 0x0412: { /* n:"BrtEndSparklineGroup", */ T:-1 },
  18415. 0x0413: { /* n:"BrtSparkline" */ },
  18416. 0x0414: { /* n:"BrtSXDI14" */ },
  18417. 0x0415: { /* n:"BrtWsFmtInfoEx14" */ },
  18418. 0x0416: { /* n:"BrtBeginConditionalFormatting14", */ T:1 },
  18419. 0x0417: { /* n:"BrtEndConditionalFormatting14", */ T:-1 },
  18420. 0x0418: { /* n:"BrtBeginCFRule14", */ T:1 },
  18421. 0x0419: { /* n:"BrtEndCFRule14", */ T:-1 },
  18422. 0x041A: { /* n:"BrtCFVO14" */ },
  18423. 0x041B: { /* n:"BrtBeginDatabar14", */ T:1 },
  18424. 0x041C: { /* n:"BrtBeginIconSet14", */ T:1 },
  18425. 0x041D: { /* n:"BrtDVal14", */ f: parse_BrtDVal14 },
  18426. 0x041E: { /* n:"BrtBeginDVals14", */ T:1 },
  18427. 0x041F: { /* n:"BrtColor14" */ },
  18428. 0x0420: { /* n:"BrtBeginSparklines", */ T:1 },
  18429. 0x0421: { /* n:"BrtEndSparklines", */ T:-1 },
  18430. 0x0422: { /* n:"BrtBeginSparklineGroups", */ T:1 },
  18431. 0x0423: { /* n:"BrtEndSparklineGroups", */ T:-1 },
  18432. 0x0425: { /* n:"BrtSXVD14" */ },
  18433. 0x0426: { /* n:"BrtBeginSXView14", */ T:1 },
  18434. 0x0427: { /* n:"BrtEndSXView14", */ T:-1 },
  18435. 0x0428: { /* n:"BrtBeginSXView16", */ T:1 },
  18436. 0x0429: { /* n:"BrtEndSXView16", */ T:-1 },
  18437. 0x042A: { /* n:"BrtBeginPCD14", */ T:1 },
  18438. 0x042B: { /* n:"BrtEndPCD14", */ T:-1 },
  18439. 0x042C: { /* n:"BrtBeginExtConn14", */ T:1 },
  18440. 0x042D: { /* n:"BrtEndExtConn14", */ T:-1 },
  18441. 0x042E: { /* n:"BrtBeginSlicerCacheIDs", */ T:1 },
  18442. 0x042F: { /* n:"BrtEndSlicerCacheIDs", */ T:-1 },
  18443. 0x0430: { /* n:"BrtBeginSlicerCacheID", */ T:1 },
  18444. 0x0431: { /* n:"BrtEndSlicerCacheID", */ T:-1 },
  18445. 0x0433: { /* n:"BrtBeginSlicerCache", */ T:1 },
  18446. 0x0434: { /* n:"BrtEndSlicerCache", */ T:-1 },
  18447. 0x0435: { /* n:"BrtBeginSlicerCacheDef", */ T:1 },
  18448. 0x0436: { /* n:"BrtEndSlicerCacheDef", */ T:-1 },
  18449. 0x0437: { /* n:"BrtBeginSlicersEx", */ T:1 },
  18450. 0x0438: { /* n:"BrtEndSlicersEx", */ T:-1 },
  18451. 0x0439: { /* n:"BrtBeginSlicerEx", */ T:1 },
  18452. 0x043A: { /* n:"BrtEndSlicerEx", */ T:-1 },
  18453. 0x043B: { /* n:"BrtBeginSlicer", */ T:1 },
  18454. 0x043C: { /* n:"BrtEndSlicer", */ T:-1 },
  18455. 0x043D: { /* n:"BrtSlicerCachePivotTables" */ },
  18456. 0x043E: { /* n:"BrtBeginSlicerCacheOlapImpl", */ T:1 },
  18457. 0x043F: { /* n:"BrtEndSlicerCacheOlapImpl", */ T:-1 },
  18458. 0x0440: { /* n:"BrtBeginSlicerCacheLevelsData", */ T:1 },
  18459. 0x0441: { /* n:"BrtEndSlicerCacheLevelsData", */ T:-1 },
  18460. 0x0442: { /* n:"BrtBeginSlicerCacheLevelData", */ T:1 },
  18461. 0x0443: { /* n:"BrtEndSlicerCacheLevelData", */ T:-1 },
  18462. 0x0444: { /* n:"BrtBeginSlicerCacheSiRanges", */ T:1 },
  18463. 0x0445: { /* n:"BrtEndSlicerCacheSiRanges", */ T:-1 },
  18464. 0x0446: { /* n:"BrtBeginSlicerCacheSiRange", */ T:1 },
  18465. 0x0447: { /* n:"BrtEndSlicerCacheSiRange", */ T:-1 },
  18466. 0x0448: { /* n:"BrtSlicerCacheOlapItem" */ },
  18467. 0x0449: { /* n:"BrtBeginSlicerCacheSelections", */ T:1 },
  18468. 0x044A: { /* n:"BrtSlicerCacheSelection" */ },
  18469. 0x044B: { /* n:"BrtEndSlicerCacheSelections", */ T:-1 },
  18470. 0x044C: { /* n:"BrtBeginSlicerCacheNative", */ T:1 },
  18471. 0x044D: { /* n:"BrtEndSlicerCacheNative", */ T:-1 },
  18472. 0x044E: { /* n:"BrtSlicerCacheNativeItem" */ },
  18473. 0x044F: { /* n:"BrtRangeProtection14" */ },
  18474. 0x0450: { /* n:"BrtRangeProtectionIso14" */ },
  18475. 0x0451: { /* n:"BrtCellIgnoreEC14" */ },
  18476. 0x0457: { /* n:"BrtList14" */ },
  18477. 0x0458: { /* n:"BrtCFIcon" */ },
  18478. 0x0459: { /* n:"BrtBeginSlicerCachesPivotCacheIDs", */ T:1 },
  18479. 0x045A: { /* n:"BrtEndSlicerCachesPivotCacheIDs", */ T:-1 },
  18480. 0x045B: { /* n:"BrtBeginSlicers", */ T:1 },
  18481. 0x045C: { /* n:"BrtEndSlicers", */ T:-1 },
  18482. 0x045D: { /* n:"BrtWbProp14" */ },
  18483. 0x045E: { /* n:"BrtBeginSXEdit", */ T:1 },
  18484. 0x045F: { /* n:"BrtEndSXEdit", */ T:-1 },
  18485. 0x0460: { /* n:"BrtBeginSXEdits", */ T:1 },
  18486. 0x0461: { /* n:"BrtEndSXEdits", */ T:-1 },
  18487. 0x0462: { /* n:"BrtBeginSXChange", */ T:1 },
  18488. 0x0463: { /* n:"BrtEndSXChange", */ T:-1 },
  18489. 0x0464: { /* n:"BrtBeginSXChanges", */ T:1 },
  18490. 0x0465: { /* n:"BrtEndSXChanges", */ T:-1 },
  18491. 0x0466: { /* n:"BrtSXTupleItems" */ },
  18492. 0x0468: { /* n:"BrtBeginSlicerStyle", */ T:1 },
  18493. 0x0469: { /* n:"BrtEndSlicerStyle", */ T:-1 },
  18494. 0x046A: { /* n:"BrtSlicerStyleElement" */ },
  18495. 0x046B: { /* n:"BrtBeginStyleSheetExt14", */ T:1 },
  18496. 0x046C: { /* n:"BrtEndStyleSheetExt14", */ T:-1 },
  18497. 0x046D: { /* n:"BrtBeginSlicerCachesPivotCacheID", */ T:1 },
  18498. 0x046E: { /* n:"BrtEndSlicerCachesPivotCacheID", */ T:-1 },
  18499. 0x046F: { /* n:"BrtBeginConditionalFormattings", */ T:1 },
  18500. 0x0470: { /* n:"BrtEndConditionalFormattings", */ T:-1 },
  18501. 0x0471: { /* n:"BrtBeginPCDCalcMemExt", */ T:1 },
  18502. 0x0472: { /* n:"BrtEndPCDCalcMemExt", */ T:-1 },
  18503. 0x0473: { /* n:"BrtBeginPCDCalcMemsExt", */ T:1 },
  18504. 0x0474: { /* n:"BrtEndPCDCalcMemsExt", */ T:-1 },
  18505. 0x0475: { /* n:"BrtPCDField14" */ },
  18506. 0x0476: { /* n:"BrtBeginSlicerStyles", */ T:1 },
  18507. 0x0477: { /* n:"BrtEndSlicerStyles", */ T:-1 },
  18508. 0x0478: { /* n:"BrtBeginSlicerStyleElements", */ T:1 },
  18509. 0x0479: { /* n:"BrtEndSlicerStyleElements", */ T:-1 },
  18510. 0x047A: { /* n:"BrtCFRuleExt" */ },
  18511. 0x047B: { /* n:"BrtBeginSXCondFmt14", */ T:1 },
  18512. 0x047C: { /* n:"BrtEndSXCondFmt14", */ T:-1 },
  18513. 0x047D: { /* n:"BrtBeginSXCondFmts14", */ T:1 },
  18514. 0x047E: { /* n:"BrtEndSXCondFmts14", */ T:-1 },
  18515. 0x0480: { /* n:"BrtBeginSortCond14", */ T:1 },
  18516. 0x0481: { /* n:"BrtEndSortCond14", */ T:-1 },
  18517. 0x0482: { /* n:"BrtEndDVals14", */ T:-1 },
  18518. 0x0483: { /* n:"BrtEndIconSet14", */ T:-1 },
  18519. 0x0484: { /* n:"BrtEndDatabar14", */ T:-1 },
  18520. 0x0485: { /* n:"BrtBeginColorScale14", */ T:1 },
  18521. 0x0486: { /* n:"BrtEndColorScale14", */ T:-1 },
  18522. 0x0487: { /* n:"BrtBeginSxrules14", */ T:1 },
  18523. 0x0488: { /* n:"BrtEndSxrules14", */ T:-1 },
  18524. 0x0489: { /* n:"BrtBeginPRule14", */ T:1 },
  18525. 0x048A: { /* n:"BrtEndPRule14", */ T:-1 },
  18526. 0x048B: { /* n:"BrtBeginPRFilters14", */ T:1 },
  18527. 0x048C: { /* n:"BrtEndPRFilters14", */ T:-1 },
  18528. 0x048D: { /* n:"BrtBeginPRFilter14", */ T:1 },
  18529. 0x048E: { /* n:"BrtEndPRFilter14", */ T:-1 },
  18530. 0x048F: { /* n:"BrtBeginPRFItem14", */ T:1 },
  18531. 0x0490: { /* n:"BrtEndPRFItem14", */ T:-1 },
  18532. 0x0491: { /* n:"BrtBeginCellIgnoreECs14", */ T:1 },
  18533. 0x0492: { /* n:"BrtEndCellIgnoreECs14", */ T:-1 },
  18534. 0x0493: { /* n:"BrtDxf14" */ },
  18535. 0x0494: { /* n:"BrtBeginDxF14s", */ T:1 },
  18536. 0x0495: { /* n:"BrtEndDxf14s", */ T:-1 },
  18537. 0x0499: { /* n:"BrtFilter14" */ },
  18538. 0x049A: { /* n:"BrtBeginCustomFilters14", */ T:1 },
  18539. 0x049C: { /* n:"BrtCustomFilter14" */ },
  18540. 0x049D: { /* n:"BrtIconFilter14" */ },
  18541. 0x049E: { /* n:"BrtPivotCacheConnectionName" */ },
  18542. 0x0800: { /* n:"BrtBeginDecoupledPivotCacheIDs", */ T:1 },
  18543. 0x0801: { /* n:"BrtEndDecoupledPivotCacheIDs", */ T:-1 },
  18544. 0x0802: { /* n:"BrtDecoupledPivotCacheID" */ },
  18545. 0x0803: { /* n:"BrtBeginPivotTableRefs", */ T:1 },
  18546. 0x0804: { /* n:"BrtEndPivotTableRefs", */ T:-1 },
  18547. 0x0805: { /* n:"BrtPivotTableRef" */ },
  18548. 0x0806: { /* n:"BrtSlicerCacheBookPivotTables" */ },
  18549. 0x0807: { /* n:"BrtBeginSxvcells", */ T:1 },
  18550. 0x0808: { /* n:"BrtEndSxvcells", */ T:-1 },
  18551. 0x0809: { /* n:"BrtBeginSxRow", */ T:1 },
  18552. 0x080A: { /* n:"BrtEndSxRow", */ T:-1 },
  18553. 0x080C: { /* n:"BrtPcdCalcMem15" */ },
  18554. 0x0813: { /* n:"BrtQsi15" */ },
  18555. 0x0814: { /* n:"BrtBeginWebExtensions", */ T:1 },
  18556. 0x0815: { /* n:"BrtEndWebExtensions", */ T:-1 },
  18557. 0x0816: { /* n:"BrtWebExtension" */ },
  18558. 0x0817: { /* n:"BrtAbsPath15" */ },
  18559. 0x0818: { /* n:"BrtBeginPivotTableUISettings", */ T:1 },
  18560. 0x0819: { /* n:"BrtEndPivotTableUISettings", */ T:-1 },
  18561. 0x081B: { /* n:"BrtTableSlicerCacheIDs" */ },
  18562. 0x081C: { /* n:"BrtTableSlicerCacheID" */ },
  18563. 0x081D: { /* n:"BrtBeginTableSlicerCache", */ T:1 },
  18564. 0x081E: { /* n:"BrtEndTableSlicerCache", */ T:-1 },
  18565. 0x081F: { /* n:"BrtSxFilter15" */ },
  18566. 0x0820: { /* n:"BrtBeginTimelineCachePivotCacheIDs", */ T:1 },
  18567. 0x0821: { /* n:"BrtEndTimelineCachePivotCacheIDs", */ T:-1 },
  18568. 0x0822: { /* n:"BrtTimelineCachePivotCacheID" */ },
  18569. 0x0823: { /* n:"BrtBeginTimelineCacheIDs", */ T:1 },
  18570. 0x0824: { /* n:"BrtEndTimelineCacheIDs", */ T:-1 },
  18571. 0x0825: { /* n:"BrtBeginTimelineCacheID", */ T:1 },
  18572. 0x0826: { /* n:"BrtEndTimelineCacheID", */ T:-1 },
  18573. 0x0827: { /* n:"BrtBeginTimelinesEx", */ T:1 },
  18574. 0x0828: { /* n:"BrtEndTimelinesEx", */ T:-1 },
  18575. 0x0829: { /* n:"BrtBeginTimelineEx", */ T:1 },
  18576. 0x082A: { /* n:"BrtEndTimelineEx", */ T:-1 },
  18577. 0x082B: { /* n:"BrtWorkBookPr15" */ },
  18578. 0x082C: { /* n:"BrtPCDH15" */ },
  18579. 0x082D: { /* n:"BrtBeginTimelineStyle", */ T:1 },
  18580. 0x082E: { /* n:"BrtEndTimelineStyle", */ T:-1 },
  18581. 0x082F: { /* n:"BrtTimelineStyleElement" */ },
  18582. 0x0830: { /* n:"BrtBeginTimelineStylesheetExt15", */ T:1 },
  18583. 0x0831: { /* n:"BrtEndTimelineStylesheetExt15", */ T:-1 },
  18584. 0x0832: { /* n:"BrtBeginTimelineStyles", */ T:1 },
  18585. 0x0833: { /* n:"BrtEndTimelineStyles", */ T:-1 },
  18586. 0x0834: { /* n:"BrtBeginTimelineStyleElements", */ T:1 },
  18587. 0x0835: { /* n:"BrtEndTimelineStyleElements", */ T:-1 },
  18588. 0x0836: { /* n:"BrtDxf15" */ },
  18589. 0x0837: { /* n:"BrtBeginDxfs15", */ T:1 },
  18590. 0x0838: { /* n:"BrtEndDxfs15", */ T:-1 },
  18591. 0x0839: { /* n:"BrtSlicerCacheHideItemsWithNoData" */ },
  18592. 0x083A: { /* n:"BrtBeginItemUniqueNames", */ T:1 },
  18593. 0x083B: { /* n:"BrtEndItemUniqueNames", */ T:-1 },
  18594. 0x083C: { /* n:"BrtItemUniqueName" */ },
  18595. 0x083D: { /* n:"BrtBeginExtConn15", */ T:1 },
  18596. 0x083E: { /* n:"BrtEndExtConn15", */ T:-1 },
  18597. 0x083F: { /* n:"BrtBeginOledbPr15", */ T:1 },
  18598. 0x0840: { /* n:"BrtEndOledbPr15", */ T:-1 },
  18599. 0x0841: { /* n:"BrtBeginDataFeedPr15", */ T:1 },
  18600. 0x0842: { /* n:"BrtEndDataFeedPr15", */ T:-1 },
  18601. 0x0843: { /* n:"BrtTextPr15" */ },
  18602. 0x0844: { /* n:"BrtRangePr15" */ },
  18603. 0x0845: { /* n:"BrtDbCommand15" */ },
  18604. 0x0846: { /* n:"BrtBeginDbTables15", */ T:1 },
  18605. 0x0847: { /* n:"BrtEndDbTables15", */ T:-1 },
  18606. 0x0848: { /* n:"BrtDbTable15" */ },
  18607. 0x0849: { /* n:"BrtBeginDataModel", */ T:1 },
  18608. 0x084A: { /* n:"BrtEndDataModel", */ T:-1 },
  18609. 0x084B: { /* n:"BrtBeginModelTables", */ T:1 },
  18610. 0x084C: { /* n:"BrtEndModelTables", */ T:-1 },
  18611. 0x084D: { /* n:"BrtModelTable" */ },
  18612. 0x084E: { /* n:"BrtBeginModelRelationships", */ T:1 },
  18613. 0x084F: { /* n:"BrtEndModelRelationships", */ T:-1 },
  18614. 0x0850: { /* n:"BrtModelRelationship" */ },
  18615. 0x0851: { /* n:"BrtBeginECTxtWiz15", */ T:1 },
  18616. 0x0852: { /* n:"BrtEndECTxtWiz15", */ T:-1 },
  18617. 0x0853: { /* n:"BrtBeginECTWFldInfoLst15", */ T:1 },
  18618. 0x0854: { /* n:"BrtEndECTWFldInfoLst15", */ T:-1 },
  18619. 0x0855: { /* n:"BrtBeginECTWFldInfo15", */ T:1 },
  18620. 0x0856: { /* n:"BrtFieldListActiveItem" */ },
  18621. 0x0857: { /* n:"BrtPivotCacheIdVersion" */ },
  18622. 0x0858: { /* n:"BrtSXDI15" */ },
  18623. 0x0859: { /* n:"BrtBeginModelTimeGroupings", */ T:1 },
  18624. 0x085A: { /* n:"BrtEndModelTimeGroupings", */ T:-1 },
  18625. 0x085B: { /* n:"BrtBeginModelTimeGrouping", */ T:1 },
  18626. 0x085C: { /* n:"BrtEndModelTimeGrouping", */ T:-1 },
  18627. 0x085D: { /* n:"BrtModelTimeGroupingCalcCol" */ },
  18628. 0x0C00: { /* n:"BrtUid" */ },
  18629. 0x0C01: { /* n:"BrtRevisionPtr" */ },
  18630. 0x1000: { /* n:"BrtBeginDynamicArrayPr", */ T:1 },
  18631. 0x1001: { /* n:"BrtEndDynamicArrayPr", */ T:-1 },
  18632. 0x138A: { /* n:"BrtBeginRichValueBlock", */ T:1 },
  18633. 0x138B: { /* n:"BrtEndRichValueBlock", */ T:-1 },
  18634. 0x13D9: { /* n:"BrtBeginRichFilters", */ T:1 },
  18635. 0x13DA: { /* n:"BrtEndRichFilters", */ T:-1 },
  18636. 0x13DB: { /* n:"BrtRichFilter" */ },
  18637. 0x13DC: { /* n:"BrtBeginRichFilterColumn", */ T:1 },
  18638. 0x13DD: { /* n:"BrtEndRichFilterColumn", */ T:-1 },
  18639. 0x13DE: { /* n:"BrtBeginCustomRichFilters", */ T:1 },
  18640. 0x13DF: { /* n:"BrtEndCustomRichFilters", */ T:-1 },
  18641. 0x13E0: { /* n:"BrtCustomRichFilter" */ },
  18642. 0x13E1: { /* n:"BrtTop10RichFilter" */ },
  18643. 0x13E2: { /* n:"BrtDynamicRichFilter" */ },
  18644. 0x13E4: { /* n:"BrtBeginRichSortCondition", */ T:1 },
  18645. 0x13E5: { /* n:"BrtEndRichSortCondition", */ T:-1 },
  18646. 0x13E6: { /* n:"BrtRichFilterDateGroupItem" */ },
  18647. 0x13E7: { /* n:"BrtBeginCalcFeatures", */ T:1 },
  18648. 0x13E8: { /* n:"BrtEndCalcFeatures", */ T:-1 },
  18649. 0x13E9: { /* n:"BrtCalcFeature" */ },
  18650. 0x13EB: { /* n:"BrtExternalLinksPr" */ },
  18651. 0xFFFF: { n:"" }
  18652. };
  18653. /* [MS-XLS] 2.3 Record Enumeration (and other sources) */
  18654. var XLSRecordEnum = {
  18655. /* [MS-XLS] 2.3 Record Enumeration 2021-08-17 */
  18656. 0x0006: { /* n:"Formula", */ f:parse_Formula },
  18657. 0x000a: { /* n:"EOF", */ f:parsenoop2 },
  18658. 0x000c: { /* n:"CalcCount", */ f:parseuint16 }, //
  18659. 0x000d: { /* n:"CalcMode", */ f:parseuint16 }, //
  18660. 0x000e: { /* n:"CalcPrecision", */ f:parsebool }, //
  18661. 0x000f: { /* n:"CalcRefMode", */ f:parsebool }, //
  18662. 0x0010: { /* n:"CalcDelta", */ f:parse_Xnum }, //
  18663. 0x0011: { /* n:"CalcIter", */ f:parsebool }, //
  18664. 0x0012: { /* n:"Protect", */ f:parsebool },
  18665. 0x0013: { /* n:"Password", */ f:parseuint16 },
  18666. 0x0014: { /* n:"Header", */ f:parse_XLHeaderFooter },
  18667. 0x0015: { /* n:"Footer", */ f:parse_XLHeaderFooter },
  18668. 0x0017: { /* n:"ExternSheet", */ f:parse_ExternSheet },
  18669. 0x0018: { /* n:"Lbl", */ f:parse_Lbl },
  18670. 0x0019: { /* n:"WinProtect", */ f:parsebool },
  18671. 0x001a: { /* n:"VerticalPageBreaks", */ },
  18672. 0x001b: { /* n:"HorizontalPageBreaks", */ },
  18673. 0x001c: { /* n:"Note", */ f:parse_Note },
  18674. 0x001d: { /* n:"Selection", */ },
  18675. 0x0022: { /* n:"Date1904", */ f:parsebool },
  18676. 0x0023: { /* n:"ExternName", */ f:parse_ExternName },
  18677. 0x0026: { /* n:"LeftMargin", */ f:parse_Xnum }, // *
  18678. 0x0027: { /* n:"RightMargin", */ f:parse_Xnum }, // *
  18679. 0x0028: { /* n:"TopMargin", */ f:parse_Xnum }, // *
  18680. 0x0029: { /* n:"BottomMargin", */ f:parse_Xnum }, // *
  18681. 0x002a: { /* n:"PrintRowCol", */ f:parsebool },
  18682. 0x002b: { /* n:"PrintGrid", */ f:parsebool },
  18683. 0x002f: { /* n:"FilePass", */ f:parse_FilePass },
  18684. 0x0031: { /* n:"Font", */ f:parse_Font },
  18685. 0x0033: { /* n:"PrintSize", */ f:parseuint16 },
  18686. 0x003c: { /* n:"Continue", */ },
  18687. 0x003d: { /* n:"Window1", */ f:parse_Window1 },
  18688. 0x0040: { /* n:"Backup", */ f:parsebool },
  18689. 0x0041: { /* n:"Pane", */ f:parse_Pane },
  18690. 0x0042: { /* n:"CodePage", */ f:parseuint16 },
  18691. 0x004d: { /* n:"Pls", */ },
  18692. 0x0050: { /* n:"DCon", */ },
  18693. 0x0051: { /* n:"DConRef", */ },
  18694. 0x0052: { /* n:"DConName", */ },
  18695. 0x0055: { /* n:"DefColWidth", */ f:parseuint16 },
  18696. 0x0059: { /* n:"XCT", */ },
  18697. 0x005a: { /* n:"CRN", */ },
  18698. 0x005b: { /* n:"FileSharing", */ },
  18699. 0x005c: { /* n:"WriteAccess", */ f:parse_WriteAccess },
  18700. 0x005d: { /* n:"Obj", */ f:parse_Obj },
  18701. 0x005e: { /* n:"Uncalced", */ },
  18702. 0x005f: { /* n:"CalcSaveRecalc", */ f:parsebool }, //
  18703. 0x0060: { /* n:"Template", */ },
  18704. 0x0061: { /* n:"Intl", */ },
  18705. 0x0063: { /* n:"ObjProtect", */ f:parsebool },
  18706. 0x007d: { /* n:"ColInfo", */ f:parse_ColInfo },
  18707. 0x0080: { /* n:"Guts", */ f:parse_Guts },
  18708. 0x0081: { /* n:"WsBool", */ f:parse_WsBool },
  18709. 0x0082: { /* n:"GridSet", */ f:parseuint16 },
  18710. 0x0083: { /* n:"HCenter", */ f:parsebool },
  18711. 0x0084: { /* n:"VCenter", */ f:parsebool },
  18712. 0x0085: { /* n:"BoundSheet8", */ f:parse_BoundSheet8 },
  18713. 0x0086: { /* n:"WriteProtect", */ },
  18714. 0x008c: { /* n:"Country", */ f:parse_Country },
  18715. 0x008d: { /* n:"HideObj", */ f:parseuint16 },
  18716. 0x0090: { /* n:"Sort", */ },
  18717. 0x0092: { /* n:"Palette", */ f:parse_Palette },
  18718. 0x0097: { /* n:"Sync", */ },
  18719. 0x0098: { /* n:"LPr", */ },
  18720. 0x0099: { /* n:"DxGCol", */ },
  18721. 0x009a: { /* n:"FnGroupName", */ },
  18722. 0x009b: { /* n:"FilterMode", */ },
  18723. 0x009c: { /* n:"BuiltInFnGroupCount", */ f:parseuint16 },
  18724. 0x009d: { /* n:"AutoFilterInfo", */ },
  18725. 0x009e: { /* n:"AutoFilter", */ },
  18726. 0x00a0: { /* n:"Scl", */ f:parse_Scl },
  18727. 0x00a1: { /* n:"Setup", */ f:parse_Setup },
  18728. 0x00ae: { /* n:"ScenMan", */ },
  18729. 0x00af: { /* n:"SCENARIO", */ },
  18730. 0x00b0: { /* n:"SxView", */ },
  18731. 0x00b1: { /* n:"Sxvd", */ },
  18732. 0x00b2: { /* n:"SXVI", */ },
  18733. 0x00b4: { /* n:"SxIvd", */ },
  18734. 0x00b5: { /* n:"SXLI", */ },
  18735. 0x00b6: { /* n:"SXPI", */ },
  18736. 0x00b8: { /* n:"DocRoute", */ },
  18737. 0x00b9: { /* n:"RecipName", */ },
  18738. 0x00bd: { /* n:"MulRk", */ f:parse_MulRk },
  18739. 0x00be: { /* n:"MulBlank", */ f:parse_MulBlank },
  18740. 0x00c1: { /* n:"Mms", */ f:parsenoop2 },
  18741. 0x00c5: { /* n:"SXDI", */ },
  18742. 0x00c6: { /* n:"SXDB", */ },
  18743. 0x00c7: { /* n:"SXFDB", */ },
  18744. 0x00c8: { /* n:"SXDBB", */ },
  18745. 0x00c9: { /* n:"SXNum", */ },
  18746. 0x00ca: { /* n:"SxBool", */ f:parsebool },
  18747. 0x00cb: { /* n:"SxErr", */ },
  18748. 0x00cc: { /* n:"SXInt", */ },
  18749. 0x00cd: { /* n:"SXString", */ },
  18750. 0x00ce: { /* n:"SXDtr", */ },
  18751. 0x00cf: { /* n:"SxNil", */ },
  18752. 0x00d0: { /* n:"SXTbl", */ },
  18753. 0x00d1: { /* n:"SXTBRGIITM", */ },
  18754. 0x00d2: { /* n:"SxTbpg", */ },
  18755. 0x00d3: { /* n:"ObProj", */ },
  18756. 0x00d5: { /* n:"SXStreamID", */ },
  18757. 0x00d7: { /* n:"DBCell", */ },
  18758. 0x00d8: { /* n:"SXRng", */ },
  18759. 0x00d9: { /* n:"SxIsxoper", */ },
  18760. 0x00da: { /* n:"BookBool", */ f:parseuint16 },
  18761. 0x00dc: { /* n:"DbOrParamQry", */ },
  18762. 0x00dd: { /* n:"ScenarioProtect", */ f:parsebool },
  18763. 0x00de: { /* n:"OleObjectSize", */ },
  18764. 0x00e0: { /* n:"XF", */ f:parse_XF },
  18765. 0x00e1: { /* n:"InterfaceHdr", */ f:parse_InterfaceHdr },
  18766. 0x00e2: { /* n:"InterfaceEnd", */ f:parsenoop2 },
  18767. 0x00e3: { /* n:"SXVS", */ },
  18768. 0x00e5: { /* n:"MergeCells", */ f:parse_MergeCells },
  18769. 0x00e9: { /* n:"BkHim", */ },
  18770. 0x00eb: { /* n:"MsoDrawingGroup", */ },
  18771. 0x00ec: { /* n:"MsoDrawing", */ },
  18772. 0x00ed: { /* n:"MsoDrawingSelection", */ },
  18773. 0x00ef: { /* n:"PhoneticInfo", */ },
  18774. 0x00f0: { /* n:"SxRule", */ },
  18775. 0x00f1: { /* n:"SXEx", */ },
  18776. 0x00f2: { /* n:"SxFilt", */ },
  18777. 0x00f4: { /* n:"SxDXF", */ },
  18778. 0x00f5: { /* n:"SxItm", */ },
  18779. 0x00f6: { /* n:"SxName", */ },
  18780. 0x00f7: { /* n:"SxSelect", */ },
  18781. 0x00f8: { /* n:"SXPair", */ },
  18782. 0x00f9: { /* n:"SxFmla", */ },
  18783. 0x00fb: { /* n:"SxFormat", */ },
  18784. 0x00fc: { /* n:"SST", */ f:parse_SST },
  18785. 0x00fd: { /* n:"LabelSst", */ f:parse_LabelSst },
  18786. 0x00ff: { /* n:"ExtSST", */ f:parse_ExtSST },
  18787. 0x0100: { /* n:"SXVDEx", */ },
  18788. 0x0103: { /* n:"SXFormula", */ },
  18789. 0x0122: { /* n:"SXDBEx", */ },
  18790. 0x0137: { /* n:"RRDInsDel", */ },
  18791. 0x0138: { /* n:"RRDHead", */ },
  18792. 0x013b: { /* n:"RRDChgCell", */ },
  18793. 0x013d: { /* n:"RRTabId", */ f:parseuint16a },
  18794. 0x013e: { /* n:"RRDRenSheet", */ },
  18795. 0x013f: { /* n:"RRSort", */ },
  18796. 0x0140: { /* n:"RRDMove", */ },
  18797. 0x014a: { /* n:"RRFormat", */ },
  18798. 0x014b: { /* n:"RRAutoFmt", */ },
  18799. 0x014d: { /* n:"RRInsertSh", */ },
  18800. 0x014e: { /* n:"RRDMoveBegin", */ },
  18801. 0x014f: { /* n:"RRDMoveEnd", */ },
  18802. 0x0150: { /* n:"RRDInsDelBegin", */ },
  18803. 0x0151: { /* n:"RRDInsDelEnd", */ },
  18804. 0x0152: { /* n:"RRDConflict", */ },
  18805. 0x0153: { /* n:"RRDDefName", */ },
  18806. 0x0154: { /* n:"RRDRstEtxp", */ },
  18807. 0x015f: { /* n:"LRng", */ },
  18808. 0x0160: { /* n:"UsesELFs", */ f:parsebool },
  18809. 0x0161: { /* n:"DSF", */ f:parsenoop2 },
  18810. 0x0191: { /* n:"CUsr", */ },
  18811. 0x0192: { /* n:"CbUsr", */ },
  18812. 0x0193: { /* n:"UsrInfo", */ },
  18813. 0x0194: { /* n:"UsrExcl", */ },
  18814. 0x0195: { /* n:"FileLock", */ },
  18815. 0x0196: { /* n:"RRDInfo", */ },
  18816. 0x0197: { /* n:"BCUsrs", */ },
  18817. 0x0198: { /* n:"UsrChk", */ },
  18818. 0x01a9: { /* n:"UserBView", */ },
  18819. 0x01aa: { /* n:"UserSViewBegin", */ },
  18820. 0x01ab: { /* n:"UserSViewEnd", */ },
  18821. 0x01ac: { /* n:"RRDUserView", */ },
  18822. 0x01ad: { /* n:"Qsi", */ },
  18823. 0x01ae: { /* n:"SupBook", */ f:parse_SupBook },
  18824. 0x01af: { /* n:"Prot4Rev", */ f:parsebool },
  18825. 0x01b0: { /* n:"CondFmt", */ },
  18826. 0x01b1: { /* n:"CF", */ },
  18827. 0x01b2: { /* n:"DVal", */ },
  18828. 0x01b5: { /* n:"DConBin", */ },
  18829. 0x01b6: { /* n:"TxO", */ f:parse_TxO },
  18830. 0x01b7: { /* n:"RefreshAll", */ f:parsebool }, //
  18831. 0x01b8: { /* n:"HLink", */ f:parse_HLink },
  18832. 0x01b9: { /* n:"Lel", */ },
  18833. 0x01ba: { /* n:"CodeName", */ f:parse_XLUnicodeString },
  18834. 0x01bb: { /* n:"SXFDBType", */ },
  18835. 0x01bc: { /* n:"Prot4RevPass", */ f:parseuint16 },
  18836. 0x01bd: { /* n:"ObNoMacros", */ },
  18837. 0x01be: { /* n:"Dv", */ },
  18838. 0x01c0: { /* n:"Excel9File", */ f:parsenoop2 },
  18839. 0x01c1: { /* n:"RecalcId", */ f:parse_RecalcId, r:2},
  18840. 0x01c2: { /* n:"EntExU2", */ f:parsenoop2 },
  18841. 0x0200: { /* n:"Dimensions", */ f:parse_Dimensions },
  18842. 0x0201: { /* n:"Blank", */ f:parse_Blank },
  18843. 0x0203: { /* n:"Number", */ f:parse_Number },
  18844. 0x0204: { /* n:"Label", */ f:parse_Label },
  18845. 0x0205: { /* n:"BoolErr", */ f:parse_BoolErr },
  18846. 0x0207: { /* n:"String", */ f:parse_String },
  18847. 0x0208: { /* n:"Row", */ f:parse_Row },
  18848. 0x020b: { /* n:"Index", */ },
  18849. 0x0221: { /* n:"Array", */ f:parse_Array },
  18850. 0x0225: { /* n:"DefaultRowHeight", */ f:parse_DefaultRowHeight },
  18851. 0x0236: { /* n:"Table", */ },
  18852. 0x023e: { /* n:"Window2", */ f:parse_Window2 },
  18853. 0x027e: { /* n:"RK", */ f:parse_RK },
  18854. 0x0293: { /* n:"Style", */ },
  18855. 0x0418: { /* n:"BigName", */ },
  18856. 0x041e: { /* n:"Format", */ f:parse_Format },
  18857. 0x043c: { /* n:"ContinueBigName", */ },
  18858. 0x04bc: { /* n:"ShrFmla", */ f:parse_ShrFmla },
  18859. 0x0800: { /* n:"HLinkTooltip", */ f:parse_HLinkTooltip },
  18860. 0x0801: { /* n:"WebPub", */ },
  18861. 0x0802: { /* n:"QsiSXTag", */ },
  18862. 0x0803: { /* n:"DBQueryExt", */ },
  18863. 0x0804: { /* n:"ExtString", */ },
  18864. 0x0805: { /* n:"TxtQry", */ },
  18865. 0x0806: { /* n:"Qsir", */ },
  18866. 0x0807: { /* n:"Qsif", */ },
  18867. 0x0808: { /* n:"RRDTQSIF", */ },
  18868. 0x0809: { /* n:"BOF", */ f:parse_BOF },
  18869. 0x080a: { /* n:"OleDbConn", */ },
  18870. 0x080b: { /* n:"WOpt", */ },
  18871. 0x080c: { /* n:"SXViewEx", */ },
  18872. 0x080d: { /* n:"SXTH", */ },
  18873. 0x080e: { /* n:"SXPIEx", */ },
  18874. 0x080f: { /* n:"SXVDTEx", */ },
  18875. 0x0810: { /* n:"SXViewEx9", */ },
  18876. 0x0812: { /* n:"ContinueFrt", */ },
  18877. 0x0813: { /* n:"RealTimeData", */ },
  18878. 0x0850: { /* n:"ChartFrtInfo", */ },
  18879. 0x0851: { /* n:"FrtWrapper", */ },
  18880. 0x0852: { /* n:"StartBlock", */ },
  18881. 0x0853: { /* n:"EndBlock", */ },
  18882. 0x0854: { /* n:"StartObject", */ },
  18883. 0x0855: { /* n:"EndObject", */ },
  18884. 0x0856: { /* n:"CatLab", */ },
  18885. 0x0857: { /* n:"YMult", */ },
  18886. 0x0858: { /* n:"SXViewLink", */ },
  18887. 0x0859: { /* n:"PivotChartBits", */ },
  18888. 0x085a: { /* n:"FrtFontList", */ },
  18889. 0x0862: { /* n:"SheetExt", */ },
  18890. 0x0863: { /* n:"BookExt", */ r:12},
  18891. 0x0864: { /* n:"SXAddl", */ },
  18892. 0x0865: { /* n:"CrErr", */ },
  18893. 0x0866: { /* n:"HFPicture", */ },
  18894. 0x0867: { /* n:"FeatHdr", */ f:parsenoop2 },
  18895. 0x0868: { /* n:"Feat", */ },
  18896. 0x086a: { /* n:"DataLabExt", */ },
  18897. 0x086b: { /* n:"DataLabExtContents", */ },
  18898. 0x086c: { /* n:"CellWatch", */ },
  18899. 0x0871: { /* n:"FeatHdr11", */ },
  18900. 0x0872: { /* n:"Feature11", */ },
  18901. 0x0874: { /* n:"DropDownObjIds", */ },
  18902. 0x0875: { /* n:"ContinueFrt11", */ },
  18903. 0x0876: { /* n:"DConn", */ },
  18904. 0x0877: { /* n:"List12", */ },
  18905. 0x0878: { /* n:"Feature12", */ },
  18906. 0x0879: { /* n:"CondFmt12", */ },
  18907. 0x087a: { /* n:"CF12", */ },
  18908. 0x087b: { /* n:"CFEx", */ },
  18909. 0x087c: { /* n:"XFCRC", */ f:parse_XFCRC, r:12 },
  18910. 0x087d: { /* n:"XFExt", */ f:parse_XFExt, r:12 },
  18911. 0x087e: { /* n:"AutoFilter12", */ },
  18912. 0x087f: { /* n:"ContinueFrt12", */ },
  18913. 0x0884: { /* n:"MDTInfo", */ },
  18914. 0x0885: { /* n:"MDXStr", */ },
  18915. 0x0886: { /* n:"MDXTuple", */ },
  18916. 0x0887: { /* n:"MDXSet", */ },
  18917. 0x0888: { /* n:"MDXProp", */ },
  18918. 0x0889: { /* n:"MDXKPI", */ },
  18919. 0x088a: { /* n:"MDB", */ },
  18920. 0x088b: { /* n:"PLV", */ },
  18921. 0x088c: { /* n:"Compat12", */ f:parsebool, r:12 },
  18922. 0x088d: { /* n:"DXF", */ },
  18923. 0x088e: { /* n:"TableStyles", */ r:12 },
  18924. 0x088f: { /* n:"TableStyle", */ },
  18925. 0x0890: { /* n:"TableStyleElement", */ },
  18926. 0x0892: { /* n:"StyleExt", */ },
  18927. 0x0893: { /* n:"NamePublish", */ },
  18928. 0x0894: { /* n:"NameCmt", */ f:parse_NameCmt, r:12 },
  18929. 0x0895: { /* n:"SortData", */ },
  18930. 0x0896: { /* n:"Theme", */ f:parse_Theme, r:12 },
  18931. 0x0897: { /* n:"GUIDTypeLib", */ },
  18932. 0x0898: { /* n:"FnGrp12", */ },
  18933. 0x0899: { /* n:"NameFnGrp12", */ },
  18934. 0x089a: { /* n:"MTRSettings", */ f:parse_MTRSettings, r:12 },
  18935. 0x089b: { /* n:"CompressPictures", */ f:parsenoop2 },
  18936. 0x089c: { /* n:"HeaderFooter", */ },
  18937. 0x089d: { /* n:"CrtLayout12", */ },
  18938. 0x089e: { /* n:"CrtMlFrt", */ },
  18939. 0x089f: { /* n:"CrtMlFrtContinue", */ },
  18940. 0x08a3: { /* n:"ForceFullCalculation", */ f:parse_ForceFullCalculation },
  18941. 0x08a4: { /* n:"ShapePropsStream", */ },
  18942. 0x08a5: { /* n:"TextPropsStream", */ },
  18943. 0x08a6: { /* n:"RichTextStream", */ },
  18944. 0x08a7: { /* n:"CrtLayout12A", */ },
  18945. 0x1001: { /* n:"Units", */ },
  18946. 0x1002: { /* n:"Chart", */ },
  18947. 0x1003: { /* n:"Series", */ },
  18948. 0x1006: { /* n:"DataFormat", */ },
  18949. 0x1007: { /* n:"LineFormat", */ },
  18950. 0x1009: { /* n:"MarkerFormat", */ },
  18951. 0x100a: { /* n:"AreaFormat", */ },
  18952. 0x100b: { /* n:"PieFormat", */ },
  18953. 0x100c: { /* n:"AttachedLabel", */ },
  18954. 0x100d: { /* n:"SeriesText", */ },
  18955. 0x1014: { /* n:"ChartFormat", */ },
  18956. 0x1015: { /* n:"Legend", */ },
  18957. 0x1016: { /* n:"SeriesList", */ },
  18958. 0x1017: { /* n:"Bar", */ },
  18959. 0x1018: { /* n:"Line", */ },
  18960. 0x1019: { /* n:"Pie", */ },
  18961. 0x101a: { /* n:"Area", */ },
  18962. 0x101b: { /* n:"Scatter", */ },
  18963. 0x101c: { /* n:"CrtLine", */ },
  18964. 0x101d: { /* n:"Axis", */ },
  18965. 0x101e: { /* n:"Tick", */ },
  18966. 0x101f: { /* n:"ValueRange", */ },
  18967. 0x1020: { /* n:"CatSerRange", */ },
  18968. 0x1021: { /* n:"AxisLine", */ },
  18969. 0x1022: { /* n:"CrtLink", */ },
  18970. 0x1024: { /* n:"DefaultText", */ },
  18971. 0x1025: { /* n:"Text", */ },
  18972. 0x1026: { /* n:"FontX", */ f:parseuint16 },
  18973. 0x1027: { /* n:"ObjectLink", */ },
  18974. 0x1032: { /* n:"Frame", */ },
  18975. 0x1033: { /* n:"Begin", */ },
  18976. 0x1034: { /* n:"End", */ },
  18977. 0x1035: { /* n:"PlotArea", */ },
  18978. 0x103a: { /* n:"Chart3d", */ },
  18979. 0x103c: { /* n:"PicF", */ },
  18980. 0x103d: { /* n:"DropBar", */ },
  18981. 0x103e: { /* n:"Radar", */ },
  18982. 0x103f: { /* n:"Surf", */ },
  18983. 0x1040: { /* n:"RadarArea", */ },
  18984. 0x1041: { /* n:"AxisParent", */ },
  18985. 0x1043: { /* n:"LegendException", */ },
  18986. 0x1044: { /* n:"ShtProps", */ f:parse_ShtProps },
  18987. 0x1045: { /* n:"SerToCrt", */ },
  18988. 0x1046: { /* n:"AxesUsed", */ },
  18989. 0x1048: { /* n:"SBaseRef", */ },
  18990. 0x104a: { /* n:"SerParent", */ },
  18991. 0x104b: { /* n:"SerAuxTrend", */ },
  18992. 0x104e: { /* n:"IFmtRecord", */ },
  18993. 0x104f: { /* n:"Pos", */ },
  18994. 0x1050: { /* n:"AlRuns", */ },
  18995. 0x1051: { /* n:"BRAI", */ },
  18996. 0x105b: { /* n:"SerAuxErrBar", */ },
  18997. 0x105c: { /* n:"ClrtClient", */ f:parse_ClrtClient },
  18998. 0x105d: { /* n:"SerFmt", */ },
  18999. 0x105f: { /* n:"Chart3DBarShape", */ },
  19000. 0x1060: { /* n:"Fbi", */ },
  19001. 0x1061: { /* n:"BopPop", */ },
  19002. 0x1062: { /* n:"AxcExt", */ },
  19003. 0x1063: { /* n:"Dat", */ },
  19004. 0x1064: { /* n:"PlotGrowth", */ },
  19005. 0x1065: { /* n:"SIIndex", */ },
  19006. 0x1066: { /* n:"GelFrame", */ },
  19007. 0x1067: { /* n:"BopPopCustom", */ },
  19008. 0x1068: { /* n:"Fbi2", */ },
  19009. 0x0000: { /* n:"Dimensions", */ f:parse_Dimensions },
  19010. 0x0001: { /* n:"BIFF2BLANK", */ },
  19011. 0x0002: { /* n:"BIFF2INT", */ f:parse_BIFF2INT },
  19012. 0x0003: { /* n:"BIFF2NUM", */ f:parse_BIFF2NUM },
  19013. 0x0004: { /* n:"BIFF2STR", */ f:parse_BIFF2STR },
  19014. 0x0005: { /* n:"BoolErr", */ f:parse_BoolErr },
  19015. 0x0007: { /* n:"String", */ f:parse_BIFF2STRING },
  19016. 0x0008: { /* n:"BIFF2ROW", */ },
  19017. 0x0009: { /* n:"BOF", */ f:parse_BOF },
  19018. 0x000b: { /* n:"Index", */ },
  19019. 0x0016: { /* n:"ExternCount", */ f:parseuint16 },
  19020. 0x001e: { /* n:"BIFF2FORMAT", */ f:parse_BIFF2Format },
  19021. 0x001f: { /* n:"BIFF2FMTCNT", */ }, /* 16-bit cnt of BIFF2FORMAT records */
  19022. 0x0020: { /* n:"BIFF2COLINFO", */ },
  19023. 0x0021: { /* n:"Array", */ f:parse_Array },
  19024. 0x0024: { /* n:"COLWIDTH", */ },
  19025. 0x0025: { /* n:"DefaultRowHeight", */ f:parse_DefaultRowHeight },
  19026. // 0x2c ??
  19027. // 0x2d ??
  19028. // 0x2e ??
  19029. // 0x30 FONTCOUNT: number of fonts
  19030. 0x0032: { /* n:"BIFF2FONTXTRA", */ f:parse_BIFF2FONTXTRA },
  19031. // 0x35: INFOOPTS
  19032. // 0x36: TABLE (BIFF2 only)
  19033. // 0x37: TABLE2 (BIFF2 only)
  19034. // 0x38: WNDESK
  19035. // 0x39 ??
  19036. // 0x3a: BEGINPREF
  19037. // 0x3b: ENDPREF
  19038. 0x003e: { /* n:"BIFF2WINDOW2", */ },
  19039. // 0x3f ??
  19040. // 0x46: SHOWSCROLL
  19041. // 0x47: SHOWFORMULA
  19042. // 0x48: STATUSBAR
  19043. // 0x49: SHORTMENUS
  19044. // 0x4A:
  19045. // 0x4B:
  19046. // 0x4C:
  19047. // 0x4E:
  19048. // 0x4F:
  19049. // 0x58: TOOLBAR (BIFF3)
  19050. /* - - - */
  19051. 0x0034: { /* n:"DDEObjName", */ },
  19052. 0x0043: { /* n:"BIFF2XF", */ },
  19053. 0x0044: { /* n:"BIFF2XFINDEX", */ f:parseuint16 },
  19054. 0x0045: { /* n:"BIFF2FONTCLR", */ },
  19055. 0x0056: { /* n:"BIFF4FMTCNT", */ }, /* 16-bit cnt, similar to BIFF2 */
  19056. 0x007e: { /* n:"RK", */ }, /* Not necessarily same as 0x027e */
  19057. 0x007f: { /* n:"ImData", */ f:parse_ImData },
  19058. 0x0087: { /* n:"Addin", */ },
  19059. 0x0088: { /* n:"Edg", */ },
  19060. 0x0089: { /* n:"Pub", */ },
  19061. // 0x8A
  19062. // 0x8B LH: alternate menu key flag (BIFF3/4)
  19063. // 0x8E
  19064. // 0x8F
  19065. 0x0091: { /* n:"Sub", */ },
  19066. // 0x93 STYLE
  19067. 0x0094: { /* n:"LHRecord", */ },
  19068. 0x0095: { /* n:"LHNGraph", */ },
  19069. 0x0096: { /* n:"Sound", */ },
  19070. // 0xA2 FNPROTO: function prototypes (BIFF4)
  19071. // 0xA3
  19072. // 0xA8
  19073. 0x00a9: { /* n:"CoordList", */ },
  19074. 0x00ab: { /* n:"GCW", */ },
  19075. 0x00bc: { /* n:"ShrFmla", */ }, /* Not necessarily same as 0x04bc */
  19076. 0x00bf: { /* n:"ToolbarHdr", */ },
  19077. 0x00c0: { /* n:"ToolbarEnd", */ },
  19078. 0x00c2: { /* n:"AddMenu", */ },
  19079. 0x00c3: { /* n:"DelMenu", */ },
  19080. 0x00d6: { /* n:"RString", */ f:parse_RString },
  19081. 0x00df: { /* n:"UDDesc", */ },
  19082. 0x00ea: { /* n:"TabIdConf", */ },
  19083. 0x0162: { /* n:"XL5Modify", */ },
  19084. 0x01a5: { /* n:"FileSharing2", */ },
  19085. 0x0206: { /* n:"Formula", */ f:parse_Formula },
  19086. 0x0209: { /* n:"BOF", */ f:parse_BOF },
  19087. 0x0218: { /* n:"Lbl", */ f:parse_Lbl },
  19088. 0x0223: { /* n:"ExternName", */ f:parse_ExternName },
  19089. 0x0231: { /* n:"Font", */ },
  19090. 0x0243: { /* n:"BIFF3XF", */ },
  19091. 0x0406: { /* n:"Formula", */ f:parse_Formula },
  19092. 0x0409: { /* n:"BOF", */ f:parse_BOF },
  19093. 0x0443: { /* n:"BIFF4XF", */ },
  19094. 0x086d: { /* n:"FeatInfo", */ },
  19095. 0x0873: { /* n:"FeatInfo11", */ },
  19096. 0x0881: { /* n:"SXAddl12", */ },
  19097. 0x08c0: { /* n:"AutoWebPub", */ },
  19098. 0x08c1: { /* n:"ListObj", */ },
  19099. 0x08c2: { /* n:"ListField", */ },
  19100. 0x08c3: { /* n:"ListDV", */ },
  19101. 0x08c4: { /* n:"ListCondFmt", */ },
  19102. 0x08c5: { /* n:"ListCF", */ },
  19103. 0x08c6: { /* n:"FMQry", */ },
  19104. 0x08c7: { /* n:"FMSQry", */ },
  19105. 0x08c8: { /* n:"PLV", */ },
  19106. 0x08c9: { /* n:"LnExt", */ },
  19107. 0x08ca: { /* n:"MkrExt", */ },
  19108. 0x08cb: { /* n:"CrtCoopt", */ },
  19109. 0x08d6: { /* n:"FRTArchId$", */ r:12 },
  19110. 0x7262: {}
  19111. };
  19112. function write_biff_rec(ba, type, payload, length) {
  19113. var t = type;
  19114. if(isNaN(t)) return;
  19115. var len = length || (payload||[]).length || 0;
  19116. var o = ba.next(4);
  19117. o.write_shift(2, t);
  19118. o.write_shift(2, len);
  19119. if(len > 0 && is_buf(payload)) ba.push(payload);
  19120. }
  19121. function write_biff_continue(ba, type, payload, length) {
  19122. var len = length || (payload||[]).length || 0;
  19123. if(len <= 8224) return write_biff_rec(ba, type, payload, len);
  19124. var t = type;
  19125. if(isNaN(t)) return;
  19126. var parts = payload.parts || [], sidx = 0;
  19127. var i = 0, w = 0;
  19128. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  19129. var o = ba.next(4);
  19130. o.write_shift(2, t);
  19131. o.write_shift(2, w);
  19132. ba.push(payload.slice(i, i + w));
  19133. i += w;
  19134. while(i < len) {
  19135. o = ba.next(4);
  19136. o.write_shift(2, 0x3c); // TODO: figure out correct continue type
  19137. w = 0;
  19138. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  19139. o.write_shift(2, w);
  19140. ba.push(payload.slice(i, i+w)); i+= w;
  19141. }
  19142. }
  19143. function write_BIFF2Cell(out, r, c) {
  19144. if(!out) out = new_buf(7);
  19145. out.write_shift(2, r);
  19146. out.write_shift(2, c);
  19147. out.write_shift(2, 0);
  19148. out.write_shift(1, 0);
  19149. return out;
  19150. }
  19151. function write_BIFF2BERR(r, c, val, t) {
  19152. var out = new_buf(9);
  19153. write_BIFF2Cell(out, r, c);
  19154. write_Bes(val, t || 'b', out);
  19155. return out;
  19156. }
  19157. /* TODO: codepage, large strings */
  19158. function write_BIFF2LABEL(r, c, val) {
  19159. var out = new_buf(8 + 2*val.length);
  19160. write_BIFF2Cell(out, r, c);
  19161. out.write_shift(1, val.length);
  19162. out.write_shift(val.length, val, 'sbcs');
  19163. return out.l < out.length ? out.slice(0, out.l) : out;
  19164. }
  19165. function write_ws_biff2_cell(ba, cell, R, C) {
  19166. if(cell.v != null) switch(cell.t) {
  19167. case 'd': case 'n':
  19168. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  19169. if((v == (v|0)) && (v >= 0) && (v < 65536))
  19170. write_biff_rec(ba, 0x0002, write_BIFF2INT(R, C, v));
  19171. else
  19172. write_biff_rec(ba, 0x0003, write_BIFF2NUM(R,C, v));
  19173. return;
  19174. case 'b': case 'e': write_biff_rec(ba, 0x0005, write_BIFF2BERR(R, C, cell.v, cell.t)); return;
  19175. /* TODO: codepage, sst */
  19176. case 's': case 'str':
  19177. write_biff_rec(ba, 0x0004, write_BIFF2LABEL(R, C, (cell.v||"").slice(0,255)));
  19178. return;
  19179. }
  19180. write_biff_rec(ba, 0x0001, write_BIFF2Cell(null, R, C));
  19181. }
  19182. function write_ws_biff2(ba, ws, idx, opts) {
  19183. var dense = Array.isArray(ws);
  19184. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  19185. if(range.e.c > 0xFF || range.e.r > 0x3FFF) {
  19186. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  19187. range.e.c = Math.min(range.e.c, 0xFF);
  19188. range.e.r = Math.min(range.e.c, 0x3FFF);
  19189. ref = encode_range(range);
  19190. }
  19191. for(var R = range.s.r; R <= range.e.r; ++R) {
  19192. rr = encode_row(R);
  19193. for(var C = range.s.c; C <= range.e.c; ++C) {
  19194. if(R === range.s.r) cols[C] = encode_col(C);
  19195. ref = cols[C] + rr;
  19196. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  19197. if(!cell) continue;
  19198. /* write cell */
  19199. write_ws_biff2_cell(ba, cell, R, C, opts);
  19200. }
  19201. }
  19202. }
  19203. /* Based on test files */
  19204. function write_biff2_buf(wb, opts) {
  19205. var o = opts || {};
  19206. if(DENSE != null && o.dense == null) o.dense = DENSE;
  19207. var ba = buf_array();
  19208. var idx = 0;
  19209. for(var i=0;i<wb.SheetNames.length;++i) if(wb.SheetNames[i] == o.sheet) idx=i;
  19210. if(idx == 0 && !!o.sheet && wb.SheetNames[0] != o.sheet) throw new Error("Sheet not found: " + o.sheet);
  19211. write_biff_rec(ba, (o.biff == 4 ? 0x0409 : (o.biff == 3 ? 0x0209 : 0x0009)), write_BOF(wb, 0x10, o));
  19212. /* ... */
  19213. write_ws_biff2(ba, wb.Sheets[wb.SheetNames[idx]], idx, o, wb);
  19214. /* ... */
  19215. write_biff_rec(ba, 0x000A);
  19216. return ba.end();
  19217. }
  19218. function write_FONTS_biff8(ba, data, opts) {
  19219. write_biff_rec(ba, 0x0031 /* Font */, write_Font({
  19220. sz:12,
  19221. color: {theme:1},
  19222. name: "Arial",
  19223. family: 2,
  19224. scheme: "minor"
  19225. }, opts));
  19226. }
  19227. function write_FMTS_biff8(ba, NF, opts) {
  19228. if(!NF) return;
  19229. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  19230. 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));
  19231. });
  19232. }
  19233. function write_FEAT(ba, ws) {
  19234. /* [MS-XLS] 2.4.112 */
  19235. var o = new_buf(19);
  19236. o.write_shift(4, 0x867); o.write_shift(4, 0); o.write_shift(4, 0);
  19237. o.write_shift(2, 3); o.write_shift(1, 1); o.write_shift(4, 0);
  19238. write_biff_rec(ba, 0x0867 /* FeatHdr */, o);
  19239. /* [MS-XLS] 2.4.111 */
  19240. o = new_buf(39);
  19241. o.write_shift(4, 0x868); o.write_shift(4, 0); o.write_shift(4, 0);
  19242. o.write_shift(2, 3); o.write_shift(1, 0); o.write_shift(4, 0);
  19243. o.write_shift(2, 1); o.write_shift(4, 4); o.write_shift(2, 0);
  19244. write_Ref8U(safe_decode_range(ws['!ref']||"A1"), o);
  19245. o.write_shift(4, 4);
  19246. write_biff_rec(ba, 0x0868 /* Feat */, o);
  19247. }
  19248. function write_CELLXFS_biff8(ba, opts) {
  19249. for(var i = 0; i < 16; ++i) write_biff_rec(ba, 0x00e0 /* XF */, write_XF({numFmtId:0, style:true}, 0, opts));
  19250. opts.cellXfs.forEach(function(c) {
  19251. write_biff_rec(ba, 0x00e0 /* XF */, write_XF(c, 0, opts));
  19252. });
  19253. }
  19254. function write_ws_biff8_hlinks(ba, ws) {
  19255. for(var R=0; R<ws['!links'].length; ++R) {
  19256. var HL = ws['!links'][R];
  19257. write_biff_rec(ba, 0x01b8 /* HLink */, write_HLink(HL));
  19258. if(HL[1].Tooltip) write_biff_rec(ba, 0x0800 /* HLinkTooltip */, write_HLinkTooltip(HL));
  19259. }
  19260. delete ws['!links'];
  19261. }
  19262. function write_ws_cols_biff8(ba, cols) {
  19263. if(!cols) return;
  19264. var cnt = 0;
  19265. cols.forEach(function(col, idx) {
  19266. if(++cnt <= 256 && col) {
  19267. write_biff_rec(ba, 0x007d /* ColInfo */, write_ColInfo(col_obj_w(idx, col), idx));
  19268. }
  19269. });
  19270. }
  19271. function write_ws_biff8_cell(ba, cell, R, C, opts) {
  19272. var os = 16 + get_cell_style(opts.cellXfs, cell, opts);
  19273. if(cell.v == null && !cell.bf) {
  19274. write_biff_rec(ba, 0x0201 /* Blank */, write_XLSCell(R, C, os));
  19275. return;
  19276. }
  19277. if(cell.bf) write_biff_rec(ba, 0x0006 /* Formula */, write_Formula(cell, R, C, opts, os));
  19278. else switch(cell.t) {
  19279. case 'd': case 'n':
  19280. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  19281. /* TODO: emit RK as appropriate */
  19282. write_biff_rec(ba, 0x0203 /* Number */, write_Number(R, C, v, os, opts));
  19283. break;
  19284. case 'b': case 'e':
  19285. write_biff_rec(ba, 0x0205 /* BoolErr */, write_BoolErr(R, C, cell.v, os, opts, cell.t));
  19286. break;
  19287. /* TODO: codepage, sst */
  19288. case 's': case 'str':
  19289. if(opts.bookSST) {
  19290. var isst = get_sst_id(opts.Strings, cell.v, opts.revStrings);
  19291. write_biff_rec(ba, 0x00fd /* LabelSst */, write_LabelSst(R, C, isst, os, opts));
  19292. } else write_biff_rec(ba, 0x0204 /* Label */, write_Label(R, C, (cell.v||"").slice(0,255), os, opts));
  19293. break;
  19294. default:
  19295. write_biff_rec(ba, 0x0201 /* Blank */, write_XLSCell(R, C, os));
  19296. }
  19297. }
  19298. /* [MS-XLS] 2.1.7.20.5 */
  19299. function write_ws_biff8(idx, opts, wb) {
  19300. var ba = buf_array();
  19301. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  19302. var _WB = ((wb||{}).Workbook||{});
  19303. var _sheet = ((_WB.Sheets||[])[idx]||{});
  19304. var dense = Array.isArray(ws);
  19305. var b8 = opts.biff == 8;
  19306. var ref, rr = "", cols = [];
  19307. var range = safe_decode_range(ws['!ref'] || "A1");
  19308. var MAX_ROWS = b8 ? 65536 : 16384;
  19309. if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
  19310. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  19311. range.e.c = Math.min(range.e.c, 0xFF);
  19312. range.e.r = Math.min(range.e.c, MAX_ROWS-1);
  19313. }
  19314. write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
  19315. /* [Uncalced] Index */
  19316. write_biff_rec(ba, 0x000d /* CalcMode */, writeuint16(1));
  19317. write_biff_rec(ba, 0x000c /* CalcCount */, writeuint16(100));
  19318. write_biff_rec(ba, 0x000f /* CalcRefMode */, writebool(true));
  19319. write_biff_rec(ba, 0x0011 /* CalcIter */, writebool(false));
  19320. write_biff_rec(ba, 0x0010 /* CalcDelta */, write_Xnum(0.001));
  19321. write_biff_rec(ba, 0x005f /* CalcSaveRecalc */, writebool(true));
  19322. write_biff_rec(ba, 0x002a /* PrintRowCol */, writebool(false));
  19323. write_biff_rec(ba, 0x002b /* PrintGrid */, writebool(false));
  19324. write_biff_rec(ba, 0x0082 /* GridSet */, writeuint16(1));
  19325. write_biff_rec(ba, 0x0080 /* Guts */, write_Guts([0,0]));
  19326. /* DefaultRowHeight WsBool [Sync] [LPr] [HorizontalPageBreaks] [VerticalPageBreaks] */
  19327. /* Header (string) */
  19328. /* Footer (string) */
  19329. write_biff_rec(ba, 0x0083 /* HCenter */, writebool(false));
  19330. write_biff_rec(ba, 0x0084 /* VCenter */, writebool(false));
  19331. /* ... */
  19332. if(b8) write_ws_cols_biff8(ba, ws["!cols"]);
  19333. /* ... */
  19334. write_biff_rec(ba, 0x200, write_Dimensions(range, opts));
  19335. /* ... */
  19336. if(b8) ws['!links'] = [];
  19337. for(var R = range.s.r; R <= range.e.r; ++R) {
  19338. rr = encode_row(R);
  19339. for(var C = range.s.c; C <= range.e.c; ++C) {
  19340. if(R === range.s.r) cols[C] = encode_col(C);
  19341. ref = cols[C] + rr;
  19342. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  19343. if(!cell) continue;
  19344. /* write cell */
  19345. write_ws_biff8_cell(ba, cell, R, C, opts);
  19346. if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
  19347. }
  19348. }
  19349. var cname = _sheet.CodeName || _sheet.name || s;
  19350. /* ... */
  19351. if(b8) write_biff_rec(ba, 0x023e /* Window2 */, write_Window2((_WB.Views||[])[0]));
  19352. /* ... */
  19353. if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, 0x00e5 /* MergeCells */, write_MergeCells(ws['!merges']));
  19354. /* [LRng] *QUERYTABLE [PHONETICINFO] CONDFMTS */
  19355. if(b8) write_ws_biff8_hlinks(ba, ws);
  19356. /* [DVAL] */
  19357. write_biff_rec(ba, 0x01ba /* CodeName */, write_XLUnicodeString(cname, opts));
  19358. /* *WebPub *CellWatch [SheetExt] */
  19359. if(b8) write_FEAT(ba, ws);
  19360. /* *FEAT11 *RECORD12 */
  19361. write_biff_rec(ba, 0x000a /* EOF */);
  19362. return ba.end();
  19363. }
  19364. /* [MS-XLS] 2.1.7.20.3 */
  19365. function write_biff8_global(wb, bufs, opts) {
  19366. var A = buf_array();
  19367. var _WB = ((wb||{}).Workbook||{});
  19368. var _sheets = (_WB.Sheets||[]);
  19369. var _wb = _WB.WBProps||{};
  19370. var b8 = opts.biff == 8, b5 = opts.biff == 5;
  19371. write_biff_rec(A, 0x0809, write_BOF(wb, 0x05, opts));
  19372. if(opts.bookType == "xla") write_biff_rec(A, 0x0087 /* Addin */);
  19373. write_biff_rec(A, 0x00e1 /* InterfaceHdr */, b8 ? writeuint16(0x04b0) : null);
  19374. write_biff_rec(A, 0x00c1 /* Mms */, writezeroes(2));
  19375. if(b5) write_biff_rec(A, 0x00bf /* ToolbarHdr */);
  19376. if(b5) write_biff_rec(A, 0x00c0 /* ToolbarEnd */);
  19377. write_biff_rec(A, 0x00e2 /* InterfaceEnd */);
  19378. write_biff_rec(A, 0x005c /* WriteAccess */, write_WriteAccess("SheetJS", opts));
  19379. /* [FileSharing] */
  19380. write_biff_rec(A, 0x0042 /* CodePage */, writeuint16(b8 ? 0x04b0 : 0x04E4));
  19381. /* *2047 Lel */
  19382. if(b8) write_biff_rec(A, 0x0161 /* DSF */, writeuint16(0));
  19383. if(b8) write_biff_rec(A, 0x01c0 /* Excel9File */);
  19384. write_biff_rec(A, 0x013d /* RRTabId */, write_RRTabId(wb.SheetNames.length));
  19385. if(b8 && wb.vbaraw) write_biff_rec(A, 0x00d3 /* ObProj */);
  19386. /* [ObNoMacros] */
  19387. if(b8 && wb.vbaraw) {
  19388. var cname = _wb.CodeName || "ThisWorkbook";
  19389. write_biff_rec(A, 0x01ba /* CodeName */, write_XLUnicodeString(cname, opts));
  19390. }
  19391. write_biff_rec(A, 0x009c /* BuiltInFnGroupCount */, writeuint16(0x11));
  19392. /* *FnGroupName *FnGrp12 */
  19393. /* *Lbl */
  19394. /* [OleObjectSize] */
  19395. write_biff_rec(A, 0x0019 /* WinProtect */, writebool(false));
  19396. write_biff_rec(A, 0x0012 /* Protect */, writebool(false));
  19397. write_biff_rec(A, 0x0013 /* Password */, writeuint16(0));
  19398. if(b8) write_biff_rec(A, 0x01af /* Prot4Rev */, writebool(false));
  19399. if(b8) write_biff_rec(A, 0x01bc /* Prot4RevPass */, writeuint16(0));
  19400. write_biff_rec(A, 0x003d /* Window1 */, write_Window1(opts));
  19401. write_biff_rec(A, 0x0040 /* Backup */, writebool(false));
  19402. write_biff_rec(A, 0x008d /* HideObj */, writeuint16(0));
  19403. write_biff_rec(A, 0x0022 /* Date1904 */, writebool(safe1904(wb)=="true"));
  19404. write_biff_rec(A, 0x000e /* CalcPrecision */, writebool(true));
  19405. if(b8) write_biff_rec(A, 0x01b7 /* RefreshAll */, writebool(false));
  19406. write_biff_rec(A, 0x00DA /* BookBool */, writeuint16(0));
  19407. /* ... */
  19408. write_FONTS_biff8(A, wb, opts);
  19409. write_FMTS_biff8(A, wb.SSF, opts);
  19410. write_CELLXFS_biff8(A, opts);
  19411. /* ... */
  19412. if(b8) write_biff_rec(A, 0x0160 /* UsesELFs */, writebool(false));
  19413. var a = A.end();
  19414. var C = buf_array();
  19415. /* METADATA [MTRSettings] [ForceFullCalculation] */
  19416. if(b8) write_biff_rec(C, 0x008C, write_Country());
  19417. /* *SUPBOOK *LBL *RTD [RecalcId] *HFPicture *MSODRAWINGGROUP */
  19418. /* BIFF8: [SST *Continue] ExtSST */
  19419. if(b8 && opts.Strings) write_biff_continue(C, 0x00FC, write_SST(opts.Strings, opts));
  19420. /* *WebPub [WOpt] [CrErr] [BookExt] *FeatHdr *DConn [THEME] [CompressPictures] [Compat12] [GUIDTypeLib] */
  19421. write_biff_rec(C, 0x000A /* EOF */);
  19422. var c = C.end();
  19423. var B = buf_array();
  19424. var blen = 0, j = 0;
  19425. for(j = 0; j < wb.SheetNames.length; ++j) blen += (b8 ? 12 : 11) + (b8 ? 2 : 1) * wb.SheetNames[j].length;
  19426. var start = a.length + blen + c.length;
  19427. for(j = 0; j < wb.SheetNames.length; ++j) {
  19428. var _sheet = _sheets[j] || ({});
  19429. write_biff_rec(B, 0x0085 /* BoundSheet8 */, write_BoundSheet8({pos:start, hs:_sheet.Hidden||0, dt:0, name:wb.SheetNames[j]}, opts));
  19430. start += bufs[j].length;
  19431. }
  19432. /* 1*BoundSheet8 */
  19433. var b = B.end();
  19434. if(blen != b.length) throw new Error("BS8 " + blen + " != " + b.length);
  19435. var out = [];
  19436. if(a.length) out.push(a);
  19437. if(b.length) out.push(b);
  19438. if(c.length) out.push(c);
  19439. return bconcat(out);
  19440. }
  19441. /* [MS-XLS] 2.1.7.20 Workbook Stream */
  19442. function write_biff8_buf(wb, opts) {
  19443. var o = opts || {};
  19444. var bufs = [];
  19445. if(wb && !wb.SSF) {
  19446. wb.SSF = dup(table_fmt);
  19447. }
  19448. if(wb && wb.SSF) {
  19449. make_ssf(); SSF_load_table(wb.SSF);
  19450. // $FlowIgnore
  19451. o.revssf = evert_num(wb.SSF); o.revssf[wb.SSF[65535]] = 0;
  19452. o.ssf = wb.SSF;
  19453. }
  19454. o.Strings = []; o.Strings.Count = 0; o.Strings.Unique = 0;
  19455. fix_write_opts(o);
  19456. o.cellXfs = [];
  19457. get_cell_style(o.cellXfs, {}, {revssf:{"General":0}});
  19458. if(!wb.Props) wb.Props = {};
  19459. for(var i = 0; i < wb.SheetNames.length; ++i) bufs[bufs.length] = write_ws_biff8(i, o, wb);
  19460. bufs.unshift(write_biff8_global(wb, bufs, o));
  19461. return bconcat(bufs);
  19462. }
  19463. function write_biff_buf(wb, opts) {
  19464. for(var i = 0; i <= wb.SheetNames.length; ++i) {
  19465. var ws = wb.Sheets[wb.SheetNames[i]];
  19466. if(!ws || !ws["!ref"]) continue;
  19467. var range = decode_range(ws["!ref"]);
  19468. if(range.e.c > 255) { // note: 255 is IV
  19469. if(typeof console != "undefined" && console.error) console.error("Worksheet '" + wb.SheetNames[i] + "' extends beyond column IV (255). Data may be lost.");
  19470. }
  19471. }
  19472. var o = opts || {};
  19473. switch(o.biff || 2) {
  19474. case 8: case 5: return write_biff8_buf(wb, opts);
  19475. case 4: case 3: case 2: return write_biff2_buf(wb, opts);
  19476. }
  19477. throw new Error("invalid type " + o.bookType + " for BIFF");
  19478. }
  19479. /* note: browser DOM element cannot see mso- style attrs, must parse */
  19480. function html_to_sheet(str, _opts) {
  19481. var opts = _opts || {};
  19482. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  19483. var ws = opts.dense ? ([]) : ({});
  19484. str = str.replace(/<!--.*?-->/g, "");
  19485. var mtch = str.match(/<table/i);
  19486. if(!mtch) throw new Error("Invalid HTML: could not find <table>");
  19487. var mtch2 = str.match(/<\/table/i);
  19488. var i = mtch.index, j = mtch2 && mtch2.index || str.length;
  19489. var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
  19490. var R = -1, C = 0, RS = 0, CS = 0;
  19491. var range = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
  19492. var merges = [];
  19493. for(i = 0; i < rows.length; ++i) {
  19494. var row = rows[i].trim();
  19495. var hd = row.slice(0,3).toLowerCase();
  19496. if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
  19497. if(hd != "<td" && hd != "<th") continue;
  19498. var cells = row.split(/<\/t[dh]>/i);
  19499. for(j = 0; j < cells.length; ++j) {
  19500. var cell = cells[j].trim();
  19501. if(!cell.match(/<t[dh]/i)) continue;
  19502. var m = cell, cc = 0;
  19503. /* TODO: parse styles etc */
  19504. while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
  19505. for(var midx = 0; midx < merges.length; ++midx) {
  19506. var _merge = merges[midx];
  19507. if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
  19508. }
  19509. var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
  19510. CS = tag.colspan ? +tag.colspan : 1;
  19511. if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
  19512. var _t = tag.t || tag["data-t"] || "";
  19513. /* TODO: generate stub cells */
  19514. if(!m.length) { C += CS; continue; }
  19515. m = htmldecode(m);
  19516. if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
  19517. if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
  19518. if(!m.length) { C += CS; continue; }
  19519. var o = {t:'s', v:m};
  19520. if(opts.raw || !m.trim().length || _t == 's'){}
  19521. else if(m === 'TRUE') o = {t:'b', v:true};
  19522. else if(m === 'FALSE') o = {t:'b', v:false};
  19523. else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
  19524. else if(!isNaN(fuzzydate(m).getDate())) {
  19525. o = ({t:'d', v:parseDate(m)});
  19526. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  19527. o.z = opts.dateNF || table_fmt[14];
  19528. }
  19529. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
  19530. else ws[encode_cell({r:R, c:C})] = o;
  19531. C += CS;
  19532. }
  19533. }
  19534. ws['!ref'] = encode_range(range);
  19535. if(merges.length) ws["!merges"] = merges;
  19536. return ws;
  19537. }
  19538. function make_html_row(ws, r, R, o) {
  19539. var M = (ws['!merges'] ||[]);
  19540. var oo = [];
  19541. for(var C = r.s.c; C <= r.e.c; ++C) {
  19542. var RS = 0, CS = 0;
  19543. for(var j = 0; j < M.length; ++j) {
  19544. if(M[j].s.r > R || M[j].s.c > C) continue;
  19545. if(M[j].e.r < R || M[j].e.c < C) continue;
  19546. if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
  19547. RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
  19548. }
  19549. if(RS < 0) continue;
  19550. var coord = encode_cell({r:R,c:C});
  19551. var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
  19552. /* TODO: html entities */
  19553. var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
  19554. var sp = ({});
  19555. if(RS > 1) sp.rowspan = RS;
  19556. if(CS > 1) sp.colspan = CS;
  19557. if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
  19558. else if(cell) {
  19559. sp["data-t"] = cell && cell.t || 'z';
  19560. if(cell.v != null) sp["data-v"] = cell.v;
  19561. if(cell.z != null) sp["data-z"] = cell.z;
  19562. if(cell.l && (cell.l.Target || "#").charAt(0) != "#") w = '<a href="' + cell.l.Target +'">' + w + '</a>';
  19563. }
  19564. sp.id = (o.id || "sjs") + "-" + coord;
  19565. oo.push(writextag('td', w, sp));
  19566. }
  19567. var preamble = "<tr>";
  19568. return preamble + oo.join("") + "</tr>";
  19569. }
  19570. var HTML_BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
  19571. var HTML_END = '</body></html>';
  19572. function html_to_workbook(str, opts) {
  19573. var mtch = str.match(/<table[\s\S]*?>[\s\S]*?<\/table>/gi);
  19574. if(!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find <table>");
  19575. if(mtch.length == 1) return sheet_to_workbook(html_to_sheet(mtch[0], opts), opts);
  19576. var wb = book_new();
  19577. mtch.forEach(function(s, idx) { book_append_sheet(wb, html_to_sheet(s, opts), "Sheet" + (idx+1)); });
  19578. return wb;
  19579. }
  19580. function make_html_preamble(ws, R, o) {
  19581. var out = [];
  19582. return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
  19583. }
  19584. function sheet_to_html(ws, opts/*, wb:?Workbook*/) {
  19585. var o = opts || {};
  19586. var header = o.header != null ? o.header : HTML_BEGIN;
  19587. var footer = o.footer != null ? o.footer : HTML_END;
  19588. var out = [header];
  19589. var r = decode_range(ws['!ref']);
  19590. o.dense = Array.isArray(ws);
  19591. out.push(make_html_preamble(ws, r, o));
  19592. for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
  19593. out.push("</table>" + footer);
  19594. return out.join("");
  19595. }
  19596. function sheet_add_dom(ws, table, _opts) {
  19597. var opts = _opts || {};
  19598. if(DENSE != null) opts.dense = DENSE;
  19599. var or_R = 0, or_C = 0;
  19600. if(opts.origin != null) {
  19601. if(typeof opts.origin == 'number') or_R = opts.origin;
  19602. else {
  19603. var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
  19604. or_R = _origin.r; or_C = _origin.c;
  19605. }
  19606. }
  19607. var rows = table.getElementsByTagName('tr');
  19608. var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
  19609. var range = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
  19610. if(ws["!ref"]) {
  19611. var _range = decode_range(ws["!ref"]);
  19612. range.s.r = Math.min(range.s.r, _range.s.r);
  19613. range.s.c = Math.min(range.s.c, _range.s.c);
  19614. range.e.r = Math.max(range.e.r, _range.e.r);
  19615. range.e.c = Math.max(range.e.c, _range.e.c);
  19616. if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
  19617. }
  19618. var merges = [], midx = 0;
  19619. var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  19620. var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  19621. if(!ws["!cols"]) ws['!cols'] = [];
  19622. for(; _R < rows.length && R < sheetRows; ++_R) {
  19623. var row = rows[_R];
  19624. if (is_dom_element_hidden(row)) {
  19625. if (opts.display) continue;
  19626. rowinfo[R] = {hidden: true};
  19627. }
  19628. var elts = (row.children);
  19629. for(_C = C = 0; _C < elts.length; ++_C) {
  19630. var elt = elts[_C];
  19631. if (opts.display && is_dom_element_hidden(elt)) continue;
  19632. var v = elt.hasAttribute('data-v') ? elt.getAttribute('data-v') : elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
  19633. var z = elt.getAttribute('data-z') || elt.getAttribute('z');
  19634. for(midx = 0; midx < merges.length; ++midx) {
  19635. var m = merges[midx];
  19636. 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; }
  19637. }
  19638. /* TODO: figure out how to extract nonstandard mso- style */
  19639. CS = +elt.getAttribute("colspan") || 1;
  19640. 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}});
  19641. var o = {t:'s', v:v};
  19642. var _t = elt.getAttribute("data-t") || elt.getAttribute("t") || "";
  19643. if(v != null) {
  19644. if(v.length == 0) o.t = _t || 'z';
  19645. else if(opts.raw || v.trim().length == 0 || _t == "s"){}
  19646. else if(v === 'TRUE') o = {t:'b', v:true};
  19647. else if(v === 'FALSE') o = {t:'b', v:false};
  19648. else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
  19649. else if(!isNaN(fuzzydate(v).getDate())) {
  19650. o = ({t:'d', v:parseDate(v)});
  19651. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  19652. o.z = opts.dateNF || table_fmt[14];
  19653. }
  19654. }
  19655. if(o.z === undefined && z != null) o.z = z;
  19656. /* The first link is used. Links are assumed to be fully specified.
  19657. * TODO: The right way to undefined relative links is to make a new <a> */
  19658. var l = "", Aelts = elt.getElementsByTagName("A");
  19659. if(Aelts && Aelts.length) for(var Aelti = 0; Aelti < Aelts.length; ++Aelti) if(Aelts[Aelti].hasAttribute("href")) {
  19660. l = Aelts[Aelti].getAttribute("href"); if(l.charAt(0) != "#") break;
  19661. }
  19662. if(l && l.charAt(0) != "#") o.l = ({ Target: l });
  19663. if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
  19664. else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
  19665. if(range.e.c < C + or_C) range.e.c = C + or_C;
  19666. C += CS;
  19667. }
  19668. ++R;
  19669. }
  19670. if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
  19671. range.e.r = Math.max(range.e.r, R - 1 + or_R);
  19672. ws['!ref'] = encode_range(range);
  19673. 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
  19674. return ws;
  19675. }
  19676. function parse_dom_table(table, _opts) {
  19677. var opts = _opts || {};
  19678. var ws = opts.dense ? ([]) : ({});
  19679. return sheet_add_dom(ws, table, _opts);
  19680. }
  19681. function table_to_book(table, opts) {
  19682. return sheet_to_workbook(parse_dom_table(table, opts), opts);
  19683. }
  19684. function is_dom_element_hidden(element) {
  19685. var display = '';
  19686. var get_computed_style = get_get_computed_style_function(element);
  19687. if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
  19688. if(!display) display = element.style && element.style.display;
  19689. return display === 'none';
  19690. }
  19691. /* global getComputedStyle */
  19692. function get_get_computed_style_function(element) {
  19693. // The proper getComputedStyle implementation is the one defined in the element window
  19694. if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
  19695. // If it is not available, try to get one from the global namespace
  19696. if(typeof getComputedStyle === 'function') return getComputedStyle;
  19697. return null;
  19698. }
  19699. /* OpenDocument */
  19700. function parse_text_p(text) {
  19701. /* 6.1.2 White Space Characters */
  19702. var fixed = text
  19703. .replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ")
  19704. .replace(/<text:s\/>/g," ")
  19705. .replace(/<text:s text:c="(\d+)"\/>/g, function($$,$1) { return Array(parseInt($1,10)+1).join(" "); })
  19706. .replace(/<text:tab[^>]*\/>/g,"\t")
  19707. .replace(/<text:line-break\/>/g,"\n");
  19708. var v = unescapexml(fixed.replace(/<[^>]*>/g,""));
  19709. return [v];
  19710. }
  19711. var number_formats_ods = {
  19712. /* ods name: [short ssf fmt, long ssf fmt] */
  19713. day: ["d", "dd"],
  19714. month: ["m", "mm"],
  19715. year: ["y", "yy"],
  19716. hours: ["h", "hh"],
  19717. minutes: ["m", "mm"],
  19718. seconds: ["s", "ss"],
  19719. "am-pm": ["A/P", "AM/PM"],
  19720. "day-of-week": ["ddd", "dddd"],
  19721. era: ["e", "ee"],
  19722. /* there is no native representation of LO "Q" format */
  19723. quarter: ["\\Qm", "m\\\"th quarter\""]
  19724. };
  19725. function parse_content_xml(d, _opts) {
  19726. var opts = _opts || {};
  19727. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  19728. var str = xlml_normalize(d);
  19729. var state = [], tmp;
  19730. var tag;
  19731. var NFtag = {name:""}, NF = "", pidx = 0;
  19732. var sheetag;
  19733. var rowtag;
  19734. var Sheets = {}, SheetNames = [];
  19735. var ws = opts.dense ? ([]) : ({});
  19736. var Rn, q;
  19737. var ctag = ({value:""});
  19738. var textp = "", textpidx = 0, textptag;
  19739. var textR = [];
  19740. var R = -1, C = -1, range = {s: {r:1000000,c:10000000}, e: {r:0, c:0}};
  19741. var row_ol = 0;
  19742. var number_format_map = {};
  19743. var merges = [], mrange = {}, mR = 0, mC = 0;
  19744. var rowinfo = [], rowpeat = 1, colpeat = 1;
  19745. var arrayf = [];
  19746. var WB = {Names:[]};
  19747. var atag = ({});
  19748. var _Ref = ["", ""];
  19749. var comments = [], comment = ({});
  19750. var creator = "", creatoridx = 0;
  19751. var isstub = false, intable = false;
  19752. var i = 0;
  19753. xlmlregex.lastIndex = 0;
  19754. str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  19755. while((Rn = xlmlregex.exec(str))) switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {
  19756. case 'table': case '工作表': // 9.1.2 <table:table>
  19757. if(Rn[1]==='/') {
  19758. if(range.e.c >= range.s.c && range.e.r >= range.s.r) ws['!ref'] = encode_range(range);
  19759. else ws['!ref'] = "A1:A1";
  19760. if(opts.sheetRows > 0 && opts.sheetRows <= range.e.r) {
  19761. ws['!fullref'] = ws['!ref'];
  19762. range.e.r = opts.sheetRows - 1;
  19763. ws['!ref'] = encode_range(range);
  19764. }
  19765. if(merges.length) ws['!merges'] = merges;
  19766. if(rowinfo.length) ws["!rows"] = rowinfo;
  19767. sheetag.name = sheetag['名称'] || sheetag.name;
  19768. if(typeof JSON !== 'undefined') JSON.stringify(sheetag);
  19769. SheetNames.push(sheetag.name);
  19770. Sheets[sheetag.name] = ws;
  19771. intable = false;
  19772. }
  19773. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  19774. sheetag = parsexmltag(Rn[0], false);
  19775. R = C = -1;
  19776. range.s.r = range.s.c = 10000000; range.e.r = range.e.c = 0;
  19777. ws = opts.dense ? ([]) : ({}); merges = [];
  19778. rowinfo = [];
  19779. intable = true;
  19780. }
  19781. break;
  19782. case 'table-row-group': // 9.1.9 <table:table-row-group>
  19783. if(Rn[1] === "/") --row_ol; else ++row_ol;
  19784. break;
  19785. case 'table-row': case '行': // 9.1.3 <table:table-row>
  19786. if(Rn[1] === '/') { R+=rowpeat; rowpeat = 1; break; }
  19787. rowtag = parsexmltag(Rn[0], false);
  19788. if(rowtag['行号']) R = rowtag['行号'] - 1; else if(R == -1) R = 0;
  19789. rowpeat = +rowtag['number-rows-repeated'] || 1;
  19790. /* TODO: remove magic */
  19791. if(rowpeat < 10) for(i = 0; i < rowpeat; ++i) if(row_ol > 0) rowinfo[R + i] = {level: row_ol};
  19792. C = -1; break;
  19793. case 'covered-table-cell': // 9.1.5 <table:covered-table-cell>
  19794. if(Rn[1] !== '/') ++C;
  19795. if(opts.sheetStubs) {
  19796. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = {t:'z'}; }
  19797. else ws[encode_cell({r:R,c:C})] = {t:'z'};
  19798. }
  19799. textp = ""; textR = [];
  19800. break; /* stub */
  19801. case 'table-cell': case '数据':
  19802. if(Rn[0].charAt(Rn[0].length-2) === '/') {
  19803. ++C;
  19804. ctag = parsexmltag(Rn[0], false);
  19805. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  19806. q = ({t:'z', v:null});
  19807. if(ctag.formula && opts.cellFormula != false) q.f = ods_to_csf_formula(unescapexml(ctag.formula));
  19808. if((ctag['数据类型'] || ctag['value-type']) == "string") {
  19809. q.t = "s"; q.v = unescapexml(ctag['string-value'] || "");
  19810. if(opts.dense) {
  19811. if(!ws[R]) ws[R] = [];
  19812. ws[R][C] = q;
  19813. } else {
  19814. ws[encode_cell({r:R,c:C})] = q;
  19815. }
  19816. }
  19817. C+= colpeat-1;
  19818. } else if(Rn[1]!=='/') {
  19819. ++C;
  19820. textp = ""; textpidx = 0; textR = [];
  19821. colpeat = 1;
  19822. var rptR = rowpeat ? R + rowpeat - 1 : R;
  19823. if(C > range.e.c) range.e.c = C;
  19824. if(C < range.s.c) range.s.c = C;
  19825. if(R < range.s.r) range.s.r = R;
  19826. if(rptR > range.e.r) range.e.r = rptR;
  19827. ctag = parsexmltag(Rn[0], false);
  19828. comments = []; comment = ({});
  19829. q = ({t:ctag['数据类型'] || ctag['value-type'], v:null});
  19830. if(opts.cellFormula) {
  19831. if(ctag.formula) ctag.formula = unescapexml(ctag.formula);
  19832. if(ctag['number-matrix-columns-spanned'] && ctag['number-matrix-rows-spanned']) {
  19833. mR = parseInt(ctag['number-matrix-rows-spanned'],10) || 0;
  19834. mC = parseInt(ctag['number-matrix-columns-spanned'],10) || 0;
  19835. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  19836. q.F = encode_range(mrange);
  19837. arrayf.push([mrange, q.F]);
  19838. }
  19839. if(ctag.formula) q.f = ods_to_csf_formula(ctag.formula);
  19840. else for(i = 0; i < arrayf.length; ++i)
  19841. if(R >= arrayf[i][0].s.r && R <= arrayf[i][0].e.r)
  19842. if(C >= arrayf[i][0].s.c && C <= arrayf[i][0].e.c)
  19843. q.F = arrayf[i][1];
  19844. }
  19845. if(ctag['number-columns-spanned'] || ctag['number-rows-spanned']) {
  19846. mR = parseInt(ctag['number-rows-spanned'],10) || 0;
  19847. mC = parseInt(ctag['number-columns-spanned'],10) || 0;
  19848. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  19849. merges.push(mrange);
  19850. }
  19851. /* 19.675.2 table:number-columns-repeated */
  19852. if(ctag['number-columns-repeated']) colpeat = parseInt(ctag['number-columns-repeated'], 10);
  19853. /* 19.385 office:value-type */
  19854. switch(q.t) {
  19855. case 'boolean': q.t = 'b'; q.v = parsexmlbool(ctag['boolean-value']); break;
  19856. case 'float': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  19857. case 'percentage': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  19858. case 'currency': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  19859. case 'date': q.t = 'd'; q.v = parseDate(ctag['date-value']);
  19860. if(!opts.cellDates) { q.t = 'n'; q.v = datenum(q.v); }
  19861. q.z = 'm/d/yy'; break;
  19862. case 'time': q.t = 'n'; q.v = parse_isodur(ctag['time-value'])/86400;
  19863. if(opts.cellDates) { q.t = 'd'; q.v = numdate(q.v); }
  19864. q.z = 'HH:MM:SS'; break;
  19865. case 'number': q.t = 'n'; q.v = parseFloat(ctag['数据数值']); break;
  19866. default:
  19867. if(q.t === 'string' || q.t === 'text' || !q.t) {
  19868. q.t = 's';
  19869. if(ctag['string-value'] != null) { textp = unescapexml(ctag['string-value']); textR = []; }
  19870. } else throw new Error('Unsupported value type ' + q.t);
  19871. }
  19872. } else {
  19873. isstub = false;
  19874. if(q.t === 's') {
  19875. q.v = textp || '';
  19876. if(textR.length) q.R = textR;
  19877. isstub = textpidx == 0;
  19878. }
  19879. if(atag.Target) q.l = atag;
  19880. if(comments.length > 0) { q.c = comments; comments = []; }
  19881. if(textp && opts.cellText !== false) q.w = textp;
  19882. if(isstub) { q.t = "z"; delete q.v; }
  19883. if(!isstub || opts.sheetStubs) {
  19884. if(!(opts.sheetRows && opts.sheetRows <= R)) {
  19885. for(var rpt = 0; rpt < rowpeat; ++rpt) {
  19886. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  19887. if(opts.dense) {
  19888. if(!ws[R + rpt]) ws[R + rpt] = [];
  19889. ws[R + rpt][C] = rpt == 0 ? q : dup(q);
  19890. while(--colpeat > 0) ws[R + rpt][C + colpeat] = dup(q);
  19891. } else {
  19892. ws[encode_cell({r:R + rpt,c:C})] = q;
  19893. while(--colpeat > 0) ws[encode_cell({r:R + rpt,c:C + colpeat})] = dup(q);
  19894. }
  19895. if(range.e.c <= C) range.e.c = C;
  19896. }
  19897. }
  19898. }
  19899. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  19900. C += colpeat-1; colpeat = 0;
  19901. q = {};
  19902. textp = ""; textR = [];
  19903. }
  19904. atag = ({});
  19905. break; // 9.1.4 <table:table-cell>
  19906. /* pure state */
  19907. case 'document': // TODO: <office:document> is the root for FODS
  19908. case 'document-content': case '电子表格文档': // 3.1.3.2 <office:document-content>
  19909. case 'spreadsheet': case '主体': // 3.7 <office:spreadsheet>
  19910. case 'scripts': // 3.12 <office:scripts>
  19911. case 'styles': // TODO <office:styles>
  19912. case 'font-face-decls': // 3.14 <office:font-face-decls>
  19913. case 'master-styles': // 3.15.4 <office:master-styles> -- relevant for FODS
  19914. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  19915. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  19916. break;
  19917. case 'annotation': // 14.1 <office:annotation>
  19918. if(Rn[1]==='/'){
  19919. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  19920. comment.t = textp;
  19921. if(textR.length) comment.R = textR;
  19922. comment.a = creator;
  19923. comments.push(comment);
  19924. }
  19925. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {state.push([Rn[3], false]);}
  19926. creator = ""; creatoridx = 0;
  19927. textp = ""; textpidx = 0; textR = [];
  19928. break;
  19929. case 'creator': // 4.3.2.7 <dc:creator>
  19930. if(Rn[1]==='/') { creator = str.slice(creatoridx,Rn.index); }
  19931. else creatoridx = Rn.index + Rn[0].length;
  19932. break;
  19933. /* ignore state */
  19934. case 'meta': case '元数据': // TODO: <office:meta> <uof:元数据> FODS/UOF
  19935. case 'settings': // TODO: <office:settings>
  19936. case 'config-item-set': // TODO: <office:config-item-set>
  19937. case 'config-item-map-indexed': // TODO: <office:config-item-map-indexed>
  19938. case 'config-item-map-entry': // TODO: <office:config-item-map-entry>
  19939. case 'config-item-map-named': // TODO: <office:config-item-map-entry>
  19940. case 'shapes': // 9.2.8 <table:shapes>
  19941. case 'frame': // 10.4.2 <draw:frame>
  19942. case 'text-box': // 10.4.3 <draw:text-box>
  19943. case 'image': // 10.4.4 <draw:image>
  19944. case 'data-pilot-tables': // 9.6.2 <table:data-pilot-tables>
  19945. case 'list-style': // 16.30 <text:list-style>
  19946. case 'form': // 13.13 <form:form>
  19947. case 'dde-links': // 9.8 <table:dde-links>
  19948. case 'event-listeners': // TODO
  19949. case 'chart': // TODO
  19950. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  19951. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], false]);
  19952. textp = ""; textpidx = 0; textR = [];
  19953. break;
  19954. case 'scientific-number': // TODO: <number:scientific-number>
  19955. break;
  19956. case 'currency-symbol': // TODO: <number:currency-symbol>
  19957. break;
  19958. case 'currency-style': // TODO: <number:currency-style>
  19959. break;
  19960. case 'number-style': // 16.27.2 <number:number-style>
  19961. case 'percentage-style': // 16.27.9 <number:percentage-style>
  19962. case 'date-style': // 16.27.10 <number:date-style>
  19963. case 'time-style': // 16.27.18 <number:time-style>
  19964. if(Rn[1]==='/'){
  19965. number_format_map[NFtag.name] = NF;
  19966. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  19967. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  19968. NF = "";
  19969. NFtag = parsexmltag(Rn[0], false);
  19970. state.push([Rn[3], true]);
  19971. } break;
  19972. case 'script': break; // 3.13 <office:script>
  19973. case 'libraries': break; // TODO: <ooo:libraries>
  19974. case 'automatic-styles': break; // 3.15.3 <office:automatic-styles>
  19975. case 'default-style': // TODO: <style:default-style>
  19976. case 'page-layout': break; // TODO: <style:page-layout>
  19977. case 'style': // 16.2 <style:style>
  19978. break;
  19979. case 'map': break; // 16.3 <style:map>
  19980. case 'font-face': break; // 16.21 <style:font-face>
  19981. case 'paragraph-properties': break; // 17.6 <style:paragraph-properties>
  19982. case 'table-properties': break; // 17.15 <style:table-properties>
  19983. case 'table-column-properties': break; // 17.16 <style:table-column-properties>
  19984. case 'table-row-properties': break; // 17.17 <style:table-row-properties>
  19985. case 'table-cell-properties': break; // 17.18 <style:table-cell-properties>
  19986. case 'number': // 16.27.3 <number:number>
  19987. switch(state[state.length-1][0]) {
  19988. case 'time-style':
  19989. case 'date-style':
  19990. tag = parsexmltag(Rn[0], false);
  19991. NF += number_formats_ods[Rn[3]][tag.style==='long'?1:0]; break;
  19992. } break;
  19993. case 'fraction': break; // TODO 16.27.6 <number:fraction>
  19994. case 'day': // 16.27.11 <number:day>
  19995. case 'month': // 16.27.12 <number:month>
  19996. case 'year': // 16.27.13 <number:year>
  19997. case 'era': // 16.27.14 <number:era>
  19998. case 'day-of-week': // 16.27.15 <number:day-of-week>
  19999. case 'week-of-year': // 16.27.16 <number:week-of-year>
  20000. case 'quarter': // 16.27.17 <number:quarter>
  20001. case 'hours': // 16.27.19 <number:hours>
  20002. case 'minutes': // 16.27.20 <number:minutes>
  20003. case 'seconds': // 16.27.21 <number:seconds>
  20004. case 'am-pm': // 16.27.22 <number:am-pm>
  20005. switch(state[state.length-1][0]) {
  20006. case 'time-style':
  20007. case 'date-style':
  20008. tag = parsexmltag(Rn[0], false);
  20009. NF += number_formats_ods[Rn[3]][tag.style==='long'?1:0]; break;
  20010. } break;
  20011. case 'boolean-style': break; // 16.27.23 <number:boolean-style>
  20012. case 'boolean': break; // 16.27.24 <number:boolean>
  20013. case 'text-style': break; // 16.27.25 <number:text-style>
  20014. case 'text': // 16.27.26 <number:text>
  20015. if(Rn[0].slice(-2) === "/>") break;
  20016. else if(Rn[1]==="/") switch(state[state.length-1][0]) {
  20017. case 'number-style':
  20018. case 'date-style':
  20019. case 'time-style':
  20020. NF += str.slice(pidx, Rn.index);
  20021. break;
  20022. }
  20023. else pidx = Rn.index + Rn[0].length;
  20024. break;
  20025. case 'named-range': // 9.4.12 <table:named-range>
  20026. tag = parsexmltag(Rn[0], false);
  20027. _Ref = ods_to_csf_3D(tag['cell-range-address']);
  20028. var nrange = ({Name:tag.name, Ref:_Ref[0] + '!' + _Ref[1]});
  20029. if(intable) nrange.Sheet = SheetNames.length;
  20030. WB.Names.push(nrange);
  20031. break;
  20032. case 'text-content': break; // 16.27.27 <number:text-content>
  20033. case 'text-properties': break; // 16.27.27 <style:text-properties>
  20034. case 'embedded-text': break; // 16.27.4 <number:embedded-text>
  20035. case 'body': case '电子表格': break; // 3.3 16.9.6 19.726.3
  20036. case 'forms': break; // 12.25.2 13.2
  20037. case 'table-column': break; // 9.1.6 <table:table-column>
  20038. case 'table-header-rows': break; // 9.1.7 <table:table-header-rows>
  20039. case 'table-rows': break; // 9.1.12 <table:table-rows>
  20040. /* TODO: outline levels */
  20041. case 'table-column-group': break; // 9.1.10 <table:table-column-group>
  20042. case 'table-header-columns': break; // 9.1.11 <table:table-header-columns>
  20043. case 'table-columns': break; // 9.1.12 <table:table-columns>
  20044. case 'null-date': break; // 9.4.2 <table:null-date> TODO: date1904
  20045. case 'graphic-properties': break; // 17.21 <style:graphic-properties>
  20046. case 'calculation-settings': break; // 9.4.1 <table:calculation-settings>
  20047. case 'named-expressions': break; // 9.4.11 <table:named-expressions>
  20048. case 'label-range': break; // 9.4.9 <table:label-range>
  20049. case 'label-ranges': break; // 9.4.10 <table:label-ranges>
  20050. case 'named-expression': break; // 9.4.13 <table:named-expression>
  20051. case 'sort': break; // 9.4.19 <table:sort>
  20052. case 'sort-by': break; // 9.4.20 <table:sort-by>
  20053. case 'sort-groups': break; // 9.4.22 <table:sort-groups>
  20054. case 'tab': break; // 6.1.4 <text:tab>
  20055. case 'line-break': break; // 6.1.5 <text:line-break>
  20056. case 'span': break; // 6.1.7 <text:span>
  20057. case 'p': case '文本串': // 5.1.3 <text:p>
  20058. if(['master-styles'].indexOf(state[state.length-1][0]) > -1) break;
  20059. if(Rn[1]==='/' && (!ctag || !ctag['string-value'])) {
  20060. var ptp = parse_text_p(str.slice(textpidx,Rn.index), textptag);
  20061. textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
  20062. } else { textptag = parsexmltag(Rn[0], false); textpidx = Rn.index + Rn[0].length; }
  20063. break; // <text:p>
  20064. case 's': break; // <text:s>
  20065. case 'database-range': // 9.4.15 <table:database-range>
  20066. if(Rn[1]==='/') break;
  20067. try {
  20068. _Ref = ods_to_csf_3D(parsexmltag(Rn[0])['target-range-address']);
  20069. Sheets[_Ref[0]]['!autofilter'] = { ref:_Ref[1] };
  20070. } catch(e) {/* empty */}
  20071. break;
  20072. case 'date': break; // <*:date>
  20073. case 'object': break; // 10.4.6.2 <draw:object>
  20074. case 'title': case '标题': break; // <*:title> OR <uof:标题>
  20075. case 'desc': break; // <*:desc>
  20076. case 'binary-data': break; // 10.4.5 TODO: b64 blob
  20077. /* 9.2 Advanced Tables */
  20078. case 'table-source': break; // 9.2.6
  20079. case 'scenario': break; // 9.2.6
  20080. case 'iteration': break; // 9.4.3 <table:iteration>
  20081. case 'content-validations': break; // 9.4.4 <table:
  20082. case 'content-validation': break; // 9.4.5 <table:
  20083. case 'help-message': break; // 9.4.6 <table:
  20084. case 'error-message': break; // 9.4.7 <table:
  20085. case 'database-ranges': break; // 9.4.14 <table:database-ranges>
  20086. case 'filter': break; // 9.5.2 <table:filter>
  20087. case 'filter-and': break; // 9.5.3 <table:filter-and>
  20088. case 'filter-or': break; // 9.5.4 <table:filter-or>
  20089. case 'filter-condition': break; // 9.5.5 <table:filter-condition>
  20090. case 'list-level-style-bullet': break; // 16.31 <text:
  20091. case 'list-level-style-number': break; // 16.32 <text:
  20092. case 'list-level-properties': break; // 17.19 <style:
  20093. /* 7.3 Document Fields */
  20094. case 'sender-firstname': // 7.3.6.2
  20095. case 'sender-lastname': // 7.3.6.3
  20096. case 'sender-initials': // 7.3.6.4
  20097. case 'sender-title': // 7.3.6.5
  20098. case 'sender-position': // 7.3.6.6
  20099. case 'sender-email': // 7.3.6.7
  20100. case 'sender-phone-private': // 7.3.6.8
  20101. case 'sender-fax': // 7.3.6.9
  20102. case 'sender-company': // 7.3.6.10
  20103. case 'sender-phone-work': // 7.3.6.11
  20104. case 'sender-street': // 7.3.6.12
  20105. case 'sender-city': // 7.3.6.13
  20106. case 'sender-postal-code': // 7.3.6.14
  20107. case 'sender-country': // 7.3.6.15
  20108. case 'sender-state-or-province': // 7.3.6.16
  20109. case 'author-name': // 7.3.7.1
  20110. case 'author-initials': // 7.3.7.2
  20111. case 'chapter': // 7.3.8
  20112. case 'file-name': // 7.3.9
  20113. case 'template-name': // 7.3.9
  20114. case 'sheet-name': // 7.3.9
  20115. break;
  20116. case 'event-listener':
  20117. break;
  20118. /* TODO: FODS Properties */
  20119. case 'initial-creator':
  20120. case 'creation-date':
  20121. case 'print-date':
  20122. case 'generator':
  20123. case 'document-statistic':
  20124. case 'user-defined':
  20125. case 'editing-duration':
  20126. case 'editing-cycles':
  20127. break;
  20128. /* TODO: FODS Config */
  20129. case 'config-item':
  20130. break;
  20131. /* TODO: style tokens */
  20132. case 'page-number': break; // TODO <text:page-number>
  20133. case 'page-count': break; // TODO <text:page-count>
  20134. case 'time': break; // TODO <text:time>
  20135. /* 9.3 Advanced Table Cells */
  20136. case 'cell-range-source': break; // 9.3.1 <table:
  20137. case 'detective': break; // 9.3.2 <table:
  20138. case 'operation': break; // 9.3.3 <table:
  20139. case 'highlighted-range': break; // 9.3.4 <table:
  20140. /* 9.6 Data Pilot Tables <table: */
  20141. case 'data-pilot-table': // 9.6.3
  20142. case 'source-cell-range': // 9.6.5
  20143. case 'source-service': // 9.6.6
  20144. case 'data-pilot-field': // 9.6.7
  20145. case 'data-pilot-level': // 9.6.8
  20146. case 'data-pilot-subtotals': // 9.6.9
  20147. case 'data-pilot-subtotal': // 9.6.10
  20148. case 'data-pilot-members': // 9.6.11
  20149. case 'data-pilot-member': // 9.6.12
  20150. case 'data-pilot-display-info': // 9.6.13
  20151. case 'data-pilot-sort-info': // 9.6.14
  20152. case 'data-pilot-layout-info': // 9.6.15
  20153. case 'data-pilot-field-reference': // 9.6.16
  20154. case 'data-pilot-groups': // 9.6.17
  20155. case 'data-pilot-group': // 9.6.18
  20156. case 'data-pilot-group-member': // 9.6.19
  20157. break;
  20158. /* 10.3 Drawing Shapes */
  20159. case 'rect': // 10.3.2
  20160. break;
  20161. /* 14.6 DDE Connections */
  20162. case 'dde-connection-decls': // 14.6.2 <text:
  20163. case 'dde-connection-decl': // 14.6.3 <text:
  20164. case 'dde-link': // 14.6.4 <table:
  20165. case 'dde-source': // 14.6.5 <office:
  20166. break;
  20167. case 'properties': break; // 13.7 <form:properties>
  20168. case 'property': break; // 13.8 <form:property>
  20169. case 'a': // 6.1.8 hyperlink
  20170. if(Rn[1]!== '/') {
  20171. atag = parsexmltag(Rn[0], false);
  20172. if(!atag.href) break;
  20173. atag.Target = unescapexml(atag.href); delete atag.href;
  20174. if(atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
  20175. _Ref = ods_to_csf_3D(atag.Target.slice(1));
  20176. atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
  20177. } else if(atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3);
  20178. }
  20179. break;
  20180. /* non-standard */
  20181. case 'table-protection': break;
  20182. case 'data-pilot-grand-total': break; // <table:
  20183. case 'office-document-common-attrs': break; // bare
  20184. default: switch(Rn[2]) {
  20185. case 'dc:': // TODO: properties
  20186. case 'calcext:': // ignore undocumented extensions
  20187. case 'loext:': // ignore undocumented extensions
  20188. case 'ooo:': // ignore undocumented extensions
  20189. case 'chartooo:': // ignore undocumented extensions
  20190. case 'draw:': // TODO: drawing
  20191. case 'style:': // TODO: styles
  20192. case 'chart:': // TODO: charts
  20193. case 'form:': // TODO: forms
  20194. case 'uof:': // TODO: uof
  20195. case '表:': // TODO: uof
  20196. case '字:': // TODO: uof
  20197. break;
  20198. default: if(opts.WTF) throw new Error(Rn);
  20199. }
  20200. }
  20201. var out = ({
  20202. Sheets: Sheets,
  20203. SheetNames: SheetNames,
  20204. Workbook: WB
  20205. });
  20206. if(opts.bookSheets) delete out.Sheets;
  20207. return out;
  20208. }
  20209. function parse_ods(zip, opts) {
  20210. opts = opts || ({});
  20211. if(safegetzipfile(zip, 'META-INF/manifest.xml')) parse_manifest(getzipdata(zip, 'META-INF/manifest.xml'), opts);
  20212. var content = getzipstr(zip, 'content.xml');
  20213. if(!content) throw new Error("Missing content.xml in ODS / UOF file");
  20214. var wb = parse_content_xml(utf8read(content), opts);
  20215. if(safegetzipfile(zip, 'meta.xml')) wb.Props = parse_core_props(getzipdata(zip, 'meta.xml'));
  20216. return wb;
  20217. }
  20218. function parse_fods(data, opts) {
  20219. return parse_content_xml(data, opts);
  20220. }
  20221. /* OpenDocument */
  20222. var write_styles_ods = /* @__PURE__ */(function() {
  20223. var master_styles = [
  20224. '<office:master-styles>',
  20225. '<style:master-page style:name="mp1" style:page-layout-name="mp1">',
  20226. '<style:header/>',
  20227. '<style:header-left style:display="false"/>',
  20228. '<style:footer/>',
  20229. '<style:footer-left style:display="false"/>',
  20230. '</style:master-page>',
  20231. '</office:master-styles>'
  20232. ].join("");
  20233. var payload = '<office:document-styles ' + wxt_helper({
  20234. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  20235. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  20236. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  20237. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  20238. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  20239. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  20240. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  20241. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  20242. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  20243. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  20244. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  20245. 'office:version': "1.2"
  20246. }) + '>' + master_styles + '</office:document-styles>';
  20247. return function wso() {
  20248. return XML_HEADER + payload;
  20249. };
  20250. })();
  20251. var write_content_ods = /* @__PURE__ */(function() {
  20252. /* 6.1.2 White Space Characters */
  20253. var write_text_p = function(text) {
  20254. return escapexml(text)
  20255. .replace(/ +/g, function($$){return '<text:s text:c="'+$$.length+'"/>';})
  20256. .replace(/\t/g, "<text:tab/>")
  20257. .replace(/\n/g, "</text:p><text:p>")
  20258. .replace(/^ /, "<text:s/>").replace(/ $/, "<text:s/>");
  20259. };
  20260. var null_cell_xml = ' <table:table-cell />\n';
  20261. var covered_cell_xml = ' <table:covered-table-cell/>\n';
  20262. var write_ws = function(ws, wb, i) {
  20263. /* Section 9 Tables */
  20264. var o = [];
  20265. o.push(' <table:table table:name="' + escapexml(wb.SheetNames[i]) + '" table:style-name="ta1">\n');
  20266. var R=0,C=0, range = decode_range(ws['!ref']||"A1");
  20267. var marr = ws['!merges'] || [], mi = 0;
  20268. var dense = Array.isArray(ws);
  20269. if(ws["!cols"]) {
  20270. 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');
  20271. }
  20272. var H = "", ROWS = ws["!rows"]||[];
  20273. for(R = 0; R < range.s.r; ++R) {
  20274. H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
  20275. o.push(' <table:table-row' + H + '></table:table-row>\n');
  20276. }
  20277. for(; R <= range.e.r; ++R) {
  20278. H = ROWS[R] ? ' table:style-name="ro' + ROWS[R].ods + '"' : "";
  20279. o.push(' <table:table-row' + H + '>\n');
  20280. for(C=0; C < range.s.c; ++C) o.push(null_cell_xml);
  20281. for(; C <= range.e.c; ++C) {
  20282. var skip = false, ct = {}, textp = "";
  20283. for(mi = 0; mi != marr.length; ++mi) {
  20284. if(marr[mi].s.c > C) continue;
  20285. if(marr[mi].s.r > R) continue;
  20286. if(marr[mi].e.c < C) continue;
  20287. if(marr[mi].e.r < R) continue;
  20288. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  20289. ct['table:number-columns-spanned'] = (marr[mi].e.c - marr[mi].s.c + 1);
  20290. ct['table:number-rows-spanned'] = (marr[mi].e.r - marr[mi].s.r + 1);
  20291. break;
  20292. }
  20293. if(skip) { o.push(covered_cell_xml); continue; }
  20294. var ref = encode_cell({r:R, c:C}), cell = dense ? (ws[R]||[])[C]: ws[ref];
  20295. if(cell && cell.f) {
  20296. ct['table:formula'] = escapexml(csf_to_ods_formula(cell.f));
  20297. if(cell.F) {
  20298. if(cell.F.slice(0, ref.length) == ref) {
  20299. var _Fref = decode_range(cell.F);
  20300. ct['table:number-matrix-columns-spanned'] = (_Fref.e.c - _Fref.s.c + 1);
  20301. ct['table:number-matrix-rows-spanned'] = (_Fref.e.r - _Fref.s.r + 1);
  20302. }
  20303. }
  20304. }
  20305. if(!cell) { o.push(null_cell_xml); continue; }
  20306. switch(cell.t) {
  20307. case 'b':
  20308. textp = (cell.v ? 'TRUE' : 'FALSE');
  20309. ct['office:value-type'] = "boolean";
  20310. ct['office:boolean-value'] = (cell.v ? 'true' : 'false');
  20311. break;
  20312. case 'n':
  20313. textp = (cell.w||String(cell.v||0));
  20314. ct['office:value-type'] = "float";
  20315. ct['office:value'] = (cell.v||0);
  20316. break;
  20317. case 's': case 'str':
  20318. textp = cell.v == null ? "" : cell.v;
  20319. ct['office:value-type'] = "string";
  20320. break;
  20321. case 'd':
  20322. textp = (cell.w||(parseDate(cell.v).toISOString()));
  20323. ct['office:value-type'] = "date";
  20324. ct['office:date-value'] = (parseDate(cell.v).toISOString());
  20325. ct['table:style-name'] = "ce1";
  20326. break;
  20327. //case 'e':
  20328. default: o.push(null_cell_xml); continue;
  20329. }
  20330. var text_p = write_text_p(textp);
  20331. if(cell.l && cell.l.Target) {
  20332. var _tgt = cell.l.Target;
  20333. _tgt = _tgt.charAt(0) == "#" ? "#" + csf_to_ods_3D(_tgt.slice(1)) : _tgt;
  20334. // TODO: choose correct parent path format based on link delimiters
  20335. if(_tgt.charAt(0) != "#" && !_tgt.match(/^\w+:/)) _tgt = '../' + _tgt;
  20336. text_p = writextag('text:a', text_p, {'xlink:href': _tgt.replace(/&/g, "&amp;")});
  20337. }
  20338. o.push(' ' + writextag('table:table-cell', writextag('text:p', text_p, {}), ct) + '\n');
  20339. }
  20340. o.push(' </table:table-row>\n');
  20341. }
  20342. o.push(' </table:table>\n');
  20343. return o.join("");
  20344. };
  20345. var write_automatic_styles_ods = function(o, wb) {
  20346. o.push(' <office:automatic-styles>\n');
  20347. o.push(' <number:date-style style:name="N37" number:automatic-order="true">\n');
  20348. o.push(' <number:month number:style="long"/>\n');
  20349. o.push(' <number:text>/</number:text>\n');
  20350. o.push(' <number:day number:style="long"/>\n');
  20351. o.push(' <number:text>/</number:text>\n');
  20352. o.push(' <number:year/>\n');
  20353. o.push(' </number:date-style>\n');
  20354. /* column styles */
  20355. var cidx = 0;
  20356. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  20357. if(!ws) return;
  20358. if(ws["!cols"]) {
  20359. for(var C = 0; C < ws["!cols"].length; ++C) if(ws["!cols"][C]) {
  20360. var colobj = ws["!cols"][C];
  20361. if(colobj.width == null && colobj.wpx == null && colobj.wch == null) continue;
  20362. process_col(colobj);
  20363. colobj.ods = cidx;
  20364. var w = ws["!cols"][C].wpx + "px";
  20365. o.push(' <style:style style:name="co' + cidx + '" style:family="table-column">\n');
  20366. o.push(' <style:table-column-properties fo:break-before="auto" style:column-width="' + w + '"/>\n');
  20367. o.push(' </style:style>\n');
  20368. ++cidx;
  20369. }
  20370. }
  20371. });
  20372. /* row styles */
  20373. var ridx = 0;
  20374. wb.SheetNames.map(function(n) { return wb.Sheets[n]; }).forEach(function(ws) {
  20375. if(!ws) return;
  20376. if(ws["!rows"]) {
  20377. for(var R = 0; R < ws["!rows"].length; ++R) if(ws["!rows"][R]) {
  20378. ws["!rows"][R].ods = ridx;
  20379. var h = ws["!rows"][R].hpx + "px";
  20380. o.push(' <style:style style:name="ro' + ridx + '" style:family="table-row">\n');
  20381. o.push(' <style:table-row-properties fo:break-before="auto" style:row-height="' + h + '"/>\n');
  20382. o.push(' </style:style>\n');
  20383. ++ridx;
  20384. }
  20385. }
  20386. });
  20387. /* table */
  20388. o.push(' <style:style style:name="ta1" style:family="table" style:master-page-name="mp1">\n');
  20389. o.push(' <style:table-properties table:display="true" style:writing-mode="lr-tb"/>\n');
  20390. o.push(' </style:style>\n');
  20391. /* table cells, text */
  20392. o.push(' <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N37"/>\n');
  20393. /* page-layout */
  20394. o.push(' </office:automatic-styles>\n');
  20395. };
  20396. return function wcx(wb, opts) {
  20397. var o = [XML_HEADER];
  20398. /* 3.1.3.2 */
  20399. var attr = wxt_helper({
  20400. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  20401. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  20402. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  20403. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  20404. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  20405. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  20406. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  20407. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  20408. 'xmlns:meta': "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
  20409. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  20410. 'xmlns:presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
  20411. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  20412. 'xmlns:chart': "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
  20413. 'xmlns:dr3d': "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
  20414. 'xmlns:math': "http://www.w3.org/1998/Math/MathML",
  20415. 'xmlns:form': "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
  20416. 'xmlns:script': "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
  20417. 'xmlns:ooo': "http://openoffice.org/2004/office",
  20418. 'xmlns:ooow': "http://openoffice.org/2004/writer",
  20419. 'xmlns:oooc': "http://openoffice.org/2004/calc",
  20420. 'xmlns:dom': "http://www.w3.org/2001/xml-events",
  20421. 'xmlns:xforms': "http://www.w3.org/2002/xforms",
  20422. 'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
  20423. 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
  20424. 'xmlns:sheet': "urn:oasis:names:tc:opendocument:sh33tjs:1.0",
  20425. 'xmlns:rpt': "http://openoffice.org/2005/report",
  20426. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  20427. 'xmlns:xhtml': "http://www.w3.org/1999/xhtml",
  20428. 'xmlns:grddl': "http://www.w3.org/2003/g/data-view#",
  20429. 'xmlns:tableooo': "http://openoffice.org/2009/table",
  20430. 'xmlns:drawooo': "http://openoffice.org/2010/draw",
  20431. 'xmlns:calcext': "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
  20432. 'xmlns:loext': "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
  20433. 'xmlns:field': "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
  20434. 'xmlns:formx': "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
  20435. 'xmlns:css3t': "http://www.w3.org/TR/css3-text/",
  20436. 'office:version': "1.2"
  20437. });
  20438. var fods = wxt_helper({
  20439. 'xmlns:config': "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
  20440. 'office:mimetype': "application/vnd.oasis.opendocument.spreadsheet"
  20441. });
  20442. if(opts.bookType == "fods") {
  20443. o.push('<office:document' + attr + fods + '>\n');
  20444. o.push(write_meta_ods().replace(/office:document-meta/g, "office:meta"));
  20445. // TODO: settings (equiv of settings.xml for ODS)
  20446. } else o.push('<office:document-content' + attr + '>\n');
  20447. // o.push(' <office:scripts/>\n');
  20448. write_automatic_styles_ods(o, wb);
  20449. o.push(' <office:body>\n');
  20450. o.push(' <office:spreadsheet>\n');
  20451. for(var i = 0; i != wb.SheetNames.length; ++i) o.push(write_ws(wb.Sheets[wb.SheetNames[i]], wb, i, opts));
  20452. o.push(' </office:spreadsheet>\n');
  20453. o.push(' </office:body>\n');
  20454. if(opts.bookType == "fods") o.push('</office:document>');
  20455. else o.push('</office:document-content>');
  20456. return o.join("");
  20457. };
  20458. })();
  20459. function write_ods(wb, opts) {
  20460. if(opts.bookType == "fods") return write_content_ods(wb, opts);
  20461. var zip = zip_new();
  20462. var f = "";
  20463. var manifest = [];
  20464. var rdf = [];
  20465. /* Part 3 Section 3.3 MIME Media Type */
  20466. f = "mimetype";
  20467. zip_add_file(zip, f, "application/vnd.oasis.opendocument.spreadsheet");
  20468. /* Part 1 Section 2.2 Documents */
  20469. f = "content.xml";
  20470. zip_add_file(zip, f, write_content_ods(wb, opts));
  20471. manifest.push([f, "text/xml"]);
  20472. rdf.push([f, "ContentFile"]);
  20473. /* TODO: these are hard-coded styles to satiate excel */
  20474. f = "styles.xml";
  20475. zip_add_file(zip, f, write_styles_ods(wb, opts));
  20476. manifest.push([f, "text/xml"]);
  20477. rdf.push([f, "StylesFile"]);
  20478. /* TODO: this is hard-coded to satiate excel */
  20479. f = "meta.xml";
  20480. zip_add_file(zip, f, XML_HEADER + write_meta_ods());
  20481. manifest.push([f, "text/xml"]);
  20482. rdf.push([f, "MetadataFile"]);
  20483. /* Part 3 Section 6 Metadata Manifest File */
  20484. f = "manifest.rdf";
  20485. zip_add_file(zip, f, write_rdf(rdf/*, opts*/));
  20486. manifest.push([f, "application/rdf+xml"]);
  20487. /* Part 3 Section 4 Manifest File */
  20488. f = "META-INF/manifest.xml";
  20489. zip_add_file(zip, f, write_manifest(manifest/*, opts*/));
  20490. return zip;
  20491. }
  20492. /*! sheetjs (C) 2013-present SheetJS -- http://sheetjs.com */
  20493. function u8_to_dataview(array) {
  20494. return new DataView(array.buffer, array.byteOffset, array.byteLength);
  20495. }
  20496. function u8str(u8) {
  20497. return typeof TextDecoder != "undefined" ? new TextDecoder().decode(u8) : utf8read(a2s(u8));
  20498. }
  20499. function stru8(str) {
  20500. return typeof TextEncoder != "undefined" ? new TextEncoder().encode(str) : s2a(utf8write(str));
  20501. }
  20502. function u8contains(body, search) {
  20503. outer:
  20504. for (var L = 0; L <= body.length - search.length; ++L) {
  20505. for (var j = 0; j < search.length; ++j)
  20506. if (body[L + j] != search[j])
  20507. continue outer;
  20508. return true;
  20509. }
  20510. return false;
  20511. }
  20512. function u8concat(u8a) {
  20513. var len = u8a.reduce(function(acc, x) {
  20514. return acc + x.length;
  20515. }, 0);
  20516. var out = new Uint8Array(len);
  20517. var off = 0;
  20518. u8a.forEach(function(u8) {
  20519. out.set(u8, off);
  20520. off += u8.length;
  20521. });
  20522. return out;
  20523. }
  20524. function popcnt(x) {
  20525. x -= x >> 1 & 1431655765;
  20526. x = (x & 858993459) + (x >> 2 & 858993459);
  20527. return (x + (x >> 4) & 252645135) * 16843009 >>> 24;
  20528. }
  20529. function readDecimal128LE(buf, offset) {
  20530. var exp = (buf[offset + 15] & 127) << 7 | buf[offset + 14] >> 1;
  20531. var mantissa = buf[offset + 14] & 1;
  20532. for (var j = offset + 13; j >= offset; --j)
  20533. mantissa = mantissa * 256 + buf[j];
  20534. return (buf[offset + 15] & 128 ? -mantissa : mantissa) * Math.pow(10, exp - 6176);
  20535. }
  20536. function writeDecimal128LE(buf, offset, value) {
  20537. var exp = Math.floor(value == 0 ? 0 : Math.LOG10E * Math.log(Math.abs(value))) + 6176 - 20;
  20538. var mantissa = value / Math.pow(10, exp - 6176);
  20539. buf[offset + 15] |= exp >> 7;
  20540. buf[offset + 14] |= (exp & 127) << 1;
  20541. for (var i = 0; mantissa >= 1; ++i, mantissa /= 256)
  20542. buf[offset + i] = mantissa & 255;
  20543. buf[offset + 15] |= value >= 0 ? 0 : 128;
  20544. }
  20545. function parse_varint49(buf, ptr) {
  20546. var l = ptr ? ptr[0] : 0;
  20547. var usz = buf[l] & 127;
  20548. varint:
  20549. if (buf[l++] >= 128) {
  20550. usz |= (buf[l] & 127) << 7;
  20551. if (buf[l++] < 128)
  20552. break varint;
  20553. usz |= (buf[l] & 127) << 14;
  20554. if (buf[l++] < 128)
  20555. break varint;
  20556. usz |= (buf[l] & 127) << 21;
  20557. if (buf[l++] < 128)
  20558. break varint;
  20559. usz += (buf[l] & 127) * Math.pow(2, 28);
  20560. ++l;
  20561. if (buf[l++] < 128)
  20562. break varint;
  20563. usz += (buf[l] & 127) * Math.pow(2, 35);
  20564. ++l;
  20565. if (buf[l++] < 128)
  20566. break varint;
  20567. usz += (buf[l] & 127) * Math.pow(2, 42);
  20568. ++l;
  20569. if (buf[l++] < 128)
  20570. break varint;
  20571. }
  20572. if (ptr)
  20573. ptr[0] = l;
  20574. return usz;
  20575. }
  20576. function write_varint49(v) {
  20577. var usz = new Uint8Array(7);
  20578. usz[0] = v & 127;
  20579. var L = 1;
  20580. sz:
  20581. if (v > 127) {
  20582. usz[L - 1] |= 128;
  20583. usz[L] = v >> 7 & 127;
  20584. ++L;
  20585. if (v <= 16383)
  20586. break sz;
  20587. usz[L - 1] |= 128;
  20588. usz[L] = v >> 14 & 127;
  20589. ++L;
  20590. if (v <= 2097151)
  20591. break sz;
  20592. usz[L - 1] |= 128;
  20593. usz[L] = v >> 21 & 127;
  20594. ++L;
  20595. if (v <= 268435455)
  20596. break sz;
  20597. usz[L - 1] |= 128;
  20598. usz[L] = v / 256 >>> 21 & 127;
  20599. ++L;
  20600. if (v <= 34359738367)
  20601. break sz;
  20602. usz[L - 1] |= 128;
  20603. usz[L] = v / 65536 >>> 21 & 127;
  20604. ++L;
  20605. if (v <= 4398046511103)
  20606. break sz;
  20607. usz[L - 1] |= 128;
  20608. usz[L] = v / 16777216 >>> 21 & 127;
  20609. ++L;
  20610. }
  20611. return usz.slice(0, L);
  20612. }
  20613. function varint_to_i32(buf) {
  20614. var l = 0, i32 = buf[l] & 127;
  20615. varint:
  20616. if (buf[l++] >= 128) {
  20617. i32 |= (buf[l] & 127) << 7;
  20618. if (buf[l++] < 128)
  20619. break varint;
  20620. i32 |= (buf[l] & 127) << 14;
  20621. if (buf[l++] < 128)
  20622. break varint;
  20623. i32 |= (buf[l] & 127) << 21;
  20624. if (buf[l++] < 128)
  20625. break varint;
  20626. i32 |= (buf[l] & 127) << 28;
  20627. }
  20628. return i32;
  20629. }
  20630. function parse_shallow(buf) {
  20631. var out = [], ptr = [0];
  20632. while (ptr[0] < buf.length) {
  20633. var off = ptr[0];
  20634. var num = parse_varint49(buf, ptr);
  20635. var type = num & 7;
  20636. num = Math.floor(num / 8);
  20637. var len = 0;
  20638. var res;
  20639. if (num == 0)
  20640. break;
  20641. switch (type) {
  20642. case 0:
  20643. {
  20644. var l = ptr[0];
  20645. while (buf[ptr[0]++] >= 128)
  20646. ;
  20647. res = buf.slice(l, ptr[0]);
  20648. }
  20649. break;
  20650. case 5:
  20651. len = 4;
  20652. res = buf.slice(ptr[0], ptr[0] + len);
  20653. ptr[0] += len;
  20654. break;
  20655. case 1:
  20656. len = 8;
  20657. res = buf.slice(ptr[0], ptr[0] + len);
  20658. ptr[0] += len;
  20659. break;
  20660. case 2:
  20661. len = parse_varint49(buf, ptr);
  20662. res = buf.slice(ptr[0], ptr[0] + len);
  20663. ptr[0] += len;
  20664. break;
  20665. case 3:
  20666. case 4:
  20667. default:
  20668. throw new Error("PB Type ".concat(type, " for Field ").concat(num, " at offset ").concat(off));
  20669. }
  20670. var v = { data: res, type: type };
  20671. if (out[num] == null)
  20672. out[num] = [v];
  20673. else
  20674. out[num].push(v);
  20675. }
  20676. return out;
  20677. }
  20678. function write_shallow(proto) {
  20679. var out = [];
  20680. proto.forEach(function(field, idx) {
  20681. field.forEach(function(item) {
  20682. if (!item.data)
  20683. return;
  20684. out.push(write_varint49(idx * 8 + item.type));
  20685. if (item.type == 2)
  20686. out.push(write_varint49(item.data.length));
  20687. out.push(item.data);
  20688. });
  20689. });
  20690. return u8concat(out);
  20691. }
  20692. function mappa(data, cb) {
  20693. return (data == null ? void 0 : data.map(function(d) {
  20694. return cb(d.data);
  20695. })) || [];
  20696. }
  20697. function parse_iwa_file(buf) {
  20698. var _a;
  20699. var out = [], ptr = [0];
  20700. while (ptr[0] < buf.length) {
  20701. var len = parse_varint49(buf, ptr);
  20702. var ai = parse_shallow(buf.slice(ptr[0], ptr[0] + len));
  20703. ptr[0] += len;
  20704. var res = {
  20705. id: varint_to_i32(ai[1][0].data),
  20706. messages: []
  20707. };
  20708. ai[2].forEach(function(b) {
  20709. var mi = parse_shallow(b.data);
  20710. var fl = varint_to_i32(mi[3][0].data);
  20711. res.messages.push({
  20712. meta: mi,
  20713. data: buf.slice(ptr[0], ptr[0] + fl)
  20714. });
  20715. ptr[0] += fl;
  20716. });
  20717. if ((_a = ai[3]) == null ? void 0 : _a[0])
  20718. res.merge = varint_to_i32(ai[3][0].data) >>> 0 > 0;
  20719. out.push(res);
  20720. }
  20721. return out;
  20722. }
  20723. function write_iwa_file(ias) {
  20724. var bufs = [];
  20725. ias.forEach(function(ia) {
  20726. var ai = [];
  20727. ai[1] = [{ data: write_varint49(ia.id), type: 0 }];
  20728. ai[2] = [];
  20729. if (ia.merge != null)
  20730. ai[3] = [{ data: write_varint49(+!!ia.merge), type: 0 }];
  20731. var midata = [];
  20732. ia.messages.forEach(function(mi) {
  20733. midata.push(mi.data);
  20734. mi.meta[3] = [{ type: 0, data: write_varint49(mi.data.length) }];
  20735. ai[2].push({ data: write_shallow(mi.meta), type: 2 });
  20736. });
  20737. var aipayload = write_shallow(ai);
  20738. bufs.push(write_varint49(aipayload.length));
  20739. bufs.push(aipayload);
  20740. midata.forEach(function(mid) {
  20741. return bufs.push(mid);
  20742. });
  20743. });
  20744. return u8concat(bufs);
  20745. }
  20746. function parse_snappy_chunk(type, buf) {
  20747. if (type != 0)
  20748. throw new Error("Unexpected Snappy chunk type ".concat(type));
  20749. var ptr = [0];
  20750. var usz = parse_varint49(buf, ptr);
  20751. var chunks = [];
  20752. while (ptr[0] < buf.length) {
  20753. var tag = buf[ptr[0]] & 3;
  20754. if (tag == 0) {
  20755. var len = buf[ptr[0]++] >> 2;
  20756. if (len < 60)
  20757. ++len;
  20758. else {
  20759. var c = len - 59;
  20760. len = buf[ptr[0]];
  20761. if (c > 1)
  20762. len |= buf[ptr[0] + 1] << 8;
  20763. if (c > 2)
  20764. len |= buf[ptr[0] + 2] << 16;
  20765. if (c > 3)
  20766. len |= buf[ptr[0] + 3] << 24;
  20767. len >>>= 0;
  20768. len++;
  20769. ptr[0] += c;
  20770. }
  20771. chunks.push(buf.slice(ptr[0], ptr[0] + len));
  20772. ptr[0] += len;
  20773. continue;
  20774. } else {
  20775. var offset = 0, length = 0;
  20776. if (tag == 1) {
  20777. length = (buf[ptr[0]] >> 2 & 7) + 4;
  20778. offset = (buf[ptr[0]++] & 224) << 3;
  20779. offset |= buf[ptr[0]++];
  20780. } else {
  20781. length = (buf[ptr[0]++] >> 2) + 1;
  20782. if (tag == 2) {
  20783. offset = buf[ptr[0]] | buf[ptr[0] + 1] << 8;
  20784. ptr[0] += 2;
  20785. } else {
  20786. offset = (buf[ptr[0]] | buf[ptr[0] + 1] << 8 | buf[ptr[0] + 2] << 16 | buf[ptr[0] + 3] << 24) >>> 0;
  20787. ptr[0] += 4;
  20788. }
  20789. }
  20790. chunks = [u8concat(chunks)];
  20791. if (offset == 0)
  20792. throw new Error("Invalid offset 0");
  20793. if (offset > chunks[0].length)
  20794. throw new Error("Invalid offset beyond length");
  20795. if (length >= offset) {
  20796. chunks.push(chunks[0].slice(-offset));
  20797. length -= offset;
  20798. while (length >= chunks[chunks.length - 1].length) {
  20799. chunks.push(chunks[chunks.length - 1]);
  20800. length -= chunks[chunks.length - 1].length;
  20801. }
  20802. }
  20803. chunks.push(chunks[0].slice(-offset, -offset + length));
  20804. }
  20805. }
  20806. var o = u8concat(chunks);
  20807. if (o.length != usz)
  20808. throw new Error("Unexpected length: ".concat(o.length, " != ").concat(usz));
  20809. return o;
  20810. }
  20811. function decompress_iwa_file(buf) {
  20812. var out = [];
  20813. var l = 0;
  20814. while (l < buf.length) {
  20815. var t = buf[l++];
  20816. var len = buf[l] | buf[l + 1] << 8 | buf[l + 2] << 16;
  20817. l += 3;
  20818. out.push(parse_snappy_chunk(t, buf.slice(l, l + len)));
  20819. l += len;
  20820. }
  20821. if (l !== buf.length)
  20822. throw new Error("data is not a valid framed stream!");
  20823. return u8concat(out);
  20824. }
  20825. function compress_iwa_file(buf) {
  20826. var out = [];
  20827. var l = 0;
  20828. while (l < buf.length) {
  20829. var c = Math.min(buf.length - l, 268435455);
  20830. var frame = new Uint8Array(4);
  20831. out.push(frame);
  20832. var usz = write_varint49(c);
  20833. var L = usz.length;
  20834. out.push(usz);
  20835. if (c <= 60) {
  20836. L++;
  20837. out.push(new Uint8Array([c - 1 << 2]));
  20838. } else if (c <= 256) {
  20839. L += 2;
  20840. out.push(new Uint8Array([240, c - 1 & 255]));
  20841. } else if (c <= 65536) {
  20842. L += 3;
  20843. out.push(new Uint8Array([244, c - 1 & 255, c - 1 >> 8 & 255]));
  20844. } else if (c <= 16777216) {
  20845. L += 4;
  20846. out.push(new Uint8Array([248, c - 1 & 255, c - 1 >> 8 & 255, c - 1 >> 16 & 255]));
  20847. } else if (c <= 4294967296) {
  20848. L += 5;
  20849. out.push(new Uint8Array([252, c - 1 & 255, c - 1 >> 8 & 255, c - 1 >> 16 & 255, c - 1 >>> 24 & 255]));
  20850. }
  20851. out.push(buf.slice(l, l + c));
  20852. L += c;
  20853. frame[0] = 0;
  20854. frame[1] = L & 255;
  20855. frame[2] = L >> 8 & 255;
  20856. frame[3] = L >> 16 & 255;
  20857. l += c;
  20858. }
  20859. return u8concat(out);
  20860. }
  20861. function parse_old_storage(buf, sst, rsst, v) {
  20862. var dv = u8_to_dataview(buf);
  20863. var flags = dv.getUint32(4, true);
  20864. var data_offset = (v > 1 ? 12 : 8) + popcnt(flags & (v > 1 ? 3470 : 398)) * 4;
  20865. var ridx = -1, sidx = -1, ieee = NaN, dt = new Date(2001, 0, 1);
  20866. if (flags & 512) {
  20867. ridx = dv.getUint32(data_offset, true);
  20868. data_offset += 4;
  20869. }
  20870. data_offset += popcnt(flags & (v > 1 ? 12288 : 4096)) * 4;
  20871. if (flags & 16) {
  20872. sidx = dv.getUint32(data_offset, true);
  20873. data_offset += 4;
  20874. }
  20875. if (flags & 32) {
  20876. ieee = dv.getFloat64(data_offset, true);
  20877. data_offset += 8;
  20878. }
  20879. if (flags & 64) {
  20880. dt.setTime(dt.getTime() + dv.getFloat64(data_offset, true) * 1e3);
  20881. data_offset += 8;
  20882. }
  20883. var ret;
  20884. switch (buf[2]) {
  20885. case 0:
  20886. break;
  20887. case 2:
  20888. ret = { t: "n", v: ieee };
  20889. break;
  20890. case 3:
  20891. ret = { t: "s", v: sst[sidx] };
  20892. break;
  20893. case 5:
  20894. ret = { t: "d", v: dt };
  20895. break;
  20896. case 6:
  20897. ret = { t: "b", v: ieee > 0 };
  20898. break;
  20899. case 7:
  20900. ret = { t: "n", v: ieee / 86400 };
  20901. break;
  20902. case 8:
  20903. ret = { t: "e", v: 0 };
  20904. break;
  20905. case 9:
  20906. {
  20907. if (ridx > -1)
  20908. ret = { t: "s", v: rsst[ridx] };
  20909. else if (sidx > -1)
  20910. ret = { t: "s", v: sst[sidx] };
  20911. else if (!isNaN(ieee))
  20912. ret = { t: "n", v: ieee };
  20913. else
  20914. throw new Error("Unsupported cell type ".concat(buf.slice(0, 4)));
  20915. }
  20916. break;
  20917. default:
  20918. throw new Error("Unsupported cell type ".concat(buf.slice(0, 4)));
  20919. }
  20920. return ret;
  20921. }
  20922. function parse_new_storage(buf, sst, rsst) {
  20923. var dv = u8_to_dataview(buf);
  20924. var flags = dv.getUint32(8, true);
  20925. var data_offset = 12;
  20926. var ridx = -1, sidx = -1, d128 = NaN, ieee = NaN, dt = new Date(2001, 0, 1);
  20927. if (flags & 1) {
  20928. d128 = readDecimal128LE(buf, data_offset);
  20929. data_offset += 16;
  20930. }
  20931. if (flags & 2) {
  20932. ieee = dv.getFloat64(data_offset, true);
  20933. data_offset += 8;
  20934. }
  20935. if (flags & 4) {
  20936. dt.setTime(dt.getTime() + dv.getFloat64(data_offset, true) * 1e3);
  20937. data_offset += 8;
  20938. }
  20939. if (flags & 8) {
  20940. sidx = dv.getUint32(data_offset, true);
  20941. data_offset += 4;
  20942. }
  20943. if (flags & 16) {
  20944. ridx = dv.getUint32(data_offset, true);
  20945. data_offset += 4;
  20946. }
  20947. var ret;
  20948. switch (buf[1]) {
  20949. case 0:
  20950. break;
  20951. case 2:
  20952. ret = { t: "n", v: d128 };
  20953. break;
  20954. case 3:
  20955. ret = { t: "s", v: sst[sidx] };
  20956. break;
  20957. case 5:
  20958. ret = { t: "d", v: dt };
  20959. break;
  20960. case 6:
  20961. ret = { t: "b", v: ieee > 0 };
  20962. break;
  20963. case 7:
  20964. ret = { t: "n", v: ieee / 86400 };
  20965. break;
  20966. case 8:
  20967. ret = { t: "e", v: 0 };
  20968. break;
  20969. case 9:
  20970. {
  20971. if (ridx > -1)
  20972. ret = { t: "s", v: rsst[ridx] };
  20973. else
  20974. throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(flags & 31, " : ").concat(buf.slice(0, 4)));
  20975. }
  20976. break;
  20977. case 10:
  20978. ret = { t: "n", v: d128 };
  20979. break;
  20980. default:
  20981. throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(flags & 31, " : ").concat(buf.slice(0, 4)));
  20982. }
  20983. return ret;
  20984. }
  20985. function write_new_storage(cell, sst) {
  20986. var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0;
  20987. out[0] = 5;
  20988. switch (cell.t) {
  20989. case "n":
  20990. out[1] = 2;
  20991. writeDecimal128LE(out, l, cell.v);
  20992. flags |= 1;
  20993. l += 16;
  20994. break;
  20995. case "b":
  20996. out[1] = 6;
  20997. dv.setFloat64(l, cell.v ? 1 : 0, true);
  20998. flags |= 2;
  20999. l += 8;
  21000. break;
  21001. case "s":
  21002. if (sst.indexOf(cell.v) == -1)
  21003. throw new Error("Value ".concat(cell.v, " missing from SST!"));
  21004. out[1] = 3;
  21005. dv.setUint32(l, sst.indexOf(cell.v), true);
  21006. flags |= 8;
  21007. l += 4;
  21008. break;
  21009. default:
  21010. throw "unsupported cell type " + cell.t;
  21011. }
  21012. dv.setUint32(8, flags, true);
  21013. return out.slice(0, l);
  21014. }
  21015. function write_old_storage(cell, sst) {
  21016. var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0;
  21017. out[0] = 3;
  21018. switch (cell.t) {
  21019. case "n":
  21020. out[2] = 2;
  21021. dv.setFloat64(l, cell.v, true);
  21022. flags |= 32;
  21023. l += 8;
  21024. break;
  21025. case "b":
  21026. out[2] = 6;
  21027. dv.setFloat64(l, cell.v ? 1 : 0, true);
  21028. flags |= 32;
  21029. l += 8;
  21030. break;
  21031. case "s":
  21032. if (sst.indexOf(cell.v) == -1)
  21033. throw new Error("Value ".concat(cell.v, " missing from SST!"));
  21034. out[2] = 3;
  21035. dv.setUint32(l, sst.indexOf(cell.v), true);
  21036. flags |= 16;
  21037. l += 4;
  21038. break;
  21039. default:
  21040. throw "unsupported cell type " + cell.t;
  21041. }
  21042. dv.setUint32(4, flags, true);
  21043. return out.slice(0, l);
  21044. }
  21045. function parse_cell_storage(buf, sst, rsst) {
  21046. switch (buf[0]) {
  21047. case 0:
  21048. case 1:
  21049. case 2:
  21050. case 3:
  21051. return parse_old_storage(buf, sst, rsst, buf[0]);
  21052. case 5:
  21053. return parse_new_storage(buf, sst, rsst);
  21054. default:
  21055. throw new Error("Unsupported payload version ".concat(buf[0]));
  21056. }
  21057. }
  21058. function parse_TSP_Reference(buf) {
  21059. var pb = parse_shallow(buf);
  21060. return parse_varint49(pb[1][0].data);
  21061. }
  21062. function write_TSP_Reference(idx) {
  21063. var out = [];
  21064. out[1] = [{ type: 0, data: write_varint49(idx) }];
  21065. return write_shallow(out);
  21066. }
  21067. function parse_TST_TableDataList(M, root) {
  21068. var pb = parse_shallow(root.data);
  21069. var type = varint_to_i32(pb[1][0].data);
  21070. var entries = pb[3];
  21071. var data = [];
  21072. (entries || []).forEach(function(entry) {
  21073. var le = parse_shallow(entry.data);
  21074. var key = varint_to_i32(le[1][0].data) >>> 0;
  21075. switch (type) {
  21076. case 1:
  21077. data[key] = u8str(le[3][0].data);
  21078. break;
  21079. case 8:
  21080. {
  21081. var rt = M[parse_TSP_Reference(le[9][0].data)][0];
  21082. var rtp = parse_shallow(rt.data);
  21083. var rtpref = M[parse_TSP_Reference(rtp[1][0].data)][0];
  21084. var mtype = varint_to_i32(rtpref.meta[1][0].data);
  21085. if (mtype != 2001)
  21086. throw new Error("2000 unexpected reference to ".concat(mtype));
  21087. var tswpsa = parse_shallow(rtpref.data);
  21088. data[key] = tswpsa[3].map(function(x) {
  21089. return u8str(x.data);
  21090. }).join("");
  21091. }
  21092. break;
  21093. }
  21094. });
  21095. return data;
  21096. }
  21097. function parse_TST_TileRowInfo(u8, type) {
  21098. var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  21099. var pb = parse_shallow(u8);
  21100. var R = varint_to_i32(pb[1][0].data) >>> 0;
  21101. var cnt = varint_to_i32(pb[2][0].data) >>> 0;
  21102. 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;
  21103. var used_storage_u8, used_storage;
  21104. if (((_d = (_c = pb[7]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && type != 0) {
  21105. used_storage_u8 = (_f = (_e = pb[7]) == null ? void 0 : _e[0]) == null ? void 0 : _f.data;
  21106. used_storage = (_h = (_g = pb[6]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data;
  21107. } else if (((_j = (_i = pb[4]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) && type != 1) {
  21108. used_storage_u8 = (_l = (_k = pb[4]) == null ? void 0 : _k[0]) == null ? void 0 : _l.data;
  21109. used_storage = (_n = (_m = pb[3]) == null ? void 0 : _m[0]) == null ? void 0 : _n.data;
  21110. } else
  21111. throw "NUMBERS Tile missing ".concat(type, " cell storage");
  21112. var width = wide_offsets ? 4 : 1;
  21113. var used_storage_offsets = u8_to_dataview(used_storage_u8);
  21114. var offsets = [];
  21115. for (var C = 0; C < used_storage_u8.length / 2; ++C) {
  21116. var off = used_storage_offsets.getUint16(C * 2, true);
  21117. if (off < 65535)
  21118. offsets.push([C, off]);
  21119. }
  21120. if (offsets.length != cnt)
  21121. throw "Expected ".concat(cnt, " cells, found ").concat(offsets.length);
  21122. var cells = [];
  21123. for (C = 0; C < offsets.length - 1; ++C)
  21124. cells[offsets[C][0]] = used_storage.subarray(offsets[C][1] * width, offsets[C + 1][1] * width);
  21125. if (offsets.length >= 1)
  21126. cells[offsets[offsets.length - 1][0]] = used_storage.subarray(offsets[offsets.length - 1][1] * width);
  21127. return { R: R, cells: cells };
  21128. }
  21129. function parse_TST_Tile(M, root) {
  21130. var _a;
  21131. var pb = parse_shallow(root.data);
  21132. var storage = ((_a = pb == null ? void 0 : pb[7]) == null ? void 0 : _a[0]) ? varint_to_i32(pb[7][0].data) >>> 0 > 0 ? 1 : 0 : -1;
  21133. var ri = mappa(pb[5], function(u8) {
  21134. return parse_TST_TileRowInfo(u8, storage);
  21135. });
  21136. return {
  21137. nrows: varint_to_i32(pb[4][0].data) >>> 0,
  21138. data: ri.reduce(function(acc, x) {
  21139. if (!acc[x.R])
  21140. acc[x.R] = [];
  21141. x.cells.forEach(function(cell, C) {
  21142. if (acc[x.R][C])
  21143. throw new Error("Duplicate cell r=".concat(x.R, " c=").concat(C));
  21144. acc[x.R][C] = cell;
  21145. });
  21146. return acc;
  21147. }, [])
  21148. };
  21149. }
  21150. function parse_TST_TableModelArchive(M, root, ws) {
  21151. var _a;
  21152. var pb = parse_shallow(root.data);
  21153. var range = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
  21154. range.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1;
  21155. if (range.e.r < 0)
  21156. throw new Error("Invalid row varint ".concat(pb[6][0].data));
  21157. range.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1;
  21158. if (range.e.c < 0)
  21159. throw new Error("Invalid col varint ".concat(pb[7][0].data));
  21160. ws["!ref"] = encode_range(range);
  21161. var store = parse_shallow(pb[4][0].data);
  21162. var sst = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[4][0].data)][0]);
  21163. var rsst = ((_a = store[17]) == null ? void 0 : _a[0]) ? parse_TST_TableDataList(M, M[parse_TSP_Reference(store[17][0].data)][0]) : [];
  21164. var tile = parse_shallow(store[3][0].data);
  21165. var _R = 0;
  21166. tile[1].forEach(function(t) {
  21167. var tl = parse_shallow(t.data);
  21168. var ref = M[parse_TSP_Reference(tl[2][0].data)][0];
  21169. var mtype = varint_to_i32(ref.meta[1][0].data);
  21170. if (mtype != 6002)
  21171. throw new Error("6001 unexpected reference to ".concat(mtype));
  21172. var _tile = parse_TST_Tile(M, ref);
  21173. _tile.data.forEach(function(row, R) {
  21174. row.forEach(function(buf, C) {
  21175. var addr = encode_cell({ r: _R + R, c: C });
  21176. var res = parse_cell_storage(buf, sst, rsst);
  21177. if (res)
  21178. ws[addr] = res;
  21179. });
  21180. });
  21181. _R += _tile.nrows;
  21182. });
  21183. }
  21184. function parse_TST_TableInfoArchive(M, root) {
  21185. var pb = parse_shallow(root.data);
  21186. var out = { "!ref": "A1" };
  21187. var tableref = M[parse_TSP_Reference(pb[2][0].data)];
  21188. var mtype = varint_to_i32(tableref[0].meta[1][0].data);
  21189. if (mtype != 6001)
  21190. throw new Error("6000 unexpected reference to ".concat(mtype));
  21191. parse_TST_TableModelArchive(M, tableref[0], out);
  21192. return out;
  21193. }
  21194. function parse_TN_SheetArchive(M, root) {
  21195. var _a;
  21196. var pb = parse_shallow(root.data);
  21197. var out = {
  21198. name: ((_a = pb[1]) == null ? void 0 : _a[0]) ? u8str(pb[1][0].data) : "",
  21199. sheets: []
  21200. };
  21201. var shapeoffs = mappa(pb[2], parse_TSP_Reference);
  21202. shapeoffs.forEach(function(off) {
  21203. M[off].forEach(function(m) {
  21204. var mtype = varint_to_i32(m.meta[1][0].data);
  21205. if (mtype == 6e3)
  21206. out.sheets.push(parse_TST_TableInfoArchive(M, m));
  21207. });
  21208. });
  21209. return out;
  21210. }
  21211. function parse_TN_DocumentArchive(M, root) {
  21212. var out = book_new();
  21213. var pb = parse_shallow(root.data);
  21214. var sheetoffs = mappa(pb[1], parse_TSP_Reference);
  21215. sheetoffs.forEach(function(off) {
  21216. M[off].forEach(function(m) {
  21217. var mtype = varint_to_i32(m.meta[1][0].data);
  21218. if (mtype == 2) {
  21219. var root2 = parse_TN_SheetArchive(M, m);
  21220. root2.sheets.forEach(function(sheet, idx) {
  21221. book_append_sheet(out, sheet, idx == 0 ? root2.name : root2.name + "_" + idx, true);
  21222. });
  21223. }
  21224. });
  21225. });
  21226. if (out.SheetNames.length == 0)
  21227. throw new Error("Empty NUMBERS file");
  21228. return out;
  21229. }
  21230. function parse_numbers_iwa(cfb) {
  21231. var _a, _b, _c, _d;
  21232. var M = {}, indices = [];
  21233. cfb.FullPaths.forEach(function(p) {
  21234. if (p.match(/\.iwpv2/))
  21235. throw new Error("Unsupported password protection");
  21236. });
  21237. cfb.FileIndex.forEach(function(s) {
  21238. if (!s.name.match(/\.iwa$/))
  21239. return;
  21240. var o;
  21241. try {
  21242. o = decompress_iwa_file(s.content);
  21243. } catch (e) {
  21244. return console.log("?? " + s.content.length + " " + (e.message || e));
  21245. }
  21246. var packets;
  21247. try {
  21248. packets = parse_iwa_file(o);
  21249. } catch (e) {
  21250. return console.log("## " + (e.message || e));
  21251. }
  21252. packets.forEach(function(packet) {
  21253. M[packet.id] = packet.messages;
  21254. indices.push(packet.id);
  21255. });
  21256. });
  21257. if (!indices.length)
  21258. throw new Error("File has no messages");
  21259. var docroot = ((_d = (_c = (_b = (_a = M == null ? void 0 : M[1]) == null ? void 0 : _a[0]) == null ? void 0 : _b.meta) == null ? void 0 : _c[1]) == null ? void 0 : _d[0].data) && varint_to_i32(M[1][0].meta[1][0].data) == 1 && M[1][0];
  21260. if (!docroot)
  21261. indices.forEach(function(idx) {
  21262. M[idx].forEach(function(iwam) {
  21263. var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0;
  21264. if (mtype == 1) {
  21265. if (!docroot)
  21266. docroot = iwam;
  21267. else
  21268. throw new Error("Document has multiple roots");
  21269. }
  21270. });
  21271. });
  21272. if (!docroot)
  21273. throw new Error("Cannot find Document root");
  21274. return parse_TN_DocumentArchive(M, docroot);
  21275. }
  21276. function write_tile_row(tri, data, SST) {
  21277. var _a, _b, _c, _d;
  21278. if (!((_a = tri[6]) == null ? void 0 : _a[0]) || !((_b = tri[7]) == null ? void 0 : _b[0]))
  21279. throw "Mutation only works on post-BNC storages!";
  21280. var wide_offsets = ((_d = (_c = tri[8]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && varint_to_i32(tri[8][0].data) > 0 || false;
  21281. if (wide_offsets)
  21282. throw "Math only works with normal offsets";
  21283. var cnt = 0;
  21284. var dv = u8_to_dataview(tri[7][0].data), last_offset = 0, cell_storage = [];
  21285. var _dv = u8_to_dataview(tri[4][0].data), _last_offset = 0, _cell_storage = [];
  21286. for (var C = 0; C < data.length; ++C) {
  21287. if (data[C] == null) {
  21288. dv.setUint16(C * 2, 65535, true);
  21289. _dv.setUint16(C * 2, 65535);
  21290. continue;
  21291. }
  21292. dv.setUint16(C * 2, last_offset, true);
  21293. _dv.setUint16(C * 2, _last_offset, true);
  21294. var celload, _celload;
  21295. switch (typeof data[C]) {
  21296. case "string":
  21297. celload = write_new_storage({ t: "s", v: data[C] }, SST);
  21298. _celload = write_old_storage({ t: "s", v: data[C] }, SST);
  21299. break;
  21300. case "number":
  21301. celload = write_new_storage({ t: "n", v: data[C] }, SST);
  21302. _celload = write_old_storage({ t: "n", v: data[C] }, SST);
  21303. break;
  21304. case "boolean":
  21305. celload = write_new_storage({ t: "b", v: data[C] }, SST);
  21306. _celload = write_old_storage({ t: "b", v: data[C] }, SST);
  21307. break;
  21308. default:
  21309. throw new Error("Unsupported value " + data[C]);
  21310. }
  21311. cell_storage.push(celload);
  21312. last_offset += celload.length;
  21313. _cell_storage.push(_celload);
  21314. _last_offset += _celload.length;
  21315. ++cnt;
  21316. }
  21317. tri[2][0].data = write_varint49(cnt);
  21318. for (; C < tri[7][0].data.length / 2; ++C) {
  21319. dv.setUint16(C * 2, 65535, true);
  21320. _dv.setUint16(C * 2, 65535, true);
  21321. }
  21322. tri[6][0].data = u8concat(cell_storage);
  21323. tri[3][0].data = u8concat(_cell_storage);
  21324. return cnt;
  21325. }
  21326. function write_numbers_iwa(wb, opts) {
  21327. if (!opts || !opts.numbers)
  21328. throw new Error("Must pass a `numbers` option -- check the README");
  21329. var ws = wb.Sheets[wb.SheetNames[0]];
  21330. if (wb.SheetNames.length > 1)
  21331. console.error("The Numbers writer currently writes only the first table");
  21332. var range = decode_range(ws["!ref"]);
  21333. range.s.r = range.s.c = 0;
  21334. var trunc = false;
  21335. if (range.e.c > 9) {
  21336. trunc = true;
  21337. range.e.c = 9;
  21338. }
  21339. if (range.e.r > 49) {
  21340. trunc = true;
  21341. range.e.r = 49;
  21342. }
  21343. if (trunc)
  21344. console.error("The Numbers writer is currently limited to ".concat(encode_range(range)));
  21345. var data = sheet_to_json(ws, { range: range, header: 1 });
  21346. var SST = ["~Sh33tJ5~"];
  21347. data.forEach(function(row) {
  21348. return row.forEach(function(cell) {
  21349. if (typeof cell == "string")
  21350. SST.push(cell);
  21351. });
  21352. });
  21353. var dependents = {};
  21354. var indices = [];
  21355. var cfb = CFB.read(opts.numbers, { type: "base64" });
  21356. cfb.FileIndex.map(function(fi, idx) {
  21357. return [fi, cfb.FullPaths[idx]];
  21358. }).forEach(function(row) {
  21359. var fi = row[0], fp = row[1];
  21360. if (fi.type != 2)
  21361. return;
  21362. if (!fi.name.match(/\.iwa/))
  21363. return;
  21364. var old_content = fi.content;
  21365. var raw1 = decompress_iwa_file(old_content);
  21366. var x2 = parse_iwa_file(raw1);
  21367. x2.forEach(function(packet2) {
  21368. indices.push(packet2.id);
  21369. dependents[packet2.id] = { deps: [], location: fp, type: varint_to_i32(packet2.messages[0].meta[1][0].data) };
  21370. });
  21371. });
  21372. indices.sort(function(x2, y2) {
  21373. return x2 - y2;
  21374. });
  21375. var indices_varint = indices.filter(function(x2) {
  21376. return x2 > 1;
  21377. }).map(function(x2) {
  21378. return [x2, write_varint49(x2)];
  21379. });
  21380. cfb.FileIndex.map(function(fi, idx) {
  21381. return [fi, cfb.FullPaths[idx]];
  21382. }).forEach(function(row) {
  21383. var fi = row[0], fp = row[1];
  21384. if (!fi.name.match(/\.iwa/))
  21385. return;
  21386. var x2 = parse_iwa_file(decompress_iwa_file(fi.content));
  21387. x2.forEach(function(ia) {
  21388. ia.messages.forEach(function(m) {
  21389. indices_varint.forEach(function(ivi) {
  21390. if (ia.messages.some(function(mess) {
  21391. return varint_to_i32(mess.meta[1][0].data) != 11006 && u8contains(mess.data, ivi[1]);
  21392. })) {
  21393. dependents[ivi[0]].deps.push(ia.id);
  21394. }
  21395. });
  21396. });
  21397. });
  21398. });
  21399. function get_unique_msgid() {
  21400. for (var i = 927262; i < 2e6; ++i)
  21401. if (!dependents[i])
  21402. return i;
  21403. throw new Error("Too many messages");
  21404. }
  21405. var entry = CFB.find(cfb, dependents[1].location);
  21406. var x = parse_iwa_file(decompress_iwa_file(entry.content));
  21407. var docroot;
  21408. for (var xi = 0; xi < x.length; ++xi) {
  21409. var packet = x[xi];
  21410. if (packet.id == 1)
  21411. docroot = packet;
  21412. }
  21413. var sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[1][0].data);
  21414. entry = CFB.find(cfb, dependents[sheetrootref].location);
  21415. x = parse_iwa_file(decompress_iwa_file(entry.content));
  21416. for (xi = 0; xi < x.length; ++xi) {
  21417. packet = x[xi];
  21418. if (packet.id == sheetrootref)
  21419. docroot = packet;
  21420. }
  21421. sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[2][0].data);
  21422. entry = CFB.find(cfb, dependents[sheetrootref].location);
  21423. x = parse_iwa_file(decompress_iwa_file(entry.content));
  21424. for (xi = 0; xi < x.length; ++xi) {
  21425. packet = x[xi];
  21426. if (packet.id == sheetrootref)
  21427. docroot = packet;
  21428. }
  21429. sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[2][0].data);
  21430. entry = CFB.find(cfb, dependents[sheetrootref].location);
  21431. x = parse_iwa_file(decompress_iwa_file(entry.content));
  21432. for (xi = 0; xi < x.length; ++xi) {
  21433. packet = x[xi];
  21434. if (packet.id == sheetrootref)
  21435. docroot = packet;
  21436. }
  21437. var pb = parse_shallow(docroot.messages[0].data);
  21438. {
  21439. pb[6][0].data = write_varint49(range.e.r + 1);
  21440. pb[7][0].data = write_varint49(range.e.c + 1);
  21441. var cruidsref = parse_TSP_Reference(pb[46][0].data);
  21442. var oldbucket = CFB.find(cfb, dependents[cruidsref].location);
  21443. var _x = parse_iwa_file(decompress_iwa_file(oldbucket.content));
  21444. {
  21445. for (var j = 0; j < _x.length; ++j) {
  21446. if (_x[j].id == cruidsref)
  21447. break;
  21448. }
  21449. if (_x[j].id != cruidsref)
  21450. throw "Bad ColumnRowUIDMapArchive";
  21451. var cruids = parse_shallow(_x[j].messages[0].data);
  21452. cruids[1] = [];
  21453. cruids[2] = [], cruids[3] = [];
  21454. for (var C = 0; C <= range.e.c; ++C) {
  21455. var uuid = [];
  21456. uuid[1] = uuid[2] = [{ type: 0, data: write_varint49(C + 420690) }];
  21457. cruids[1].push({ type: 2, data: write_shallow(uuid) });
  21458. cruids[2].push({ type: 0, data: write_varint49(C) });
  21459. cruids[3].push({ type: 0, data: write_varint49(C) });
  21460. }
  21461. cruids[4] = [];
  21462. cruids[5] = [], cruids[6] = [];
  21463. for (var R = 0; R <= range.e.r; ++R) {
  21464. uuid = [];
  21465. uuid[1] = uuid[2] = [{ type: 0, data: write_varint49(R + 726270) }];
  21466. cruids[4].push({ type: 2, data: write_shallow(uuid) });
  21467. cruids[5].push({ type: 0, data: write_varint49(R) });
  21468. cruids[6].push({ type: 0, data: write_varint49(R) });
  21469. }
  21470. _x[j].messages[0].data = write_shallow(cruids);
  21471. }
  21472. oldbucket.content = compress_iwa_file(write_iwa_file(_x));
  21473. oldbucket.size = oldbucket.content.length;
  21474. delete pb[46];
  21475. var store = parse_shallow(pb[4][0].data);
  21476. {
  21477. store[7][0].data = write_varint49(range.e.r + 1);
  21478. var row_headers = parse_shallow(store[1][0].data);
  21479. var row_header_ref = parse_TSP_Reference(row_headers[2][0].data);
  21480. oldbucket = CFB.find(cfb, dependents[row_header_ref].location);
  21481. _x = parse_iwa_file(decompress_iwa_file(oldbucket.content));
  21482. {
  21483. if (_x[0].id != row_header_ref)
  21484. throw "Bad HeaderStorageBucket";
  21485. var base_bucket = parse_shallow(_x[0].messages[0].data);
  21486. for (R = 0; R < data.length; ++R) {
  21487. var _bucket = parse_shallow(base_bucket[2][0].data);
  21488. _bucket[1][0].data = write_varint49(R);
  21489. _bucket[4][0].data = write_varint49(data[R].length);
  21490. base_bucket[2][R] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) };
  21491. }
  21492. _x[0].messages[0].data = write_shallow(base_bucket);
  21493. }
  21494. oldbucket.content = compress_iwa_file(write_iwa_file(_x));
  21495. oldbucket.size = oldbucket.content.length;
  21496. var col_header_ref = parse_TSP_Reference(store[2][0].data);
  21497. oldbucket = CFB.find(cfb, dependents[col_header_ref].location);
  21498. _x = parse_iwa_file(decompress_iwa_file(oldbucket.content));
  21499. {
  21500. if (_x[0].id != col_header_ref)
  21501. throw "Bad HeaderStorageBucket";
  21502. base_bucket = parse_shallow(_x[0].messages[0].data);
  21503. for (C = 0; C <= range.e.c; ++C) {
  21504. _bucket = parse_shallow(base_bucket[2][0].data);
  21505. _bucket[1][0].data = write_varint49(C);
  21506. _bucket[4][0].data = write_varint49(range.e.r + 1);
  21507. base_bucket[2][C] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) };
  21508. }
  21509. _x[0].messages[0].data = write_shallow(base_bucket);
  21510. }
  21511. oldbucket.content = compress_iwa_file(write_iwa_file(_x));
  21512. oldbucket.size = oldbucket.content.length;
  21513. var sstref = parse_TSP_Reference(store[4][0].data);
  21514. (function() {
  21515. var sentry = CFB.find(cfb, dependents[sstref].location);
  21516. var sx = parse_iwa_file(decompress_iwa_file(sentry.content));
  21517. var sstroot;
  21518. for (var sxi = 0; sxi < sx.length; ++sxi) {
  21519. var packet2 = sx[sxi];
  21520. if (packet2.id == sstref)
  21521. sstroot = packet2;
  21522. }
  21523. var sstdata = parse_shallow(sstroot.messages[0].data);
  21524. {
  21525. sstdata[3] = [];
  21526. var newsst = [];
  21527. SST.forEach(function(str, i) {
  21528. newsst[1] = [{ type: 0, data: write_varint49(i) }];
  21529. newsst[2] = [{ type: 0, data: write_varint49(1) }];
  21530. newsst[3] = [{ type: 2, data: stru8(str) }];
  21531. sstdata[3].push({ type: 2, data: write_shallow(newsst) });
  21532. });
  21533. }
  21534. sstroot.messages[0].data = write_shallow(sstdata);
  21535. var sy = write_iwa_file(sx);
  21536. var raw32 = compress_iwa_file(sy);
  21537. sentry.content = raw32;
  21538. sentry.size = sentry.content.length;
  21539. })();
  21540. var tile = parse_shallow(store[3][0].data);
  21541. {
  21542. var t = tile[1][0];
  21543. delete tile[2];
  21544. var tl = parse_shallow(t.data);
  21545. {
  21546. var tileref = parse_TSP_Reference(tl[2][0].data);
  21547. (function() {
  21548. var tentry = CFB.find(cfb, dependents[tileref].location);
  21549. var tx = parse_iwa_file(decompress_iwa_file(tentry.content));
  21550. var tileroot;
  21551. for (var sxi = 0; sxi < tx.length; ++sxi) {
  21552. var packet2 = tx[sxi];
  21553. if (packet2.id == tileref)
  21554. tileroot = packet2;
  21555. }
  21556. var tiledata = parse_shallow(tileroot.messages[0].data);
  21557. {
  21558. delete tiledata[6];
  21559. delete tile[7];
  21560. var rowload = new Uint8Array(tiledata[5][0].data);
  21561. tiledata[5] = [];
  21562. var cnt = 0;
  21563. for (var R2 = 0; R2 <= range.e.r; ++R2) {
  21564. var tilerow = parse_shallow(rowload);
  21565. cnt += write_tile_row(tilerow, data[R2], SST);
  21566. tilerow[1][0].data = write_varint49(R2);
  21567. tiledata[5].push({ data: write_shallow(tilerow), type: 2 });
  21568. }
  21569. tiledata[1] = [{ type: 0, data: write_varint49(range.e.c + 1) }];
  21570. tiledata[2] = [{ type: 0, data: write_varint49(range.e.r + 1) }];
  21571. tiledata[3] = [{ type: 0, data: write_varint49(cnt) }];
  21572. tiledata[4] = [{ type: 0, data: write_varint49(range.e.r + 1) }];
  21573. }
  21574. tileroot.messages[0].data = write_shallow(tiledata);
  21575. var ty = write_iwa_file(tx);
  21576. var raw32 = compress_iwa_file(ty);
  21577. tentry.content = raw32;
  21578. tentry.size = tentry.content.length;
  21579. })();
  21580. }
  21581. t.data = write_shallow(tl);
  21582. }
  21583. store[3][0].data = write_shallow(tile);
  21584. }
  21585. pb[4][0].data = write_shallow(store);
  21586. }
  21587. docroot.messages[0].data = write_shallow(pb);
  21588. var y = write_iwa_file(x);
  21589. var raw3 = compress_iwa_file(y);
  21590. entry.content = raw3;
  21591. entry.size = entry.content.length;
  21592. return cfb;
  21593. }
  21594. function fix_opts_func(defaults) {
  21595. return function fix_opts(opts) {
  21596. for(var i = 0; i != defaults.length; ++i) {
  21597. var d = defaults[i];
  21598. if(opts[d[0]] === undefined) opts[d[0]] = d[1];
  21599. if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
  21600. }
  21601. };
  21602. }
  21603. function fix_read_opts(opts) {
  21604. fix_opts_func([
  21605. ['cellNF', false], /* emit cell number format string as .z */
  21606. ['cellHTML', true], /* emit html string as .h */
  21607. ['cellFormula', true], /* emit formulae as .f */
  21608. ['cellStyles', false], /* emits style/theme as .s */
  21609. ['cellText', true], /* emit formatted text as .w */
  21610. ['cellDates', false], /* emit date cells with type `d` */
  21611. ['sheetStubs', false], /* emit empty cells */
  21612. ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
  21613. ['bookDeps', false], /* parse calculation chains */
  21614. ['bookSheets', false], /* only try to get sheet names (no Sheets) */
  21615. ['bookProps', false], /* only try to get properties (no Sheets) */
  21616. ['bookFiles', false], /* include raw file structure (keys, files, cfb) */
  21617. ['bookVBA', false], /* include vba raw data (vbaraw) */
  21618. ['password',''], /* password */
  21619. ['WTF', false] /* WTF mode (throws errors) */
  21620. ])(opts);
  21621. }
  21622. function fix_write_opts(opts) {
  21623. fix_opts_func([
  21624. ['cellDates', false], /* write date cells with type `d` */
  21625. ['bookSST', false], /* Generate Shared String Table */
  21626. ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
  21627. ['compression', false], /* Use file compression */
  21628. ['WTF', false] /* WTF mode (throws errors) */
  21629. ])(opts);
  21630. }
  21631. function get_sheet_type(n) {
  21632. if(RELS.WS.indexOf(n) > -1) return "sheet";
  21633. if(RELS.CS && n == RELS.CS) return "chart";
  21634. if(RELS.DS && n == RELS.DS) return "dialog";
  21635. if(RELS.MS && n == RELS.MS) return "macro";
  21636. return (n && n.length) ? n : "sheet";
  21637. }
  21638. function safe_parse_wbrels(wbrels, sheets) {
  21639. if(!wbrels) return 0;
  21640. try {
  21641. 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)]; });
  21642. } catch(e) { return null; }
  21643. return !wbrels || wbrels.length === 0 ? null : wbrels;
  21644. }
  21645. function safe_parse_sheet(zip, path, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles) {
  21646. try {
  21647. sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
  21648. var data = getzipdata(zip, path);
  21649. var _ws;
  21650. switch(stype) {
  21651. case 'sheet': _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  21652. case 'chart': _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
  21653. if(!_ws || !_ws['!drawel']) break;
  21654. var dfile = resolve_path(_ws['!drawel'].Target, path);
  21655. var drelsp = get_rels_path(dfile);
  21656. var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
  21657. var chartp = resolve_path(draw, dfile);
  21658. var crelsp = get_rels_path(chartp);
  21659. _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
  21660. break;
  21661. case 'macro': _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  21662. case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  21663. default: throw new Error("Unrecognized sheet type " + stype);
  21664. }
  21665. sheets[sheet] = _ws;
  21666. /* scan rels for comments and threaded comments */
  21667. var tcomments = [];
  21668. if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
  21669. var dfile = "";
  21670. if(sheetRels[sheet][n].Type == RELS.CMNT) {
  21671. dfile = resolve_path(sheetRels[sheet][n].Target, path);
  21672. var comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
  21673. if(!comments || !comments.length) return;
  21674. sheet_insert_comments(_ws, comments, false);
  21675. }
  21676. if(sheetRels[sheet][n].Type == RELS.TCMNT) {
  21677. dfile = resolve_path(sheetRels[sheet][n].Target, path);
  21678. tcomments = tcomments.concat(parse_tcmnt_xml(getzipdata(zip, dfile, true), opts));
  21679. }
  21680. });
  21681. if(tcomments && tcomments.length) sheet_insert_comments(_ws, tcomments, true, opts.people || []);
  21682. } catch(e) { if(opts.WTF) throw e; }
  21683. }
  21684. function strip_front_slash(x) { return x.charAt(0) == '/' ? x.slice(1) : x; }
  21685. function parse_zip(zip, opts) {
  21686. make_ssf();
  21687. opts = opts || {};
  21688. fix_read_opts(opts);
  21689. /* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
  21690. if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
  21691. /* UOC */
  21692. if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
  21693. /* Numbers */
  21694. if(safegetzipfile(zip, 'Index/Document.iwa')) {
  21695. if(typeof Uint8Array == "undefined") throw new Error('NUMBERS file parsing requires Uint8Array support');
  21696. if(typeof parse_numbers_iwa != "undefined") {
  21697. if(zip.FileIndex) return parse_numbers_iwa(zip);
  21698. var _zip = CFB.utils.cfb_new();
  21699. zipentries(zip).forEach(function(e) { zip_add_file(_zip, e, getzipbin(zip, e)); });
  21700. return parse_numbers_iwa(_zip);
  21701. }
  21702. throw new Error('Unsupported NUMBERS file');
  21703. }
  21704. if(!safegetzipfile(zip, '[Content_Types].xml')) {
  21705. if(safegetzipfile(zip, 'index.xml.gz')) throw new Error('Unsupported NUMBERS 08 file');
  21706. if(safegetzipfile(zip, 'index.xml')) throw new Error('Unsupported NUMBERS 09 file');
  21707. throw new Error('Unsupported ZIP file');
  21708. }
  21709. var entries = zipentries(zip);
  21710. var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')));
  21711. var xlsb = false;
  21712. var sheets, binname;
  21713. if(dir.workbooks.length === 0) {
  21714. binname = "xl/workbook.xml";
  21715. if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
  21716. }
  21717. if(dir.workbooks.length === 0) {
  21718. binname = "xl/workbook.bin";
  21719. if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
  21720. dir.workbooks.push(binname);
  21721. xlsb = true;
  21722. }
  21723. if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  21724. var themes = ({});
  21725. var styles = ({});
  21726. if(!opts.bookSheets && !opts.bookProps) {
  21727. strs = [];
  21728. if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }
  21729. if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"",dir.themes[0], opts);
  21730. if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  21731. }
  21732. /*var externbooks = */dir.links.map(function(link) {
  21733. try {
  21734. var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
  21735. return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
  21736. } catch(e) {}
  21737. });
  21738. var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  21739. var props = {}, propdata = "";
  21740. if(dir.coreprops.length) {
  21741. propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
  21742. if(propdata) props = parse_core_props(propdata);
  21743. if(dir.extprops.length !== 0) {
  21744. propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
  21745. if(propdata) parse_ext_props(propdata, props, opts);
  21746. }
  21747. }
  21748. var custprops = {};
  21749. if(!opts.bookSheets || opts.bookProps) {
  21750. if (dir.custprops.length !== 0) {
  21751. propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
  21752. if(propdata) custprops = parse_cust_props(propdata, opts);
  21753. }
  21754. }
  21755. var out = ({});
  21756. if(opts.bookSheets || opts.bookProps) {
  21757. if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
  21758. else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
  21759. if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
  21760. if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
  21761. if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  21762. }
  21763. sheets = {};
  21764. var deps = {};
  21765. if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);
  21766. var i=0;
  21767. var sheetRels = ({});
  21768. var path, relsPath;
  21769. {
  21770. var wbsheets = wb.Sheets;
  21771. props.Worksheets = wbsheets.length;
  21772. props.SheetNames = [];
  21773. for(var j = 0; j != wbsheets.length; ++j) {
  21774. props.SheetNames[j] = wbsheets[j].name;
  21775. }
  21776. }
  21777. var wbext = xlsb ? "bin" : "xml";
  21778. var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  21779. var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
  21780. if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
  21781. var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile.replace(/_rels.*/, "s5s"));
  21782. if((dir.metadata || []).length >= 1) {
  21783. /* TODO: MDX and other types of metadata */
  21784. opts.xlmeta = parse_xlmeta(getzipdata(zip, strip_front_slash(dir.metadata[0])),dir.metadata[0],opts);
  21785. }
  21786. if((dir.people || []).length >= 1) {
  21787. opts.people = parse_people_xml(getzipdata(zip, strip_front_slash(dir.people[0])),opts);
  21788. }
  21789. if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  21790. /* Numbers iOS hack */
  21791. var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
  21792. wsloop: for(i = 0; i != props.Worksheets; ++i) {
  21793. var stype = "sheet";
  21794. if(wbrels && wbrels[i]) {
  21795. path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
  21796. if(!safegetzipfile(zip, path)) path = wbrels[i][1];
  21797. if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
  21798. stype = wbrels[i][2];
  21799. } else {
  21800. path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
  21801. path = path.replace(/sheet0\./,"sheet.");
  21802. }
  21803. relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
  21804. if(opts && opts.sheets != null) switch(typeof opts.sheets) {
  21805. case "number": if(i != opts.sheets) continue wsloop; break;
  21806. case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
  21807. default: if(Array.isArray && Array.isArray(opts.sheets)) {
  21808. var snjseen = false;
  21809. for(var snj = 0; snj != opts.sheets.length; ++snj) {
  21810. if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
  21811. if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
  21812. }
  21813. if(!snjseen) continue wsloop;
  21814. }
  21815. }
  21816. safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
  21817. }
  21818. out = ({
  21819. Directory: dir,
  21820. Workbook: wb,
  21821. Props: props,
  21822. Custprops: custprops,
  21823. Deps: deps,
  21824. Sheets: sheets,
  21825. SheetNames: props.SheetNames,
  21826. Strings: strs,
  21827. Styles: styles,
  21828. Themes: themes,
  21829. SSF: dup(table_fmt)
  21830. });
  21831. if(opts && opts.bookFiles) {
  21832. if(zip.files) {
  21833. out.keys = entries;
  21834. out.files = zip.files;
  21835. } else {
  21836. out.keys = [];
  21837. out.files = {};
  21838. zip.FullPaths.forEach(function(p, idx) {
  21839. p = p.replace(/^Root Entry[\/]/, "");
  21840. out.keys.push(p);
  21841. out.files[p] = zip.FileIndex[idx];
  21842. });
  21843. }
  21844. }
  21845. if(opts && opts.bookVBA) {
  21846. if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
  21847. else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
  21848. }
  21849. return out;
  21850. }
  21851. /* [MS-OFFCRYPTO] 2.1.1 */
  21852. function parse_xlsxcfb(cfb, _opts) {
  21853. var opts = _opts || {};
  21854. var f = 'Workbook', data = CFB.find(cfb, f);
  21855. try {
  21856. f = '/!DataSpaces/Version';
  21857. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  21858. /*var version = */parse_DataSpaceVersionInfo(data.content);
  21859. /* 2.3.4.1 */
  21860. f = '/!DataSpaces/DataSpaceMap';
  21861. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  21862. var dsm = parse_DataSpaceMap(data.content);
  21863. 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")
  21864. throw new Error("ECMA-376 Encrypted file bad " + f);
  21865. /* 2.3.4.2 */
  21866. f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
  21867. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  21868. var seds = parse_DataSpaceDefinition(data.content);
  21869. if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
  21870. throw new Error("ECMA-376 Encrypted file bad " + f);
  21871. /* 2.3.4.3 */
  21872. f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
  21873. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  21874. /*var hdr = */parse_Primary(data.content);
  21875. } catch(e) {}
  21876. f = '/EncryptionInfo';
  21877. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  21878. var einfo = parse_EncryptionInfo(data.content);
  21879. /* 2.3.4.4 */
  21880. f = '/EncryptedPackage';
  21881. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  21882. /*global decrypt_agile */
  21883. if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  21884. /*global decrypt_std76 */
  21885. if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  21886. throw new Error("File is password-protected");
  21887. }
  21888. function write_zip(wb, opts) {
  21889. if(opts.bookType == "ods") return write_ods(wb, opts);
  21890. if(opts.bookType == "numbers") return write_numbers_iwa(wb, opts);
  21891. if(opts.bookType == "xlsb") return write_zip_xlsxb(wb, opts);
  21892. return write_zip_xlsx(wb, opts);
  21893. }
  21894. /* XLSX and XLSB writing are very similar. Originally they were unified in one
  21895. export function. This is horrible for tree shaking in the common case (most
  21896. applications need to export files in one format) so this function supports
  21897. both formats while write_zip_xlsx only handles XLSX */
  21898. function write_zip_xlsxb(wb, opts) {
  21899. _shapeid = 1024;
  21900. if(wb && !wb.SSF) {
  21901. wb.SSF = dup(table_fmt);
  21902. }
  21903. if(wb && wb.SSF) {
  21904. make_ssf(); SSF_load_table(wb.SSF);
  21905. // $FlowIgnore
  21906. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  21907. opts.ssf = wb.SSF;
  21908. }
  21909. opts.rels = {}; opts.wbrels = {};
  21910. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  21911. if(browser_has_Map) opts.revStrings = new Map();
  21912. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  21913. var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
  21914. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  21915. var ct = new_ct();
  21916. fix_write_opts(opts = opts || {});
  21917. var zip = zip_new();
  21918. var f = "", rId = 0;
  21919. opts.cellXfs = [];
  21920. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  21921. if(!wb.Props) wb.Props = {};
  21922. f = "docProps/core.xml";
  21923. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  21924. ct.coreprops.push(f);
  21925. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  21926. f = "docProps/app.xml";
  21927. if(wb.Props && wb.Props.SheetNames){/* empty */}
  21928. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  21929. else {
  21930. var _sn = [];
  21931. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  21932. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  21933. wb.Props.SheetNames = _sn;
  21934. }
  21935. wb.Props.Worksheets = wb.Props.SheetNames.length;
  21936. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  21937. ct.extprops.push(f);
  21938. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  21939. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  21940. f = "docProps/custom.xml";
  21941. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  21942. ct.custprops.push(f);
  21943. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  21944. }
  21945. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  21946. var wsrels = {'!id':{}};
  21947. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  21948. var _type = (ws || {})["!type"] || "sheet";
  21949. switch(_type) {
  21950. case "chart":
  21951. /* falls through */
  21952. default:
  21953. f = "xl/worksheets/sheet" + rId + "." + wbext;
  21954. zip_add_file(zip, f, write_ws(rId-1, f, opts, wb, wsrels));
  21955. ct.sheets.push(f);
  21956. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  21957. }
  21958. if(ws) {
  21959. var comments = ws['!comments'];
  21960. var need_vml = false;
  21961. var cf = "";
  21962. if(comments && comments.length > 0) {
  21963. cf = "xl/comments" + rId + "." + wbext;
  21964. zip_add_file(zip, cf, write_cmnt(comments, cf, opts));
  21965. ct.comments.push(cf);
  21966. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  21967. need_vml = true;
  21968. }
  21969. if(ws['!legacy']) {
  21970. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
  21971. }
  21972. delete ws['!comments'];
  21973. delete ws['!legacy'];
  21974. }
  21975. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  21976. }
  21977. if(opts.Strings != null && opts.Strings.length > 0) {
  21978. f = "xl/sharedStrings." + wbext;
  21979. zip_add_file(zip, f, write_sst(opts.Strings, f, opts));
  21980. ct.strs.push(f);
  21981. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  21982. }
  21983. f = "xl/workbook." + wbext;
  21984. zip_add_file(zip, f, write_wb(wb, f, opts));
  21985. ct.workbooks.push(f);
  21986. add_rels(opts.rels, 1, f, RELS.WB);
  21987. /* TODO: something more intelligent with themes */
  21988. f = "xl/theme/theme1.xml";
  21989. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  21990. ct.themes.push(f);
  21991. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  21992. /* TODO: something more intelligent with styles */
  21993. f = "xl/styles." + wbext;
  21994. zip_add_file(zip, f, write_sty(wb, f, opts));
  21995. ct.styles.push(f);
  21996. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  21997. if(wb.vbaraw && vbafmt) {
  21998. f = "xl/vbaProject.bin";
  21999. zip_add_file(zip, f, wb.vbaraw);
  22000. ct.vba.push(f);
  22001. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  22002. }
  22003. f = "xl/metadata." + wbext;
  22004. zip_add_file(zip, f, write_xlmeta(f));
  22005. ct.metadata.push(f);
  22006. add_rels(opts.wbrels, -1, "metadata." + wbext, RELS.XLMETA);
  22007. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  22008. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  22009. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  22010. delete opts.revssf; delete opts.ssf;
  22011. return zip;
  22012. }
  22013. function write_zip_xlsx(wb, opts) {
  22014. _shapeid = 1024;
  22015. if(wb && !wb.SSF) {
  22016. wb.SSF = dup(table_fmt);
  22017. }
  22018. if(wb && wb.SSF) {
  22019. make_ssf(); SSF_load_table(wb.SSF);
  22020. // $FlowIgnore
  22021. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  22022. opts.ssf = wb.SSF;
  22023. }
  22024. opts.rels = {}; opts.wbrels = {};
  22025. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  22026. if(browser_has_Map) opts.revStrings = new Map();
  22027. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  22028. var wbext = "xml";
  22029. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  22030. var ct = new_ct();
  22031. fix_write_opts(opts = opts || {});
  22032. var zip = zip_new();
  22033. var f = "", rId = 0;
  22034. opts.cellXfs = [];
  22035. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  22036. if(!wb.Props) wb.Props = {};
  22037. f = "docProps/core.xml";
  22038. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  22039. ct.coreprops.push(f);
  22040. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  22041. f = "docProps/app.xml";
  22042. if(wb.Props && wb.Props.SheetNames){/* empty */}
  22043. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  22044. else {
  22045. var _sn = [];
  22046. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  22047. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  22048. wb.Props.SheetNames = _sn;
  22049. }
  22050. wb.Props.Worksheets = wb.Props.SheetNames.length;
  22051. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  22052. ct.extprops.push(f);
  22053. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  22054. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  22055. f = "docProps/custom.xml";
  22056. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  22057. ct.custprops.push(f);
  22058. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  22059. }
  22060. var people = ["SheetJ5"];
  22061. opts.tcid = 0;
  22062. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  22063. var wsrels = {'!id':{}};
  22064. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  22065. var _type = (ws || {})["!type"] || "sheet";
  22066. switch(_type) {
  22067. case "chart":
  22068. /* falls through */
  22069. default:
  22070. f = "xl/worksheets/sheet" + rId + "." + wbext;
  22071. zip_add_file(zip, f, write_ws_xml(rId-1, opts, wb, wsrels));
  22072. ct.sheets.push(f);
  22073. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  22074. }
  22075. if(ws) {
  22076. var comments = ws['!comments'];
  22077. var need_vml = false;
  22078. var cf = "";
  22079. if(comments && comments.length > 0) {
  22080. var needtc = false;
  22081. comments.forEach(function(carr) {
  22082. carr[1].forEach(function(c) { if(c.T == true) needtc = true; });
  22083. });
  22084. if(needtc) {
  22085. cf = "xl/threadedComments/threadedComment" + rId + "." + wbext;
  22086. zip_add_file(zip, cf, write_tcmnt_xml(comments, people, opts));
  22087. ct.threadedcomments.push(cf);
  22088. add_rels(wsrels, -1, "../threadedComments/threadedComment" + rId + "." + wbext, RELS.TCMNT);
  22089. }
  22090. cf = "xl/comments" + rId + "." + wbext;
  22091. zip_add_file(zip, cf, write_comments_xml(comments, opts));
  22092. ct.comments.push(cf);
  22093. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  22094. need_vml = true;
  22095. }
  22096. if(ws['!legacy']) {
  22097. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
  22098. }
  22099. delete ws['!comments'];
  22100. delete ws['!legacy'];
  22101. }
  22102. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  22103. }
  22104. if(opts.Strings != null && opts.Strings.length > 0) {
  22105. f = "xl/sharedStrings." + wbext;
  22106. zip_add_file(zip, f, write_sst_xml(opts.Strings, opts));
  22107. ct.strs.push(f);
  22108. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  22109. }
  22110. f = "xl/workbook." + wbext;
  22111. zip_add_file(zip, f, write_wb_xml(wb, opts));
  22112. ct.workbooks.push(f);
  22113. add_rels(opts.rels, 1, f, RELS.WB);
  22114. /* TODO: something more intelligent with themes */
  22115. f = "xl/theme/theme1.xml";
  22116. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  22117. ct.themes.push(f);
  22118. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  22119. /* TODO: something more intelligent with styles */
  22120. f = "xl/styles." + wbext;
  22121. zip_add_file(zip, f, write_sty_xml(wb, opts));
  22122. ct.styles.push(f);
  22123. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  22124. if(wb.vbaraw && vbafmt) {
  22125. f = "xl/vbaProject.bin";
  22126. zip_add_file(zip, f, wb.vbaraw);
  22127. ct.vba.push(f);
  22128. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  22129. }
  22130. f = "xl/metadata." + wbext;
  22131. zip_add_file(zip, f, write_xlmeta_xml());
  22132. ct.metadata.push(f);
  22133. add_rels(opts.wbrels, -1, "metadata." + wbext, RELS.XLMETA);
  22134. if(people.length > 1) {
  22135. f = "xl/persons/person.xml";
  22136. zip_add_file(zip, f, write_people_xml(people, opts));
  22137. ct.people.push(f);
  22138. add_rels(opts.wbrels, -1, "persons/person.xml", RELS.PEOPLE);
  22139. }
  22140. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  22141. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  22142. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  22143. delete opts.revssf; delete opts.ssf;
  22144. return zip;
  22145. }
  22146. function firstbyte(f,o) {
  22147. var x = "";
  22148. switch((o||{}).type || "base64") {
  22149. case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  22150. case 'base64': x = Base64_decode(f.slice(0,12)); break;
  22151. case 'binary': x = f; break;
  22152. case 'array': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  22153. default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
  22154. }
  22155. 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)];
  22156. }
  22157. function read_cfb(cfb, opts) {
  22158. if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  22159. return parse_xlscfb(cfb, opts);
  22160. }
  22161. function read_zip(data, opts) {
  22162. var zip, d = data;
  22163. var o = opts||{};
  22164. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  22165. zip = zip_read(d, o);
  22166. return parse_zip(zip, o);
  22167. }
  22168. function read_plaintext(data, o) {
  22169. var i = 0;
  22170. main: while(i < data.length) switch(data.charCodeAt(i)) {
  22171. case 0x0A: case 0x0D: case 0x20: ++i; break;
  22172. case 0x3C: return parse_xlml(data.slice(i),o);
  22173. default: break main;
  22174. }
  22175. return PRN.to_workbook(data, o);
  22176. }
  22177. function read_plaintext_raw(data, o) {
  22178. var str = "", bytes = firstbyte(data, o);
  22179. switch(o.type) {
  22180. case 'base64': str = Base64_decode(data); break;
  22181. case 'binary': str = data; break;
  22182. case 'buffer': str = data.toString('binary'); break;
  22183. case 'array': str = cc2str(data); break;
  22184. default: throw new Error("Unrecognized type " + o.type);
  22185. }
  22186. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
  22187. o.type = "binary";
  22188. return read_plaintext(str, o);
  22189. }
  22190. function read_utf16(data, o) {
  22191. var d = data;
  22192. if(o.type == 'base64') d = Base64_decode(d);
  22193. d = $cptable.utils.decode(1200, d.slice(2), 'str');
  22194. o.type = "binary";
  22195. return read_plaintext(d, o);
  22196. }
  22197. function bstrify(data) {
  22198. return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
  22199. }
  22200. function read_prn(data, d, o, str) {
  22201. if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
  22202. return PRN.to_workbook(d, o);
  22203. }
  22204. function readSync(data, opts) {
  22205. reset_cp();
  22206. var o = opts||{};
  22207. if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o = dup(o), o.type = "array", o));
  22208. if(typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && !o.type) o.type = typeof Deno !== "undefined" ? "buffer" : "array";
  22209. var d = data, n = [0,0,0,0], str = false;
  22210. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  22211. _ssfopts = {};
  22212. if(o.dateNF) _ssfopts.dateNF = o.dateNF;
  22213. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  22214. if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); if(typeof Uint8Array !== 'undefined' && !has_buf) o.type = "array"; }
  22215. if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
  22216. if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
  22217. // $FlowIgnore
  22218. var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
  22219. // $FlowIgnore
  22220. if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
  22221. }
  22222. switch((n = firstbyte(d, o))[0]) {
  22223. 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;
  22224. case 0x09: if(n[1] <= 0x08) return parse_xlscfb(d, o); break;
  22225. case 0x3C: return parse_xlml(d, o);
  22226. case 0x49:
  22227. if(n[1] === 0x49 && n[2] === 0x2a && n[3] === 0x00) throw new Error("TIFF Image File is not a spreadsheet");
  22228. if(n[1] === 0x44) return read_wb_ID(d, o);
  22229. break;
  22230. case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
  22231. case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
  22232. case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
  22233. case 0xFF:
  22234. if(n[1] === 0xFE) { return read_utf16(d, o); }
  22235. else if(n[1] === 0x00 && n[2] === 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
  22236. break;
  22237. case 0x00:
  22238. if(n[1] === 0x00) {
  22239. if(n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o);
  22240. if(n[2] === 0x00 && (n[3] === 0x08 || n[3] === 0x09)) return WK_.to_workbook(d, o);
  22241. }
  22242. break;
  22243. case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
  22244. case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return RTF.to_workbook(d, o); break;
  22245. case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
  22246. case 0x89: if(n[1] === 0x50 && n[2] === 0x4E && n[3] === 0x47) throw new Error("PNG Image File is not a spreadsheet"); break;
  22247. }
  22248. if(DBF_SUPPORTED_VERSIONS.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
  22249. return read_prn(data, d, o, str);
  22250. }
  22251. function readFileSync(filename, opts) {
  22252. var o = opts||{}; o.type = 'file';
  22253. return readSync(filename, o);
  22254. }
  22255. function write_cfb_ctr(cfb, o) {
  22256. switch(o.type) {
  22257. case "base64": case "binary": break;
  22258. case "buffer": case "array": o.type = ""; break;
  22259. case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
  22260. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  22261. default: throw new Error("Unrecognized type " + o.type);
  22262. }
  22263. return CFB.write(cfb, o);
  22264. }
  22265. function write_zip_type(wb, opts) {
  22266. var o = dup(opts||{});
  22267. var z = write_zip(wb, o);
  22268. return write_zip_denouement(z, o);
  22269. }
  22270. function write_zip_typeXLSX(wb, opts) {
  22271. var o = dup(opts||{});
  22272. var z = write_zip_xlsx(wb, o);
  22273. return write_zip_denouement(z, o);
  22274. }
  22275. function write_zip_denouement(z, o) {
  22276. var oopts = {};
  22277. var ftype = has_buf ? "nodebuffer" : (typeof Uint8Array !== "undefined" ? "array" : "string");
  22278. if(o.compression) oopts.compression = 'DEFLATE';
  22279. if(o.password) oopts.type = ftype;
  22280. else switch(o.type) {
  22281. case "base64": oopts.type = "base64"; break;
  22282. case "binary": oopts.type = "string"; break;
  22283. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  22284. case "buffer":
  22285. case "file": oopts.type = ftype; break;
  22286. default: throw new Error("Unrecognized type " + o.type);
  22287. }
  22288. var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: {"nodebuffer": "buffer", "string": "binary"}[oopts.type] || oopts.type, compression: !!o.compression}) : z.generate(oopts);
  22289. if(typeof Deno !== "undefined") {
  22290. if(typeof out == "string") {
  22291. if(o.type == "binary" || o.type == "base64") return out;
  22292. out = new Uint8Array(s2ab(out));
  22293. }
  22294. }
  22295. /*jshint -W083 */
  22296. if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
  22297. /*jshint +W083 */
  22298. if(o.type === "file") return write_dl(o.file, out);
  22299. return o.type == "string" ? utf8read(out) : out;
  22300. }
  22301. function write_cfb_type(wb, opts) {
  22302. var o = opts||{};
  22303. var cfb = write_xlscfb(wb, o);
  22304. return write_cfb_ctr(cfb, o);
  22305. }
  22306. function write_string_type(out, opts, bom) {
  22307. if(!bom) bom = "";
  22308. var o = bom + out;
  22309. switch(opts.type) {
  22310. case "base64": return Base64_encode(utf8write(o));
  22311. case "binary": return utf8write(o);
  22312. case "string": return out;
  22313. case "file": return write_dl(opts.file, o, 'utf8');
  22314. case "buffer": {
  22315. if(has_buf) return Buffer_from(o, 'utf8');
  22316. else if(typeof TextEncoder !== "undefined") return new TextEncoder().encode(o);
  22317. else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
  22318. }
  22319. }
  22320. throw new Error("Unrecognized type " + opts.type);
  22321. }
  22322. function write_stxt_type(out, opts) {
  22323. switch(opts.type) {
  22324. case "base64": return Base64_encode(out);
  22325. case "binary": return out;
  22326. case "string": return out; /* override in sheet_to_txt */
  22327. case "file": return write_dl(opts.file, out, 'binary');
  22328. case "buffer": {
  22329. if(has_buf) return Buffer_from(out, 'binary');
  22330. else return out.split("").map(function(c) { return c.charCodeAt(0); });
  22331. }
  22332. }
  22333. throw new Error("Unrecognized type " + opts.type);
  22334. }
  22335. /* TODO: test consistency */
  22336. function write_binary_type(out, opts) {
  22337. switch(opts.type) {
  22338. case "string":
  22339. case "base64":
  22340. case "binary":
  22341. var bstr = "";
  22342. // $FlowIgnore
  22343. for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
  22344. return opts.type == 'base64' ? Base64_encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
  22345. case "file": return write_dl(opts.file, out);
  22346. case "buffer": return out;
  22347. default: throw new Error("Unrecognized type " + opts.type);
  22348. }
  22349. }
  22350. function writeSyncXLSX(wb, opts) {
  22351. reset_cp();
  22352. check_wb(wb);
  22353. var o = dup(opts||{});
  22354. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  22355. if(o.type == "array") { o.type = "binary"; var out = (writeSyncXLSX(wb, o)); o.type = "array"; return s2ab(out); }
  22356. return write_zip_typeXLSX(wb, o);
  22357. }
  22358. function writeSync(wb, opts) {
  22359. reset_cp();
  22360. check_wb(wb);
  22361. var o = dup(opts||{});
  22362. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  22363. if(o.type == "array") { o.type = "binary"; var out = (writeSync(wb, o)); o.type = "array"; return s2ab(out); }
  22364. var idx = 0;
  22365. if(o.sheet) {
  22366. if(typeof o.sheet == "number") idx = o.sheet;
  22367. else idx = wb.SheetNames.indexOf(o.sheet);
  22368. if(!wb.SheetNames[idx]) throw new Error("Sheet not found: " + o.sheet + " : " + (typeof o.sheet));
  22369. }
  22370. switch(o.bookType || 'xlsb') {
  22371. case 'xml':
  22372. case 'xlml': return write_string_type(write_xlml(wb, o), o);
  22373. case 'slk':
  22374. case 'sylk': return write_string_type(SYLK.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  22375. case 'htm':
  22376. case 'html': return write_string_type(sheet_to_html(wb.Sheets[wb.SheetNames[idx]], o), o);
  22377. case 'txt': return write_stxt_type(sheet_to_txt(wb.Sheets[wb.SheetNames[idx]], o), o);
  22378. case 'csv': return write_string_type(sheet_to_csv(wb.Sheets[wb.SheetNames[idx]], o), o, "\ufeff");
  22379. case 'dif': return write_string_type(DIF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  22380. case 'dbf': return write_binary_type(DBF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  22381. case 'prn': return write_string_type(PRN.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  22382. case 'rtf': return write_string_type(RTF.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  22383. case 'eth': return write_string_type(ETH.from_sheet(wb.Sheets[wb.SheetNames[idx]], o), o);
  22384. case 'fods': return write_string_type(write_ods(wb, o), o);
  22385. case 'wk1': return write_binary_type(WK_.sheet_to_wk1(wb.Sheets[wb.SheetNames[idx]], o), o);
  22386. case 'wk3': return write_binary_type(WK_.book_to_wk3(wb, o), o);
  22387. case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
  22388. case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
  22389. case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
  22390. case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
  22391. case 'biff8':
  22392. case 'xla':
  22393. case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
  22394. case 'xlsx':
  22395. case 'xlsm':
  22396. case 'xlam':
  22397. case 'xlsb':
  22398. case 'numbers':
  22399. case 'ods': return write_zip_type(wb, o);
  22400. default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
  22401. }
  22402. }
  22403. function resolve_book_type(o) {
  22404. if(o.bookType) return;
  22405. var _BT = {
  22406. "xls": "biff8",
  22407. "htm": "html",
  22408. "slk": "sylk",
  22409. "socialcalc": "eth",
  22410. "Sh33tJS": "WTF"
  22411. };
  22412. var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
  22413. if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
  22414. o.bookType = _BT[o.bookType] || o.bookType;
  22415. }
  22416. function writeFileSync(wb, filename, opts) {
  22417. var o = opts||{}; o.type = 'file';
  22418. o.file = filename;
  22419. resolve_book_type(o);
  22420. return writeSync(wb, o);
  22421. }
  22422. function writeFileSyncXLSX(wb, filename, opts) {
  22423. var o = opts||{}; o.type = 'file';
  22424. o.file = filename;
  22425. resolve_book_type(o);
  22426. return writeSyncXLSX(wb, o);
  22427. }
  22428. function writeFileAsync(filename, wb, opts, cb) {
  22429. var o = opts||{}; o.type = 'file';
  22430. o.file = filename;
  22431. resolve_book_type(o);
  22432. o.type = 'buffer';
  22433. var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts);
  22434. return _fs.writeFile(filename, writeSync(wb, o), _cb);
  22435. }
  22436. function make_json_row(sheet, r, R, cols, header, hdr, dense, o) {
  22437. var rr = encode_row(R);
  22438. var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
  22439. var isempty = true;
  22440. var row = (header === 1) ? [] : {};
  22441. if(header !== 1) {
  22442. if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
  22443. else row.__rowNum__ = R;
  22444. }
  22445. if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
  22446. var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  22447. if(val === undefined || val.t === undefined) {
  22448. if(defval === undefined) continue;
  22449. if(hdr[C] != null) { row[hdr[C]] = defval; }
  22450. continue;
  22451. }
  22452. var v = val.v;
  22453. switch(val.t){
  22454. case 'z': if(v == null) break; continue;
  22455. case 'e': v = (v == 0 ? null : void 0); break;
  22456. case 's': case 'd': case 'b': case 'n': break;
  22457. default: throw new Error('unrecognized type ' + val.t);
  22458. }
  22459. if(hdr[C] != null) {
  22460. if(v == null) {
  22461. if(val.t == "e" && v === null) row[hdr[C]] = null;
  22462. else if(defval !== undefined) row[hdr[C]] = defval;
  22463. else if(raw && v === null) row[hdr[C]] = null;
  22464. else continue;
  22465. } else {
  22466. row[hdr[C]] = raw && (val.t !== "n" || (val.t === "n" && o.rawNumbers !== false)) ? v : format_cell(val,v,o);
  22467. }
  22468. if(v != null) isempty = false;
  22469. }
  22470. }
  22471. return { row: row, isempty: isempty };
  22472. }
  22473. function sheet_to_json(sheet, opts) {
  22474. if(sheet == null || sheet["!ref"] == null) return [];
  22475. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  22476. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  22477. var o = opts || {};
  22478. var range = o.range != null ? o.range : sheet["!ref"];
  22479. if(o.header === 1) header = 1;
  22480. else if(o.header === "A") header = 2;
  22481. else if(Array.isArray(o.header)) header = 3;
  22482. else if(o.header == null) header = 0;
  22483. switch(typeof range) {
  22484. case 'string': r = safe_decode_range(range); break;
  22485. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  22486. default: r = range;
  22487. }
  22488. if(header > 0) offset = 0;
  22489. var rr = encode_row(r.s.r);
  22490. var cols = [];
  22491. var out = [];
  22492. var outi = 0, counter = 0;
  22493. var dense = Array.isArray(sheet);
  22494. var R = r.s.r, C = 0;
  22495. var header_cnt = {};
  22496. if(dense && !sheet[R]) sheet[R] = [];
  22497. var colinfo = o.skipHidden && sheet["!cols"] || [];
  22498. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  22499. for(C = r.s.c; C <= r.e.c; ++C) {
  22500. if(((colinfo[C]||{}).hidden)) continue;
  22501. cols[C] = encode_col(C);
  22502. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  22503. switch(header) {
  22504. case 1: hdr[C] = C - r.s.c; break;
  22505. case 2: hdr[C] = cols[C]; break;
  22506. case 3: hdr[C] = o.header[C - r.s.c]; break;
  22507. default:
  22508. if(val == null) val = {w: "__EMPTY", t: "s"};
  22509. vv = v = format_cell(val, null, o);
  22510. counter = header_cnt[v] || 0;
  22511. if(!counter) header_cnt[v] = 1;
  22512. else {
  22513. do { vv = v + "_" + (counter++); } while(header_cnt[vv]); header_cnt[v] = counter;
  22514. header_cnt[vv] = 1;
  22515. }
  22516. hdr[C] = vv;
  22517. }
  22518. }
  22519. for (R = r.s.r + offset; R <= r.e.r; ++R) {
  22520. if ((rowinfo[R]||{}).hidden) continue;
  22521. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  22522. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
  22523. }
  22524. out.length = outi;
  22525. return out;
  22526. }
  22527. var qreg = /"/g;
  22528. function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
  22529. var isempty = true;
  22530. var row = [], txt = "", rr = encode_row(R);
  22531. for(var C = r.s.c; C <= r.e.c; ++C) {
  22532. if (!cols[C]) continue;
  22533. var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
  22534. if(val == null) txt = "";
  22535. else if(val.v != null) {
  22536. isempty = false;
  22537. txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
  22538. 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; }
  22539. if(txt == "ID") txt = '"ID"';
  22540. } else if(val.f != null && !val.F) {
  22541. isempty = false;
  22542. txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
  22543. } else txt = "";
  22544. /* NOTE: Excel CSV does not support array formulae */
  22545. row.push(txt);
  22546. }
  22547. if(o.blankrows === false && isempty) return null;
  22548. return row.join(FS);
  22549. }
  22550. function sheet_to_csv(sheet, opts) {
  22551. var out = [];
  22552. var o = opts == null ? {} : opts;
  22553. if(sheet == null || sheet["!ref"] == null) return "";
  22554. var r = safe_decode_range(sheet["!ref"]);
  22555. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  22556. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  22557. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  22558. var row = "", cols = [];
  22559. o.dense = Array.isArray(sheet);
  22560. var colinfo = o.skipHidden && sheet["!cols"] || [];
  22561. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  22562. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  22563. var w = 0;
  22564. for(var R = r.s.r; R <= r.e.r; ++R) {
  22565. if ((rowinfo[R]||{}).hidden) continue;
  22566. row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
  22567. if(row == null) { continue; }
  22568. if(o.strip) row = row.replace(endregex,"");
  22569. if(row || (o.blankrows !== false)) out.push((w++ ? RS : "") + row);
  22570. }
  22571. delete o.dense;
  22572. return out.join("");
  22573. }
  22574. function sheet_to_txt(sheet, opts) {
  22575. if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
  22576. var s = sheet_to_csv(sheet, opts);
  22577. if(typeof $cptable == 'undefined' || opts.type == 'string') return s;
  22578. var o = $cptable.utils.encode(1200, s, 'str');
  22579. return String.fromCharCode(255) + String.fromCharCode(254) + o;
  22580. }
  22581. function sheet_to_formulae(sheet) {
  22582. var y = "", x, val="";
  22583. if(sheet == null || sheet["!ref"] == null) return [];
  22584. var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
  22585. var cmds = [];
  22586. var dense = Array.isArray(sheet);
  22587. for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
  22588. for(var R = r.s.r; R <= r.e.r; ++R) {
  22589. rr = encode_row(R);
  22590. for(C = r.s.c; C <= r.e.c; ++C) {
  22591. y = cols[C] + rr;
  22592. x = dense ? (sheet[R]||[])[C] : sheet[y];
  22593. val = "";
  22594. if(x === undefined) continue;
  22595. else if(x.F != null) {
  22596. y = x.F;
  22597. if(!x.f) continue;
  22598. val = x.f;
  22599. if(y.indexOf(":") == -1) y = y + ":" + y;
  22600. }
  22601. if(x.f != null) val = x.f;
  22602. else if(x.t == 'z') continue;
  22603. else if(x.t == 'n' && x.v != null) val = "" + x.v;
  22604. else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
  22605. else if(x.w !== undefined) val = "'" + x.w;
  22606. else if(x.v === undefined) continue;
  22607. else if(x.t == 's') val = "'" + x.v;
  22608. else val = ""+x.v;
  22609. cmds[cmds.length] = y + "=" + val;
  22610. }
  22611. }
  22612. return cmds;
  22613. }
  22614. function sheet_add_json(_ws, js, opts) {
  22615. var o = opts || {};
  22616. var offset = +!o.skipHeader;
  22617. var ws = _ws || ({});
  22618. var _R = 0, _C = 0;
  22619. if(ws && o.origin != null) {
  22620. if(typeof o.origin == 'number') _R = o.origin;
  22621. else {
  22622. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  22623. _R = _origin.r; _C = _origin.c;
  22624. }
  22625. }
  22626. var cell;
  22627. var range = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}});
  22628. if(ws['!ref']) {
  22629. var _range = safe_decode_range(ws['!ref']);
  22630. range.e.c = Math.max(range.e.c, _range.e.c);
  22631. range.e.r = Math.max(range.e.r, _range.e.r);
  22632. if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
  22633. } else {
  22634. if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
  22635. }
  22636. var hdr = o.header || [], C = 0;
  22637. js.forEach(function (JS, R) {
  22638. keys(JS).forEach(function(k) {
  22639. if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
  22640. var v = JS[k];
  22641. var t = 'z';
  22642. var z = "";
  22643. var ref = encode_cell({c:_C + C,r:_R + R + offset});
  22644. cell = ws_get_cell_stub(ws, ref);
  22645. if(v && typeof v === 'object' && !(v instanceof Date)){
  22646. ws[ref] = v;
  22647. } else {
  22648. if(typeof v == 'number') t = 'n';
  22649. else if(typeof v == 'boolean') t = 'b';
  22650. else if(typeof v == 'string') t = 's';
  22651. else if(v instanceof Date) {
  22652. t = 'd';
  22653. if(!o.cellDates) { t = 'n'; v = datenum(v); }
  22654. z = (o.dateNF || table_fmt[14]);
  22655. }
  22656. else if(v === null && o.nullError) { t = 'e'; v = 0; }
  22657. if(!cell) ws[ref] = cell = ({t:t, v:v});
  22658. else {
  22659. cell.t = t; cell.v = v;
  22660. delete cell.w; delete cell.R;
  22661. if(z) cell.z = z;
  22662. }
  22663. if(z) cell.z = z;
  22664. }
  22665. });
  22666. });
  22667. range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
  22668. var __R = encode_row(_R);
  22669. if(offset) for(C = 0; C < hdr.length; ++C) ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
  22670. ws['!ref'] = encode_range(range);
  22671. return ws;
  22672. }
  22673. function json_to_sheet(js, opts) { return sheet_add_json(null, js, opts); }
  22674. /* get cell, creating a stub if necessary */
  22675. function ws_get_cell_stub(ws, R, C) {
  22676. /* A1 cell address */
  22677. if(typeof R == "string") {
  22678. /* dense */
  22679. if(Array.isArray(ws)) {
  22680. var RC = decode_cell(R);
  22681. if(!ws[RC.r]) ws[RC.r] = [];
  22682. return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
  22683. }
  22684. return ws[R] || (ws[R] = {t:'z'});
  22685. }
  22686. /* cell address object */
  22687. if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
  22688. /* R and C are 0-based indices */
  22689. return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
  22690. }
  22691. /* find sheet index for given name / validate index */
  22692. function wb_sheet_idx(wb, sh) {
  22693. if(typeof sh == "number") {
  22694. if(sh >= 0 && wb.SheetNames.length > sh) return sh;
  22695. throw new Error("Cannot find sheet # " + sh);
  22696. } else if(typeof sh == "string") {
  22697. var idx = wb.SheetNames.indexOf(sh);
  22698. if(idx > -1) return idx;
  22699. throw new Error("Cannot find sheet name |" + sh + "|");
  22700. } else throw new Error("Cannot find sheet |" + sh + "|");
  22701. }
  22702. /* simple blank workbook object */
  22703. function book_new() {
  22704. return { SheetNames: [], Sheets: {} };
  22705. }
  22706. /* add a worksheet to the end of a given workbook */
  22707. function book_append_sheet(wb, ws, name, roll) {
  22708. var i = 1;
  22709. if(!name) for(; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
  22710. if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
  22711. if(roll && wb.SheetNames.indexOf(name) >= 0) {
  22712. var m = name.match(/(^.*?)(\d+)$/);
  22713. i = m && +m[2] || 0;
  22714. var root = m && m[1] || name;
  22715. for(++i; i <= 0xFFFF; ++i) if(wb.SheetNames.indexOf(name = root + i) == -1) break;
  22716. }
  22717. check_ws_name(name);
  22718. if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  22719. wb.SheetNames.push(name);
  22720. wb.Sheets[name] = ws;
  22721. return name;
  22722. }
  22723. /* set sheet visibility (visible/hidden/very hidden) */
  22724. function book_set_sheet_visibility(wb, sh, vis) {
  22725. if(!wb.Workbook) wb.Workbook = {};
  22726. if(!wb.Workbook.Sheets) wb.Workbook.Sheets = [];
  22727. var idx = wb_sheet_idx(wb, sh);
  22728. // $FlowIgnore
  22729. if(!wb.Workbook.Sheets[idx]) wb.Workbook.Sheets[idx] = {};
  22730. switch(vis) {
  22731. case 0: case 1: case 2: break;
  22732. default: throw new Error("Bad sheet visibility setting " + vis);
  22733. }
  22734. // $FlowIgnore
  22735. wb.Workbook.Sheets[idx].Hidden = vis;
  22736. }
  22737. /* set number format */
  22738. function cell_set_number_format(cell, fmt) {
  22739. cell.z = fmt;
  22740. return cell;
  22741. }
  22742. /* set cell hyperlink */
  22743. function cell_set_hyperlink(cell, target, tooltip) {
  22744. if(!target) {
  22745. delete cell.l;
  22746. } else {
  22747. cell.l = ({ Target: target });
  22748. if(tooltip) cell.l.Tooltip = tooltip;
  22749. }
  22750. return cell;
  22751. }
  22752. function cell_set_internal_link(cell, range, tooltip) { return cell_set_hyperlink(cell, "#" + range, tooltip); }
  22753. /* add to cell comments */
  22754. function cell_add_comment(cell, text, author) {
  22755. if(!cell.c) cell.c = [];
  22756. cell.c.push({t:text, a:author||"SheetJS"});
  22757. }
  22758. /* set array formula and flush related cells */
  22759. function sheet_set_array_formula(ws, range, formula, dynamic) {
  22760. var rng = typeof range != "string" ? range : safe_decode_range(range);
  22761. var rngstr = typeof range == "string" ? range : encode_range(range);
  22762. for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
  22763. var cell = ws_get_cell_stub(ws, R, C);
  22764. cell.t = 'n';
  22765. cell.F = rngstr;
  22766. delete cell.v;
  22767. if(R == rng.s.r && C == rng.s.c) {
  22768. cell.f = formula;
  22769. if(dynamic) cell.D = true;
  22770. }
  22771. }
  22772. return ws;
  22773. }
  22774. var utils = {
  22775. encode_col: encode_col,
  22776. encode_row: encode_row,
  22777. encode_cell: encode_cell,
  22778. encode_range: encode_range,
  22779. decode_col: decode_col,
  22780. decode_row: decode_row,
  22781. split_cell: split_cell,
  22782. decode_cell: decode_cell,
  22783. decode_range: decode_range,
  22784. format_cell: format_cell,
  22785. sheet_add_aoa: sheet_add_aoa,
  22786. sheet_add_json: sheet_add_json,
  22787. sheet_add_dom: sheet_add_dom,
  22788. aoa_to_sheet: aoa_to_sheet,
  22789. json_to_sheet: json_to_sheet,
  22790. table_to_sheet: parse_dom_table,
  22791. table_to_book: table_to_book,
  22792. sheet_to_csv: sheet_to_csv,
  22793. sheet_to_txt: sheet_to_txt,
  22794. sheet_to_json: sheet_to_json,
  22795. sheet_to_html: sheet_to_html,
  22796. sheet_to_formulae: sheet_to_formulae,
  22797. sheet_to_row_object_array: sheet_to_json,
  22798. sheet_get_cell: ws_get_cell_stub,
  22799. book_new: book_new,
  22800. book_append_sheet: book_append_sheet,
  22801. book_set_sheet_visibility: book_set_sheet_visibility,
  22802. cell_set_number_format: cell_set_number_format,
  22803. cell_set_hyperlink: cell_set_hyperlink,
  22804. cell_set_internal_link: cell_set_internal_link,
  22805. cell_add_comment: cell_add_comment,
  22806. sheet_set_array_formula: sheet_set_array_formula,
  22807. consts: {
  22808. SHEET_VISIBLE: 0,
  22809. SHEET_HIDDEN: 1,
  22810. SHEET_VERY_HIDDEN: 2
  22811. }
  22812. };
  22813. var _Readable;
  22814. function set_readable(R) { _Readable = R; }
  22815. function write_csv_stream(sheet, opts) {
  22816. var stream = _Readable();
  22817. var o = opts == null ? {} : opts;
  22818. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  22819. var r = safe_decode_range(sheet["!ref"]);
  22820. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  22821. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  22822. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  22823. var row = "", cols = [];
  22824. o.dense = Array.isArray(sheet);
  22825. var colinfo = o.skipHidden && sheet["!cols"] || [];
  22826. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  22827. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  22828. var R = r.s.r;
  22829. var BOM = false, w = 0;
  22830. stream._read = function() {
  22831. if(!BOM) { BOM = true; return stream.push("\uFEFF"); }
  22832. while(R <= r.e.r) {
  22833. ++R;
  22834. if ((rowinfo[R-1]||{}).hidden) continue;
  22835. row = make_csv_row(sheet, r, R-1, cols, fs, rs, FS, o);
  22836. if(row != null) {
  22837. if(o.strip) row = row.replace(endregex,"");
  22838. if(row || (o.blankrows !== false)) return stream.push((w++ ? RS : "") + row);
  22839. }
  22840. }
  22841. return stream.push(null);
  22842. };
  22843. return stream;
  22844. }
  22845. function write_html_stream(ws, opts) {
  22846. var stream = _Readable();
  22847. var o = opts || {};
  22848. var header = o.header != null ? o.header : HTML_BEGIN;
  22849. var footer = o.footer != null ? o.footer : HTML_END;
  22850. stream.push(header);
  22851. var r = decode_range(ws['!ref']);
  22852. o.dense = Array.isArray(ws);
  22853. stream.push(make_html_preamble(ws, r, o));
  22854. var R = r.s.r;
  22855. var end = false;
  22856. stream._read = function() {
  22857. if(R > r.e.r) {
  22858. if(!end) { end = true; stream.push("</table>" + footer); }
  22859. return stream.push(null);
  22860. }
  22861. while(R <= r.e.r) {
  22862. stream.push(make_html_row(ws, r, R, o));
  22863. ++R;
  22864. break;
  22865. }
  22866. };
  22867. return stream;
  22868. }
  22869. function write_json_stream(sheet, opts) {
  22870. var stream = _Readable({objectMode:true});
  22871. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  22872. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  22873. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  22874. var o = opts || {};
  22875. var range = o.range != null ? o.range : sheet["!ref"];
  22876. if(o.header === 1) header = 1;
  22877. else if(o.header === "A") header = 2;
  22878. else if(Array.isArray(o.header)) header = 3;
  22879. switch(typeof range) {
  22880. case 'string': r = safe_decode_range(range); break;
  22881. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  22882. default: r = range;
  22883. }
  22884. if(header > 0) offset = 0;
  22885. var rr = encode_row(r.s.r);
  22886. var cols = [];
  22887. var counter = 0;
  22888. var dense = Array.isArray(sheet);
  22889. var R = r.s.r, C = 0;
  22890. var header_cnt = {};
  22891. if(dense && !sheet[R]) sheet[R] = [];
  22892. var colinfo = o.skipHidden && sheet["!cols"] || [];
  22893. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  22894. for(C = r.s.c; C <= r.e.c; ++C) {
  22895. if(((colinfo[C]||{}).hidden)) continue;
  22896. cols[C] = encode_col(C);
  22897. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  22898. switch(header) {
  22899. case 1: hdr[C] = C - r.s.c; break;
  22900. case 2: hdr[C] = cols[C]; break;
  22901. case 3: hdr[C] = o.header[C - r.s.c]; break;
  22902. default:
  22903. if(val == null) val = {w: "__EMPTY", t: "s"};
  22904. vv = v = format_cell(val, null, o);
  22905. counter = header_cnt[v] || 0;
  22906. if(!counter) header_cnt[v] = 1;
  22907. else {
  22908. do { vv = v + "_" + (counter++); } while(header_cnt[vv]); header_cnt[v] = counter;
  22909. header_cnt[vv] = 1;
  22910. }
  22911. hdr[C] = vv;
  22912. }
  22913. }
  22914. R = r.s.r + offset;
  22915. stream._read = function() {
  22916. while(R <= r.e.r) {
  22917. if ((rowinfo[R-1]||{}).hidden) continue;
  22918. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  22919. ++R;
  22920. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) {
  22921. stream.push(row.row);
  22922. return;
  22923. }
  22924. }
  22925. return stream.push(null);
  22926. };
  22927. return stream;
  22928. }
  22929. var __stream = {
  22930. to_json: write_json_stream,
  22931. to_html: write_html_stream,
  22932. to_csv: write_csv_stream,
  22933. set_readable: set_readable
  22934. };
  22935. if(typeof parse_xlscfb !== "undefined") XLSX.parse_xlscfb = parse_xlscfb;
  22936. XLSX.parse_zip = parse_zip;
  22937. XLSX.read = readSync; //xlsread
  22938. XLSX.readFile = readFileSync; //readFile
  22939. XLSX.readFileSync = readFileSync;
  22940. XLSX.write = writeSync;
  22941. XLSX.writeFile = writeFileSync;
  22942. XLSX.writeFileSync = writeFileSync;
  22943. XLSX.writeFileAsync = writeFileAsync;
  22944. XLSX.utils = utils;
  22945. XLSX.writeXLSX = writeSyncXLSX;
  22946. XLSX.writeFileXLSX = writeFileSyncXLSX;
  22947. XLSX.SSF = SSF;
  22948. if(typeof __stream !== "undefined") XLSX.stream = __stream;
  22949. if(typeof CFB !== "undefined") XLSX.CFB = CFB;
  22950. if(typeof require !== "undefined") {
  22951. var strmod = undefined;
  22952. if((strmod||{}).Readable) set_readable(strmod.Readable);
  22953. }
  22954. }
  22955. /*global define */
  22956. if(typeof exports !== 'undefined') make_xlsx_lib(exports);
  22957. else if(typeof module !== 'undefined' && module.exports) make_xlsx_lib(module.exports);
  22958. else if(typeof define === 'function' && define.amd) define('xlsx', function() { if(!XLSX.version) make_xlsx_lib(XLSX); return XLSX; });
  22959. else make_xlsx_lib(XLSX);
  22960. /* NOTE: the following extra line is needed for "Lightning Locker Service" */
  22961. if(typeof window !== 'undefined' && !window.XLSX) try { window.XLSX = XLSX; } catch(e) {}