You are on page 1of 8

PaperCC011

ExchangingdatabetweenSASandMicrosoftExcel

YuqingXiao,SouthernCompany,Atlanta,GA

ABSTRACT
TransferringdatabetweenSASandMicrosoftExcelhasgainedpopularityovertheyears.Manymethodswere
developedbydifferentgroupsofpeople,fromstandarddatasteptomostrecentSASODStagset.Withmanyoptions
availabletoday,onemaywonderWhichwouldfitmysituationthebest?Thispaperbrieflydiscusesseveraloptions
forimportingandexportingdatafrom/toMicrosoftExcelusingSASandtheirprosandcons.

INTRODUCTION
MicrosoftOfficeisthemostpopulartoolusedintodaysbusiness.ClientsoftenprovidedatainExcelworkbooks
and/orliketoreceivereports,analyticalresultsinExcelformat.Somecanbesimpleonesheetdataworkbooks
somemayrequiremultiplesheetswithmanyformattingandtablessomearesimplecreationofnewworkbooks
some maydesireanupdateofanexistingworkbookratherthanrecreationofthefile.Manymethodologieswere
developedand/ordiscoveredbySASusergroupsrespondingtothoseneeds.Researchingand learning themare
timeconsuming.Thispapercollectsafewcommonwaysofimporting/exportingdataandincludessome brief
discussionontheirusages.NotethatallSAScodeanddiscussionsarebasedonSAS9.1.3althoughtheyarenot
limitedtoit.

IMPORT/EXPORTDATAFROM/TOEXCEL
SomeofthecommonwaysofImport/Export:
DataStep
SASImport/ExportFacility
SAS/ACCESSLIBNAMEStatement
SAS/ACCESSPassThroughFacility
SASXMLEngine
DynamicDataExchange(DDE)
ODS
SASAddIntoMicrosoftOffice

DATASTEP
IfyouhaveasimpleonesheetExcelworkbook,importusingstandarddatastepmightbeagoodchoice.Firstyou
needtosavetheExcelworkbookincommadelimitedCSVformat.Thenyoucanreaditinwithdatastep.

Codeexampletoread.CSVfile:
Filenamemyfilec:\mywork\testfile.csv
Datasasdat
Infilemyfiledlm=,firstobs=2missover
Inputvar1var2$var3$var4
Run

Thismethodisrelativelysimple.AlmostallSASusersshouldknowhowtowriteadatasteptoreadintextfiles,and
youhavethecontrolovervariablenames,typesand/orlength.ThismethodworkswithbothWindowsSASandUNIX
SAS(additionalstepsmaybeneededtoFTPCSVfiletoyourUNIXbox).Someofthedrawbacksarethatitdoesnt
workwithmultiplesheets,youhavetosupplythevariablenamesand/or informatspecifications(althoughyoucan
writemoresophisticatedcodetoautomate thejob),datagetshiftedwhenthereareblankcells,plusyoulose
additionalinformationthatcanbestoredinXLSformatwhenyouconvertit.

Forexport,usingPUTstatementwithinthedatastepcanoutputCSVorXMLfiletobeopenedinExcel.Itseasyto
writeCSVfile,butlimitedtoplainonesheetworkbooks.XMLfilecanhavecomplexstructuresformoresophisticated
workbookswithformulas,pivottablesetc,butwritingXMLfilefromscratchisnotadauntingtasktoaverageSAS
users.A trickfordoingthisistocreatetheworkbookwithallthedesiredfeaturesandsaveinXMLformatfirst, then
openitwithtexteditorandcopy/pastethetextintoyourSASprogram,wrapeachlineinPUT,manuallydeal
withfewembeddedsinglequotesandplacetheminadatastep.Customtweakoftheprogrammaybenecessaryin
somecases.TheresultcanbeopenedinExceljustasifitwasgeneratedwithExcel.

