问题
New to this, so apologies. I have a file in SAS that I need to export as a CSV and I need to add double quotes to all fields. How can I accomplish this? Thanks in advance.
回答1:
There are many ways to create a CSV file from SAS. Using proc export
won't wrap every field in double-quotes, so the easiest one that will do this is the %ds2csv()
macro. This assumes you have SAS 9.2 or later. The documentation for it can be found here:
http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002683390.htm
An example of running it:
%ds2csv(data=sashelp.retail, runmode=b, csvfile=c:\class.csv);
Produces:
"Retail sales in millions of $","DATE","YEAR","MONTH","DAY"
"$220","80Q1","1980","1","1"
"$257","80Q2","1980","4","1"
"$258","80Q3","1980","7","1"
回答2:
Here is another one using data step
data _null_;
file 'data_want.csv' dsd dlm = ',';
set data_have;
if _n_ = 1 then put @1 "variables name to input"; /* Add variable names */
put (_all_) (~);
run;
回答3:
Here is a way to get the same result with headers included
proc contents data=sashelp.class out=vars(keep=name varnum);run;
proc sql noprint;
select quote(strip(name)) into :vars separated by '|' from vars
order by varnum;
quit;
data _null_;
file 'test.txt' dsd dlm='|';
set sashelp.class;
if _n_ = 1 then put %sysfunc(quote(&vars.));
put (_all_) (~);
run;
回答4:
I know it's an old question, but my 2 pence...
The macro below does not quote numeric values that are formatted to a character value, but it's easy to implement.
%macro csvQuoteChars(lib=,dset=,outPath=);
proc contents data=&lib..&dset out=c(keep=name type) noprint;
run;
%let dsid = %sysfunc(open(c));
%let nobs = %sysfunc(attrn(&dsid,nlobs));
data _null_;
set &lib..&dset;
file "&outPath\&lib..&dset..csv" dsd;
%do i=1 %to &nobs;
%let rc = %sysfunc(fetchobs(&dsid,&i));
%let vName = %sysfunc(getvarc(&dsid,1));
%let vType = %sysfunc(getvarn(&dsid,2));
%put &=vName &=vType;
%if &vType = 2 %then %do;
put (&vName) (~) @;
%end;
%else %if &vType = 1 %then %do;
put &vName @;
%end;
%if &i = &nobs %then %do;
put;
%end;
%end;
run;
%let dsid = %sysfunc(close(&dsid));
%mend csvQuoteChars;
%csvQuoteChars(lib=sashelp,dset=class,outPath=d:\temp);
来源:https://stackoverflow.com/questions/25572025/sas-proc-export-to-csv-how-to-add-double-quotes