Creating Excel File Through XML
2012-04-19 22:35
302 查看
from CreatingExcelFileThroughXML Weallknowthattheonlyplacetokeepdataisadatabase.Surprisingly,150%ofourcustomersfirmlybelievethatdatahastobestoredinExcelsheets.Asexpectedyourcustomerrejectedyourfirstandquickattempt toexporttoExcelfilesusingCOPYTO.Nowyou'resufferingfromautomationhelltryingtokeepexecutiontimeofasimpleexportdowntolessthananhour.There'snoreasonto! EversinceExcelXP(Excel2000withdownloadableplugins)ExcelsupportsXMLfilesinXMLSS(XMLSpreadsheet)format.That'salmostadecadenow!EvenyourmostcostsensitivecustomermighthavenowreplacedtheirOffice 95andOffice97installations,meaningthere'snoneedtochastiseyourselfwithExcelautomation. CreatingExcelfilesIfyouneedtostoredata,ofcourse,youstoretheminatable.Atleastthat’swhateveryVisualFoxProdeveloperwilltellyou.Aska.NETdeveloperthesamequestionandthey’llwonderwhyyouwouldevenconsidersomethingotherthanXMLfiles. Ourcustomersarebusinesspersons.Theonlyplacefordatathatonecantakeseriouslyis–oneshouldn’tneedtopointouttheobvious–naturallyExcel.Exceldrivesbusinessestoadegreethatmostofuswon’teven wanttoknowabout.JustrecentlyIcameacrossanotheronemyself.Oneofthenotsosmallbanks(Barclay’sBank)andasimilarwell-knownairline(BritishAirways)worktogetherinsomecountries. UndersomeconditionsBarclay’sissuesavouchertoitscustomerthattheycanredeemwithBritishAirways.Employeestracktheseconditionsmanually,andthensendanemailtoBritishAirwayswheretherecipientisentered inalargeExceldocument.ToredeemthevouchercustomersneedtocallBritishAirwayswhereafewpeoplehavethepermissionstolookintothefile.Thesearebigcorporationsandthevouchersinquestionsarefortheirtopcustomers.Andstill,Excelwins againstacarefullycraftedsolutiontoautomatedataexchangebetweenthetwocompanies. Exceliseverywhere.Excelmakesdataaccessible.WhenyouproviderdatatousersinExcelformat,theyareusuallyhappy,becausenowtheycanworkwithdata.DatainaSQLserverorintheapplicationislockedaway. Theycanonlydowhattheprogramallowsthemtodo.ForeverylittlebittheyhavetoaskITtoimplementanewfeature.Budgetsneedtobeallocated,decisionsmade,endlessmeetings,justtodosomethingwithdataonaserverthatwouldbeano-brainer inExcel. VisualFoxProoffersmultiplewaystoexportdatatoExcel.ThesimplestonesofthemaretheCOPYTOandEXPORTcommands.TheydirectlysupportseveralolderversionsofExcel.Alternatively,youcancreateatabdelimited oraCSVfile.NamethefilewithanXLSextension.Excelissmartenoughtorealizethatthesefilescan’tbenativeXLSfiles.Rather,Excelautomaticallyconvertsthesefileswhenyouopenthem. Office2007introducedalittlechangethatmakesthisonetinybitmoredifficult.Presumablyforsecurityreasons,Excel2007andExcel2010promptforconfirmationwhenyouopenafilewherethefileextensiondiffers fromthecontent. Thequickandsimpleapproachesareexactlythis:quickandsimple.There’snotalotofchoiceyouhaveregardingformattingordatatypes.Exceldeductsthetypefromthecontent.Ifsomethinglookslikeanumber,it willbecomeanumber. WithODBCandOLEDByoucandirectlywriteintoExcelsheets.Thisgivesyouquiteabitofcontroloverhowdataisinterpretedandwheredataisplacedinthedocument.There’szilchcontroloveranyvisualaspect,though. Youcan’tcontrolthelayout,columnwidths,worksheetnames,andsoforth.PamelaThalackerwroteaboutusingODBCtocontrolExcelintheNovember2007issueofFoxProAdvisor( Formany,manyyearsautomationwastheonlywaytotransferdatatoExcelandcontrolformattingatthesametime.Therearetwokindsofautomation.TheolderoneofthetwoisDynamicDataExchange,DDEforshort.The currenttechnologyiscalledOLEautomationorjustautomation.Bothtechnologiessufferfromthesamedisadvantages. Theyaren’tknownforbeingblazinglyfast.NoneofthemwillworkwhenExcelisnotinstalledonthemachine.Infact,eventheversionofExcelisoftenrelevant.Withautomationyoucan’tensurethatnodialogcomes up.Thisrendersautomationunusableinwebserverscenarios. ExcelXPintroducedanewstorageformatthatsolvesalloftheseproblems:XML.Itwouldn’tbeatrueMicrosoftformat,iftheformathadn’tchangedovertime.ExcelXPandExcel2003useasyntaxthatiscalledXMLSpreadsheet (XMLSS).Adetaileddescriptionoftheformatisavailableonthefollowingwebsite: Excel2007andExcel2010openXMLSSfileswithoutanyproblem.Thenativeformatofthesetwoversions,though,isOfficeOpenXML.DonotconfusethiswiththesimilarlynamedOpenOfficeXML.Thelatteristhenative formatofOpenOffice,thecompetitionontheofficeproductmarket.OfficeOpenXML,orOOXML,isanewISOstandardsuggestedbyMicrosoft.ThestandardhasbeenacceptedinApril2008.XMLSSislimitedtoonlyExcel.YoucanstorejustaboutanyOffice documentasOOXML,though.OOXMLsupportsthefullfeaturesetoftheMicrosoftOfficeSuite. XMLSSismuchmorelimited.NoteveneveryfeatureofExcelsupported.Missingare,forinstance,pictures,embeddedActiveXcontrolsorOLEobjects,andVBAprojectswhichmeansmacrosupport.Lackingsupportforpictures isactuallythemostmissedfeatureofXMLSS.ManycompaniesusetheirlogoinExcelsheets.TheselogoscannotbestoredinXMLformat. ForusXMLSShasonebigadvantageoverOOXML.It’sdramaticallyeasiertohandle.Youdon’tneedtogeneratedozensofdifferentfilesandstoretheminaZIParchive.XLSXfilesareinfactZIParchives.XMLSSexists longerandiseasier.Thismakesitaformatthatisprettywellsupported,evenoutsidetheOfficeproductfamily.There’sanimportfilterforOffice2000.UnlessyouhavetodealwithOffice95orOffice97,XMLSSisaprettysafeformat.Theremaining documentwillonlycovertheXMLSSformat. Asmentionedpreviously,youdon’thavetouseXMLasthefileextensionwhenyoucreateXMLSSfiles.Inthedefaultconfiguration,openingafilewiththeXMLextensionwouldstillopenMicrosoftExcelwhenthecontent isanXMLSSdocument.OfficeachievesthisbyusingasmallloaderapplicationthatlooksatthecontentoftheXMLfileandthendecideswhichapplicationtolaunch.ManyusersconfigurethecomputersothatWindowsdoesn’topenXMLfilesinOffice.Theloader doesn’tdisplaytherighticoninExplorer,though. Thereforeit’slessconfusingandmorecompatiblewhenyouusethefamiliarXLSextensionforyouXMLfiles.ExcelopenstheseasXMLspreadsheetsautomatically.ThesimplestformofsuchanXMLspreadsheetlookslike this: <?xmlversion="1.0"?> <Workbookxmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> <Worksheetss:Name="Sheet1"> </Worksheet> </Workbook> Thisdefinesaworkbookwithasingle,emptyworksheet.IfyouwouldsavethisdocumentfromExcel,you’dnoticethatExceladdsarealbunchoffurtherinformation.Allofthoseareoptionalandwouldonlyclutterthe file.ShouldyoueverneedtodebuganXMLSSfileitpaysofftorestrictthecontenttotheabsoluteminimum.Andyouwillneedtodebugthesefiles,trustme. BystartingwithanemptyworkbookIalreadybrokewiththehabitofbeginningwitha„HelloWorld“example.Letmeprovideyouwithonenow: <?xmlversion="1.0"?> <Workbookxmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> <Worksheetss:Name="Sheet1"> <Table> <Row> <Cell> <Datass:Type="String">Helloworld</Data> </Cell> </Row> </Table> </Worksheet> </Workbook> Someattributesarerequired.Forinstance,onthe<Data>tagyouhavetospecifywhichtypeofdatayouwanttostoreinthecell.ThisiscontrarytoExcel’snormalbehavior,whichistofigureoutthingsbasedonthe content.ThisisacommonthemeinXMLSS.YouwillseethatExceldoesnotattempttofigureoutanythingonitsown.ProvideallinformationasrequiredbyExcel,orbedoomed.That’syourchoice. Ifyoudon’tspecifythess:Typeattribute,Excelwon’topenthedocumentatall.Insteadyougetanerrordialog.IfyouusedautomationtoopentheXLSfile,ExcelforwardstheerrortoVisualFoxPro.It’stherefore agoodideatoencapsulateopeninganXMLSSdocumentintoaTRY…CATCH…ENDTRYblock. IfyouwritecodethatcreatesExcelfilesyou’lllikelyseethiserrormessagequitefrequently.ExcelisverypickyaboutthedataformatintheXMLfile.Forgetjustasingleattributeortag,ormisspellone,store datainthewrongformat,havetoomanyelementsofonekind,ortoofew,andExcelrefusestoopenthedocument. ThispickinessofExcelisn’ttheresultofafrustratedprogrammanageratMicrosoftwhodecidedthatdevelopersneedtosharehispain.IfyouhaveworkedwithXMLdocuments,youmostlikelyusedtheDOMparser.DOM meansDocumentObjectModel.Onceyouloadedadocumentintomemory,youcanwalkthroughanobjecttree,useXPathtosearchfornodes,andsoon.It’sacomfortablewayofaccessingXML. ExcelusesadifferentmodecalledtheSAXparser..NETmakesthisparseravailableastheSystem.Xml.XmlReaderclass.ThisparserreadstheentireXMLdocumentinasinglepasstoptobottom.Insteadofaskingforwhatever XMLnodeyouneed,yourcodereceivestheXMLnodesintheordertheyappearinthedocument.ThatmeansyouneedtowriteyourcodearoundthestructureoftheXMLfile,notviceversa. Whatyougainisperformance.UsingthisparserandinsistingontagsbeinginastrictordermakesitpossibleforExceltoopena50MBXMLdocumentwithintwoseconds.WiththeDOMparseryouwouldlikelyspendminutes forthesamedocument. DebuggingExcelfileisanartofitsown.Fortunately,Excelprovidessomeguidancewhenthefileformatiswrong.Unfortunately,thismightbelessthanyouexpect.Excelcreatesalogfileeverytimeyouopenaninvalid document.ThislogfilecontainsallerrorsandonWindowsXPisstoredin C:\DocumentsandSettings\<user>\LocalSettings\TemporaryInternetFiles\Content.MSO OnWindowsVistaandWindows7you’llfindthisfileinthefollowingdirectory: C:\Users\<user>\AppData\Local\Microsoft\Windows\TemporaryInternetFiles\Content.MSO AsI’vementionedabovethelogfiledoescontainanydetailsabouttheerror,theactualposition,etc.Theerrorlogonlyspecifiesthetagand,ifapplicable,theattributeorthevaluethatcausedtheproblem.However, ifyouhavehundredsorthousandsofcellsit’snotparticularhelpfultoknowthatoneofthemcontainsanerror. Rightnowoursampleworksheetdoesn’tlookparticularexciting.Let’sthereforestartexploitingsomemoreExcelfeaturesstepbystep. Thecontentconsistsofrowsandcells.Youdefinitelynoticedthatthisdoesn’tleaveanyroomforcolumns.There’saseparatetagforeverythingyoucanchangeonthecolumnlevel.Themostfrequentsettingneededfor columnsisthecolumnwidth.Toprovideyouwithabetterreadingexperience,IomitrepeatedelementsinthefollowingXMLsamples.YoufindthecompletedocumentforeverystepinthesessionmaterialontheCDorthedownloadablefiles.Changesarehighlighted inboldfont: <Table> <Columnss:Width="200"/> <Row>…</Row> </Table> Excelexpectsthatyoupassallsizesandpositionsinpoints,notinpixels.Apointisatypographicalunitthatis1/72thofaninch.Theactualpixelvaluedependsontheresolutionofyourmonitor.Astandardresolution formonitorsis96dpi.Someusersmighthaveenabledlargefontsonthedisplaypropertiesdialog.Inthiscasetheresolutionisoften120dpioranyothervalue.AsVisualFoxProapplicationalwaysusepixelsinsteadtwips(no,thisdoesn’thaveanything todowithTwitter),youcanusethefollowingformulatoconvertbetweenpixelsandpoints: pixels=points*96/72 points=pixels*72/96 Thecolumnwedefinedintheprevioussampleistherefore267pixelswide.Otheroptionsavailableonthecolumnlevelincludevisibility,automaticresizing,andsoon.Todefinemultiplecolumnsyousimplyaddmultiple <Column>tagstothe<Table>tag.Thereisnogroupingtagsuchas<Columns>. Thephysicalorderofthe<Column>tagsdefinestheorderofthecolumnsintheExcelsheet.Manytagsacceptthess:Indexattribute.Withthistagyoucanskiponeormultiplecolumns.Forinstance,ifyouwanttodefine thesizeofthefirstandthe10thcolumn,youwoulduse: <Columnss:Width="200"/> <Columnss:Index="10"ss:Width="200"/> XMLSSidentifiescolumnsbynumbers.Numberingstartswith1,notlikein.NETwith0.Columnnumber10isthesameastheJcolumninExcel.Youwilllikelyusethess:Indexattributequiteabitwiththe<Cell>tag. Youabsolutelyhavetospecifythecontentforevery<Cell>tagthatyouuse.Contentisn’toptional.Tokeepacellempty,youneedtoturnthiscellintoastringandpassanemptyvalue. JustlinkFoxProdistinguishesbetweenEMPTY()andISBLANK(),Excelkeepstrackofwhetheracellisusedornot,evenifthecontentisemptyinbothcases.Toleaveacelltotallyemptyandundefined,youhavetoskip thiscellintheXMLdefinitionusingthess:Indexattributeonthefollowingcolumn. Withina<Cell>tagyouusethe<Data>tagtodefinethecontentofacell,aswellasthetype.Thethreemostcommondatatypesarestrings,numbersanddatevalues. <Row> <Cell><Datass:Type="String">Helloworld</Data></Cell> <Cell> <Data ss:Type="DateTime">2008-05-01T00:00:00.000</Data> </Cell> <Cell><Datass:Type="Number">123.456</Data></Cell> </Row> Thereanumberofrulesregardingthecontentofacellthatyouhavetofollow.Everythingbetween<Data>and</Data>isthecontent.Firstofall,thecontentmustnothaveanyadditionalblanksorlinebreaks.Forthis reasonIinsertedthelinebreakinthepreviousexampleintothe<Data>tagitself,notbetweentagsasinthefollowing–invalid(!)–sample: <Datass:Type="DateTime"> 2008-05-01T00:00:00.000 </Data> Thelineabovewillcauseanerrorwhenyouattempttoopenthedocument.Excelwon’ttellyouwhichlinecausedtheerror.Atleastwhentheerrorisinthe<Data>tag,yougetanerrormessagethatactuallycontains avalue: XMLERRORinTable REASON:BadValue FILE:C:\Users\Christof\AppData\Local\Microsoft\Windows\TemporaryInternetFiles\Content.MSO\47D0ED28.xls GROUP:Cell TAG:Data VALUE:2008-05-01T00:00:00.000 Thecontentbetween<Data>and</Data>mustbeconvertibleaccordingtothedatatype.There’snocleanupperformedbyExcelbeforetheconversiontakesplace. AllstringvalueshavetobeprovidedinUTF-8format.ForEnglishtextUTF-8andANSIareidentical.However,umlautsusedinGermantexts,accentedcharactersusedineverycountryaroundtheUS,requireaconversion. VisualFoxPromakesthisaneasyjobwiththeSTRCONV()function: [<Datass:Type="String">]+STRCONV(cData,9)+[</Data>] IfyoupassafieldtoSTRCONV(),makesureyoutrimthevaluewiththeALLTRIM()function.Otherwisethecellcontentmightlookstrange,especiallywhenthecellisnotleftaligned.Numericalvaluesmustuseadecimal pointandnoseparators.ThisistrueindependentofthelanguageversionofExcelandtheregionalsettingsofWindows.ManyEuropeanuserswouldenter“1,23”inExcel.WithintheXMLdocument,however,thishastobecome“1.23”. IfyourapplicationusesSETSYSFORMATSONtorespecttheuserssetting,ordefinesSETPOINT,youneedtoresetthisvalueto“.”fortheexportprocess.EvenifyourapplicationonlyrunsintheUSandyoudon’thave aSpanishversion,youshouldmakeapointofchangingSETPOINT(punintended). LocallcPoint lcPoint=Set("Point") SetPointTo"." WiththissettinginplaceyoucanconvertnumericalvalueswithasimplecalltotheTRANSFORM()function. [<Datass:Type="Number">]+TRANSFORM(nData)+[</Data>] Numbersaren’toptional!Ifyouturnacellintoanumericvalue,youmustprovideanumber.Ifyoudon’thaveavalue,thezeroisagooddefaultvalue.Youcan’tleavethetagemptyorspecifysomethingelse.Thisis mainlyanissuewithNULLvalues.Inyougenericroutinesyoushouldusethefollowingexpression: TRANSFORM(NVL(nData,0)) Excelsavesdatevaluesasintegernumbers.Thisnumberisthenumberofdayssinceaparticulardate.WhenyoustoreadatevalueinanXMLspreadsheet,though,youhavetousethestandardXMLdateformat.Fortunately, there’safunctioninVisualFoxProthatperformstheconversionforyou: [<Datass:Type="DateTime">]+TTOC(tData,3)+[</Data>] Herecomestheconfusingpart:EventhoughyouspecifiedthedatatypeasdateandyoupassedadatevalueinXMLformat,whatyouseenwhenyouopenthespreadsheetinExcelisamerenumber.Datavaluesarenotautomatically formattedasdatevalues.Contrarytonumbersandstringsyouhavetoformatthecellexplicitly. ExcelusesstylessimilartoWordorCSS.However,Excelofferssignificantlylessflexibility.Stylesaredefinedina<Styles>tagontheworkbooklevel.Allsheetswithinaworkbookareusingthesamestyle.Every styleusedbyExcelcorrespondstoone<Style>tagthatdefinesvariousvisualaspects. <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet <Styles> <Styless:ID="styleDemo"> <NumberFormatss:Format="Standard"/> </Style> </Styles> <Worksheetss:Name="Sheet1">…</Worksheet> </Workbook> StylesinExceldonotsupportinheritance,atall.Moreover,youcanonlyassignonestyletoeachcell.Imagine,youhaveacellwithacomplexformatinvolvingconditions,abackgroundpattern,aborder,andsoon. Forthesummarylineyouneedexactlythesamestyle,exceptthatitneedstobebold.TheonlypossibilitytodothisinXMLSSistoduplicatethefirststyleandadjustthecopy.Ifyoumakechangestoonestyleyouhavetoremembertomakethesechanges inallplaces. Excelnamesallstylesas“S”followedbyanincrementingnumber.Youdon’thavetofollowthisexample.Justlikeyoudon’tnamevariablelc1tolc200inyourapplication,namingstylesthiswaymakesthemamaintenance nightmare.Youcanuseanytextyouwantforthestylename,aslongasyourememberthatthenameiscasesensitive.Don’tbesurprisedwhenyourcarefullycraftednamesdisappearafteryousavedthefileinExcel. Everytimeyousaveafile,Excelcompletelyregeneratesthelistofstyles.Stylesthatarenotusedanywhereinthespreadsheetareremovedfromthefile.AllothersstylesarenamedasExcelwouldnamethem,thatis, “S”followedbyanumber.Yourstylenamesaregone…forever. Whendeveloperssettleonnames,thosearen’tnecessarilythebestchoices.<NumberFormat>issuchatagwherenamemusthavebeenchosenbyadeveloperwithoutreflectingthechoicewithotherteammembers.Youcanthink of<NumberFormat>as<CellFormat>,aslongasyouwriteit<NumberFormat>.Thistagspecifiestheformatofcells,notjustnumericcells. Ifyouwanttodisplaythedatevaluefromoneofourprevioussamplesas“01-Mai-2008”(that’sGerman,notaspellingerror),youhavetoenterthefollowingcodeintoanEnglishversionofExcelwhentheregionalsettings fortheEnglishversionofWindowsareGerman: [$-409]T-MMM-JJJJ;@ Excelisextremelylanguagedependent.SomeofthiswillbiteyouwhenyoudealwithdifferentversionsofExcelordifferentregionalsettings.Butit’snotthattimeyet.Fornowyoucanbelucky,asformatsarestored languageindependentlyintheXMLfile.Conveniently,MicrosoftsettledontheEnglishformatinstructions: <Styless:ID="s22"> <NumberFormatss:Format="[ENG][$-409]d\-mmm\-yyyy;@"/> </Style> Youcanfindthecorrectformatstringusingtrialanderror.IpersonallyfinditmoreefficienttoformatthecellinExcelinthewayIwantit.ThensavethefileasXMLSpreadsheetandtakealookatthestyledefinition inthegeneratedfile.IthenjustcopyandpastethedefinitionintomyXMLfile. Thisbecomesabiteasierwhenyouformatthecellwithafontthatyoudon’tuseanywhereelseintheExcelsheet.WiththisyoucanopenthegeneratedXMLfileandmerelysearchforthefontnametoquicklyidentify thestyleusedbythiscell. ToformatacellwithacertainstyleyoupasstheIDofthestyletothe<Cell>tag’sstyleIDattribute: <Cellss:StyleID="s22"><Datass:Type="Da…</Data></Cell> Youcannotformatacellwithoutusingastyle.InHTMLandCSSyouhavethechoiceofcreatingaCSSselectorwiththestyleinformation,writingtheformatintothestyleattributeoruseoneoftheolderHTMLtagslike <B></B>toformattext.InExcelcreatingastyleandassigningittoacellisyouronlychoice. Asidefromtheformatstringyoucanalsochangethefont,styleandsizeinanXMLSSfile.Withinthe<Style>tagyouusethe<Font>tagtoalterthefontsettings: <Styless:ID="s22"> <Fontss:FontName="Tahoma"ss:Size="13" ss:Bold="1"ss:Color="silver"/> </Style> Switchessuchasss:Bold,ss:Italic,ss:Outline,ss:Shadow,ss:StrikeThrough,haveavalueofone,whenthestyleisactive,orzerowhenthestyleisdeactivated.Zeroisthedefaultvalueforallofthem.Anexception tothisisthess:Underlineattributewhichcanhavebe“Single”or“Double”.Ifnothingisspecified,thetextisnotunderlinedatall. Excelshineswhenitcomestofalsefriends.Therewasthe<NumberFormat>tagthatdoesn’tdealwithnumbers,thedateformatthatdoesn’tshowupasadate,emptycellsthatcannotbeempty,andsoforth.Colorsaresimilar. WithintheXMLfiles,ExcelusesahexadecimalnotationthatissimilartoHTML.Forinstance,thevalue#FF0000denotesred.Behindthe#-sign,youspecifythevaluesforred,blueandgreen.Eachisatwo-digithexadecimal value.Alternatively,youcanusethesamecolornamesthatInternetExplorerusesforwebsites.AlistofthesenamesisavailableonlineontheMicrosoftwebsite: Unfortunately,thetooltipnamesinthecolorselectiondialogofExceldonotmatchthesenames,soyoucandeductfromtheuserinterfacewhatvaluesyouhavetouseintheXMLfiletoobtainthesameeffect. ThepossibilitytospecifyhexvaluesmakesExcellookmuchmoreflexiblethanitactuallyis.FoxPro2.xusedcolorsetstospecifythecolorforvariouselements.Excelcallsthempalettes,buttheconceptisthesame. Apaletteispartoftheexcelworkbookandconsistsof40colorsforcells,eightcolorsforlinesandeightcolorsforfillingcharts.InExcelyoucanviewandeditthepalettewiththeTools>Options>Colorsmenuitem. Wheneveryouspecifyacolorinhexadecimalnotationinoneofthestyles,Excelsearchesthelistofall56availablecolors.Whenthereisnoexactmatch,Excelwillautomaticallyusetheclosestcolor.Beforeyoucan useyourowncolorsyouhavetodefineyourownpalettewithintheXMLfile: <Workbook> <Colors> <Color> <Index>37</Index> <RGB>#D4CAFA</RGB> </Color> </Colors> <Styles>…</Styles> <Worksheetss:Name="Sheet1">…</Worksheet> </Workbook> Indexcanbeanumberbetween1and56.RGBisthedesiredcolor.Youcannotusemorethan56differentcolorsinoneExcelworkbook. Therearemanymoreoptionstoformataspreadsheet.Youcanchangethebackgroundofacell,definethemarginforeverysideofthecell,defineaprintarea,selecttheactivecellwhenyouthespreadsheet,andmuch more.TheeasiestwaytofindoutwhatXMLyouhavetowriteistocreateanExceldocumentthatlooksexactlyasyouwantittolook.ThensavethespreadsheetasanXMLfileandlookforthestyleorcelldefinitions. XMLfilesarepuretextfiles.VisualFoxProprovidesextremelyflexiblewaystogeneratethesetextfiles.Youcancreatethementirelyprogrammaticallyfromthegroundup,oryouuseTEXTMERGEtogetherwithtemplates. WhenyoustartedgeneratingXMLfiles,youwon’tgobacktopureautomation. ThefollowingsamplegeneratesaformattedExcelsheetfromtheNorthwindCustomertablewhereeverysecondlineisdifferentlycolored: UseNorthwind\Customers SetPointTo"." LocallcFile lcFile=GetEnv("USERPROFILE")+"\Desktop\Customers.xls" IfFile(m.lcFile) Erase(m.lcFile) EndIf LocallcRows,lnField,luValue,lcStyle,lcData lcRows="" Scan lcRows=m.lcRows+"<Row>" ForlnField=1toFcount() luValue=Evaluate(Field(m.lnField)) lcStyle=Iif(Recno()%2==0,"even","odd") Docase CaseInList(Vartype(m.luValue),"C") lcData=; [<Datass:Type="String">]+Strconv(Alltrim(m.luValue),9)+[</Data>] CaseInList(Vartype(m.luValue),"N") lcData=; [<Datass:Type="Number">]+Transform(Nvl(m.luValue,0))+[</Data] Otherwise Loop EndCase lcRows=m.lcRows+; [<Cellss:StyleID="]+m.lcStyle+[">]+m.lcData+[</Cell>] EndFor lcRows=m.lcRows+"</Row>" endscan LocallcXML Texttom.lcXMLNoshowTextmerge <?xmlversion="1.0"?> <Workbookxmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> <Styles> <Styless:ID="even"> <Fontss:FontName="Tahoma"ss:Size="13"ss:Bold="1"/> </Style> <Styless:ID="odd"> <Fontss:FontName="Tahoma"ss:Size="13"ss:Color="red"/> </Style> </Styles> <Worksheetss:Name="Sheet1"> <Table><<m.lcRows>></Table> </Worksheet> </Workbook> EndText StrToFile(m.lcXml,m.lcFile) |
相关文章推荐
- Java上传Excel同时兼容2003和2007 解决read error和org.apache.poi.poifs.filesystem.OfficeXmlFileException异常
- Csharp: read excel file using Open XML SDK 2.5
- Using DocumentFormat.OpenXml to generate a new excel file in terms of temp excel file
- SSH架构易出现的问题之Error creating bean with name '*' defined in file [*.xml]
- ExcelPackage: Office Open XML Format file creation
- Python transfer file through xmlrpc
- Error creating bean with name 'userService' defined in class path resource [beans.xml]: Unsatisfied dependency expressed through
- Creating excel sheets through php with an image
- csharp:using OpenXml SDK 2.0 and ClosedXML read excel file
- Creating a custom server.xml file with Tomcat
- 在 Excel 2003 中创建 XML 映射 (Creating XML Mappings in Excel 2003)
- Csharp: read excel file using Open XML SDK 2.5
- .net Create Excel 2007 file with open xml
- Creating Excel File in Oracle Forms
- Creating a XML Document from scratch without using a file in C#
- Csharp: read excel file using Open XML SDK 2.5
- libxml/tree.h file not found
- 将excel转存为xml数据
- 利用.NET FileStreams将DTD插入XML文件中
- vtk实战(二十九)——读入未知格式XMLFile数据