1
Codeexampleforoutput .CSVfile:
Filenamemyfilec:\mywork\testfile.csv
Data_null_
setsasdat
filemyfiledelimiter=','dsd
if_n_=1thendo
put'name1'',''name2'',''name3'
end
putvar1var2$var3$var4
Run

Datastepisveryflexibleandcandocomplexjobs.Toconvertresultsfromprocedures,youneedtooutputthemto
SASdatasetsinordertousethismethod.

SASIMPORT/EXPORTFACILITY
Anothereasywaytoimport/exportXLSfileistouseSASImport/Exportwizard.Forimport,gotoFileImport
data,chooseMicrosoftExcelappropriateversionfromdropdownlist,chooseworkbookandworksheetyoudlike
toreadin,namethedatasetandthewizardwilldotherestforyou.FollowFileExportdataforexport.Youcan
alsosaveacopyofImport/Export WizardgeneratedIMPORT/EXPORTprocedurecodeforsubsequentuseorwrite
yourown.Import/ExportwizardforXLSformatonlyavailableforWindowsandPROCIMPORT/EXPORTcandeal
withXLSfileinbothWindowsandUNIXenvironmentbutthe XLSfilehastoresideonPC.

SASIMPORTWizard:

CodeexampleforPROCIMPORT(Windows):
ProcImportdatafile="c:\mywork\testfile.xls"
out=work.sasdatdbms=excelreplace
sheet="mydata$"
getnames=yes
mixed=no
scantext=yes
usedate=yes
scantime=yes
Run

CodeexampleforPROCIMPORT(UNIX):
ProcImportdatafile="c:\mywork\testfile.xls"
out=work.sasdatdbms=excelcsreplace
server=market /*NameofPCfilesserver */
port=1234 /*PortnumberlisteningonthePCserver*/
version='2002'
sheet=mydata
scantext=yes
usedate=yes
scantime=yes
dbsaslabel=none
textsize=512
Run

2
CodeexampleforPROCEXPORT(UNIX):
Procexportdata=work.sasdat
outfile="c:\mywork\testfile.xls"dbms=excelcsreplace
sheet=mydata
version="2002"
server=market /*Servername*/
port=1234 /*Portnumber */
Run

Thisisaprettyefficientmethod.Noadditionalstepsrequiredcolumnnamescanbereservedasvariablenamesor
thereversemultipleworksheetscanbereadinorwrittenoutinseparatestepsblankcellsarehandledproperly.The
disadvantagesarethatSAS/ACCESStoPCfilesisrequiredforimporting/exportingXLSformat,youhavelittle
controlovervariablenames,typesand/orlength.Therecouldbecaseswherecolumnisrecognizedbytheprogram
asnumericandcharactervaluesaresettomissingorviceversa.Plus,theentireworksheethastobeimported,you
cantchoosecolumnsand/orranges.

ThePROCIMPORT/EXPORTactually imports/exportsXLSfilesthroughgeneratedSAS/ACCESScode.Amore
customizedapproachistousePROCACCESS.Itsmoreflexible,candefinecolumnsandrangestobereadin,can
changevariablenames,types, formatsandmore.However,itsonlyavailableunderWindowsandmightbealittlebit
beyondbeginnerSASusersscope.

CodeexampleforPROCACCESS:
ProcAccessdbms=xls
/*createaccessdescriptor*/
creatework.dat_view.access
path="c:\mywork\testfile.xls"
worksheet=mydata
range='a1..j39'
getname=yes
scantype=5
mixed=yes
assign=no
renamevar1=name1
var2=name2
format1 5.0
2 $4
/*createSASview*/
creatework.dat_view.view
selectvar1var2var3
Run
/*createSASdataset*/
Datasasdat
setwork.dat_view
Run

Anotherverysimilarwayofdoingthisisthroughtheuseof.DBFformat.Itworksprettymuchlikeimporting/exporting
XLSfileexceptthatfilecanbesavedunderboth WindowsandUNIXenvironment.

Codeexampletoread/write .DBFfile:
ProcImportdatafile="c:\mywork\testfile.dbf"
out=work.sasdatdbms=dbfreplace
getdeleted=no
Run
Procexportdata=work.sasdat
outfile="c:\mywork\testfile.dbf"dbms=dbfreplace
Run

AfewdrawbacksarethatseparateDBFfilesmaybeneededformultisheetworkbooks,oneneedstopayextra
attentiontohiddencolumnsand/ordatafilters inExcelbecausedataarelostwhensavedasDBFfile.Also,allthe
formattingarelostafterconversion.

3
SAS/ACCESSLIBNAMESTATEMENT
SAS/ACCESSprovidesothermeansofaccessing/creatingExcelfilesusingthenLIBNAMEstatement.Simplyassign
alibraryreferencetoanExcelworkbookanddirectlyreadfromand/orwritetoit.ForUNIXSAS,usepcfilesoption
withservernameandportname toconnecttoPCfiles.Excelworkbookcanbeeitheranewworkbookoranexisting
one.Thismethodworkswithmultipleworksheetsandisavailableanywherealibraryreferenceisvalid,suchasdata
step,SASSQLandSASProcedures.

CodeexampleforImport/ExportExcelfiles(Windows):
Libnamemyxls'c:\mywork\testfile.xls'
/*importdata*/
Datasasdat
setmyxls.mydata
Run
/*exportExcelworkbook*/
Datamyxls.mydata2
setsasdat
Run
Procsql
createtablemyxls.summaryasselectvar1,var2,var3
fromsasdatgroupbyvar4
quit
Libnamemyxlsclear

CodeexampleforImportExcelfiles(UNIX):
Libnamemyxlspcfilesserver=marketport=1234path='c:\mywork\testfile.xls'
Datasasdat
setmyxls.'mydata$'n
Run
Libnamemyxlsclear

SAS/ACCESSPASSTHROUGHFACILITY
AnalternativetoSAS/ACCESSLIBNAMEstatementisthePassThroughfacility.ItusesSAS/ACCESStoconnectto
adatasourceandsendsdatasourcespecificSQLstatementsdirectlytothedatasource.Itenablesyoutoretrieve
dataorasubsetofthedata fromExcelworkbookworksheetsand/ornamedranges.Itsalsoavailableinboth
WindowsandUNIXenvironment.

CodeexampleforSAS/ACCESSPassThrough(Windows):
Procsql
connecttoexcel(path='c:\mywork\testfile.xls')
createtablesasdatasselect*fromconnectiontoexcel
(selectvar1,var2,var3frommydata)
disconnectfromexcel
Quit

CodeexampleforSAS/ACCESSPassThrough(UNIX):
Procsql
connecttopcfiles(path='c:\mywork\testfile.xls'server=marketport=1234)
createtablesasdatasselect*fromconnectiontopcfiles
(select*frommydata)
disconnectfrompcfiles
Quit

SASXMLENGINE
ExcelcanopenandsaveXMLdocuments.SASXMLengine translatesdatabetweenXMLdocumentandSASdata
sets.ItcanreadandwriteXMLdocumentswithSASdatasteporProcedures.However,withoutfurtherinstructions
XMLenginereadsonlyfilesthatconformtocertainstructures.Otherwise,youcancreateanXMLMapwhichtellsthe
XMLenginehowtointerprettheXMLmarkupintoSASdatasets.AsupportingtoolcalledXMLMapperisavailable
fromSAS.Ithasagraphicalinterfacewiththreeprimarypanes.OpenanddisplaytheXMLdocumentinitsXML
primarypaneandcreateXMLMAPbydraganddropelementsfromXMLprimarypaneintoXMLMAPprimarypane,
thenspecifytheXMLMAPintheLIBNAMEstatementtotranslatetheXMLdocument.

4
SASXMLMapper:

CodeexampleforSASXMLengine:
/*assignlibreftoXMLdocumentlocationandspecifyXMLengine*/
Filenamemymap'c:\mywork\myfile.map'
Libnamemypathxml'c:\mywork\myfile.xml'xmlmap=mymap
/*readinXMLdocumentwithdatastep*/
datasasdat
setmypath.mydata
run
/*readinXMLdocumentwithprocedures*/
proccopyin=mypathout=sasdat
selectgrades
run
/*createXMLdocumentwithdatastep*/
Datamypath.myfile
setsasdat
Run

XMLhasmanybenefitsandisbecomingverypopularinstoringdatanowadays.Itssoftwareandhardware
independentcharacteristicmakesitveryusefulinsharingdatabetweendifferentpartiesandrelativelyimmuneto
changesintechnology.Eventhough,therearecertaindisadvantagesassociatedwiththismethod.First, inExcel,
savingspreadsheetsasXMLDatarequiresusersuppliedXMLschema.Althoughyoucanavoidthisbychoosing
saveasXMLspreadsheet,theresultingfilestructurecanbe complicateandIhaventhadanysuccessbuildingXML
Mapwiththisformatoption.Second,XMLengineusesmoreprocessingtimethanotherstrategies.Andlast,XML
documentscanbelarge.Itsnotrecommendedwhenspaceornetworkbandwidthisanissue.

DYNAMICDATAEXCHANGE(DDE)
DDEisusedtodynamicallyexchangeinformationbetweenWindowsapplications.TransferringdatabetweenExcel
spreadsheetsandSAS isamongDDEsmanypotentialuses.Inordertoreadorwritethedata,MicrosoftExcel
workbookmustbeopenedfirst.ItcanbedoneeithermanuallyorbySAScode.ThenaDDElinkisestablished
throughFILENAMEstatement.TextstringknownasDDETripletmustbespecifiedandenclosedinquotationmarks.
Tripletconsistsofthreepartsintheformapplicationname|topic!item,whereapplicationisExcelinthiscase,topic
istypicallythefullpathfilenamewhichyouwanttosharedataanditemistherange.Aneasytricktodeterminethe
tripletistocopythedesiredrangeofcellsto theclipboardandtheninPCSAS,gotoSolutions>Accessories>DDE
triplet.Theexacttripletwillappearinthedialogbox.Datacanthenbereadorwrittenwithdatastep.And last,you
maywanttoclosetheworkbookandExcelapplication.

Codeexampletoread.XLS filethroughDDE:
/*invokeExcelandopenworkbook*/
Optionsnoxwaitnoxsync
x'"c:\programfiles\microsoftoffice\office11\excel.exe"'
Data_null_
rc=sleep(5)
Run

5
Filenameddecmddde'excel|system'
Data_null_
fileddecmd
put'[FILEOPEN("c:\mywork\testfile.xls")]'
Run
/*readdesiredrowsandcolumnsfromExcelfileintoSAS*/
Filenamemyfiledde'excel|c:\mywork\[testfile.xls]mydata!r2c1:r10c3'
Datasasdat
infilemyfilenotabdlm=09xdsdmissover
informatvar15.var2$4.var3$20.
inputvar1var2$var3$
Run
/*closeworkbookandquitExcel*/
Data_null_
filexlin
put'[FILECLOSE("c:\mywork\testfile.xls")]'
put'[QUIT()]'
Run

Codeexampletowrite.XLSfilethroughDDE:
/*invokeExcelandopennewworkbook*/
Optionsnoxwaitnoxsync
x'"c:\programfiles\microsoftoffice\office11\excel.exe"'
Data_null_
rc=sleep(5)
Run
/*saveblankspreadsheettodesiredlocation*/
Filenameddecmddde'excel|system'
Data_null_
fileddecmd
put'[SAVE.AS("c:\mywork\testfile.xls")]'
Run
/*definefilerefusingDDEaccessmethod*/
Filenamemyfiledde'excel|c:\mywork\[testfile.xls]sheet1!r1c1:r&rows.c3'notab
/*writetoExcelworkbook*/
Data_null_
filemyfile
setwork.sasdat
if_n_=1thenput'name1''09'x'name2''09'x'name3'
putvar109xvar209xvar3
Run
/*saveworkbookandquitExcel*/
Filenameddecmddde'excel|system'
Data_null_
fileddecmd
put'[SAVE()]'
put'[QUIT()]'
Run

DDEgivesyoutheflexibilityofspecifyingthedesiredrangesforread/writeandcontrolovervariabletypesandlength.
Inaddition,youcanissueExcelcommandstocustomizethe spreadsheet,likesetformat,font,color,header/footeror
runmacros,etc.Youmayconsiderthismethodwhencreatinghighlycustomizedspreadsheetsorupdatingexisting
spreadsheets.ItalsoworkswitholderversionsofSAS.TheshortcomingsarethatitsnotavailableforUNIXand
Excelmustberunningforittowork.Plus,youhavetoknowExcelcommandstodoformatting.

ODS
ODSstandsforOutputDeliverySystem.Itsaverypowerfultoolwhichcangeneratealmostlimitlesstypesofoutput
withhighlycustomizedformatting. ODSorganizesoutputfromdatastepsorproceduresintoaseriesofobjectsand
sendsallorpartofthemtouserspecifieddestinations.ChoiceofODSdestinationsdeterminesthetypeofoutputto
begenerated,suchasHTML,XML,PDFetc.Bydefault,LISTINGdestinationisopenandallothersareclosed.To
createmultisheetExcelworkbooks,specifytagsets.ExcelXPODSdestinationandwraptheprocedureand/ordata

6
stepbetweenODSopenandclosestatements.AppearanceoftheoutputiscontrolledbyODSstyles.Youcancreate
yourownstyledefinitionormodifyanexistingone throughPROCTEMPLATE. Withcustomstyledefinitions,SAS
ODScangenerateverysophisticatedExcelworkbookwithformulas,highlighting,wrappedtextandmuchmore.

SamplecodeforcreatingmultisheetspreadsheetwithODS:
/*closeodslistingdestination*/
Odslistingclose
/*opentagsetsdestinationandsendoutputtoxmlfile*/
Odstagsets.ExcelXPpath='c:\mywork'file='testfile.xml'style=mystyle
Odstagsets.ExcelXPoptions(sheet_name=mydata)
Data_null_
setsasdat
fileprintods=(variables=(var1var2var3))
put_ods_
Run
Odstagsets.ExcelXPoptions(sheet_name=summary)
OdsExcludeMomentsTestForLocation
Procunivariatedata=sasdat
Byvar2
varvar1
Run
/*closetagsetsdestinationandreopenlistingdestination*/
Odstagsets.ExcelXPclose
Odslisting

ODSisanexcellentwayofexportingSASdatasetstoExcelworkbooksandcanmakefancylookingExcel
workbookswithoutopeningandrunningExcel.ItcanalsooutputCSVorHTMLfilestobeopenedinExcel.One
possibledrawbackisthatexploringmanystyleoptionsforcustomizedformattingcanbetimeconsumingandmaynot
beyourbestchoicewhenmovingdataisthecentralfocus.

SASADDINTOMICROSOFTOFFICE
SASAddInforMicrosoftOfficeismynewfavoritemethodofsharingdatabetweenSASandMicrosoftOffice
products.ItsprovidedwithSASBIserverorSASEnterpriseBIserverandcanbedistributedamongtheentire
organization.Afterinstallingit,youcanopenSASdatasetinExcel,viewand/oreditdata,analyzethedataanddo
reporting.DatainExcelspreadsheetcanbecopiedbacktoaSASserverandsavedasSASdataset.Toopena
SASdataset,findSASmenuinthetoolbar,selectSASOpenDataSourceIntoWorksheet,chooseyourSAS
serverandSASdatasetandclickopen.Thenyouwillbepromptedtoselectvariablestobebroughtintothe
spreadsheet.TocopyaworkbooktoaSASdataset,selectthedesiredrangeofdata,gotoSASActive
DataCopytoSASServer,usebrowsertofindthelocationwhereyoudliketosavethedata,name thedataset
thensave.

SASMenuinMicrosoftExcel:

Thereareafewthingsyouneedtobeawareof.First,SASAddInforMicrosoftOfficemustconnecttoan
environmentrunningSASBIServerorSASEnterpriseBIServer.Second, thedatafoldermustberegisteredwith
SASBIServertobeseeninbrowserwindows.Andnoteyoumaywanttochangethedefaultnumberofdisplayed
recordsatOptionswindowunderSASmenuitem.

CONCLUSION
Sofar,weexploredseveralcommonwaysofexchangingdatabetweentwoapplications.Theyallhavesome pros
andconsandmaybesuitablefordifferentsituations.Thetablebelowsummarizessomeoftheircharacteristicsand
mayhelpyourmethodselection.Yet,evenmore methodsexist.Theycanbecustommade macroslike%sas2xls,

7
%sas2csv.sasand%xlxp2sas,dataconversionsoftware,orsolutionswithotherlanguageslikeXML,VSTOandVBA
etc.

SummaryofDataExchangingMethods:
Available Available Workwith Excel OtherSAS
Import Export Workwith
withPC withUNIX Multisheet Formatting packages
capable capable procedures
SAS SAS workbook available required
DataStep
Import/Export
SAS/ACCESS
Wizard
Import/Export
SAS/ACCESS
procedure
ProcAccess SAS/ACCESS
SAS/ACCESS
SAS/ACCESS
LIBNAME
SAS/ACCESS
SAS/ACCESS
PassThrough
SASXML

Engine
DDE
ODS
SASAddIn SASBI

REFERENCES
1. SASOnlineDOC,SASInstituteInc.
<http://support.sas.com/91doc/docMainpage.jsp>
2. ImportingExcelfilestoSASDatasets.
<http://archive.chesapeakebay.net/cims/importing_excellb.pdf>
3. CurtisA.Smith.ImportingExcelFilesIntoSASUsingDDE
<http://www.lexjansen.com/wuss/2007/ApplicationsDevelopment/APP_SmithC_ImportingExcelFiles.pdf>
4. LawrenceHelbers,AlexVinokurov. SASOutputtoExcel:DDEandBeyond.NESUG2002Conference.
5. RalphWinters.ExcellentWaysofExportingSASDatatoExcel.NESUG2004Conference.
6. VincentDelGobbo.CreatingANDImportingMultiSheetExcelWorkbookstheEasyWaywithSAS.
SUGI2006Conference,paper11531.
7. MarkTerjeson.HowtocreateanexcelpivottableusingSASOnlineposting.7Apr.2005. SASL
<http://www.listserv.uga.edu/cgibin/wa?A2=ind0504A&L=sasl&P=R30054>
8. AlanChurchill.ConvertSASdatasetstoExcelOnlineposting.23Jan.2006.
<http://savian.blogspot.com/search?q=sas+to+excel>

ACKNOWLEDGMENTS
IwouldliketothankmycolleaguesBobBolen,ChaoyingHsiehandDianCunninghamfortheirthoroughreviewand
valuablecomments.

CONTACTINFORMATION
Yourcommentsandquestionsarevaluedandencouraged.Contacttheauthorat:
YuqingXiao
SouthernCompanyMarketingServices
Bin10206
241RalphMcGillBlvd.NE
Atlanta,GA30308
WorkPhone: (404)5064619
Email: yxiao@southernco.com

SASandallotherSASInstituteInc.productorservicenamesareregisteredtrademarksortrademarksofSAS
InstituteInc.intheUSAandothercountries.indicatesUSAregistration.
Otherbrandandproductnamesaretrademarksoftheirrespectivecompanies.