Production Ready Macros for SAS Application Developers
https://github.com/sasjs/core
mp_ds2csv.sas
Go to the documentation of this file.
1/**
2 @file
3 @brief Export a dataset to a CSV file
4 @details Export to a file or a fileref
5 Usage:
6
7 %mp_ds2csv(sashelp.class,outref="%sysfunc(pathname(work))/file.csv")
8
9 @param ds The dataset to be exported
10 @param outfile= The output filename - should be quoted.
11 @param outref= The output fileref (takes precedence if provided)
12 @param outencoding= The output encoding to use (unquoted)
13
14 @version 9.2
15 @author Allan Bowe (credit mjsq)
16**/
17
18%macro mp_ds2csv(ds, outref=0, outfile=, outencoding=0
19)/*/STORE SOURCE*/;
20
21%if not %sysfunc(exist(&ds)) %then %do;
22 %put %str(WARN)ING: &ds does not exist;
23 %return;
24%end;
25
26%if %index(&ds,.)=0 %then %let ds=WORK.&ds;
27
28%if &outencoding=0 %then %let outencoding=;
29%else %let outencoding=encoding="&outencoding";
30
31%local outloc;
32%if &outref=0 %then %let outloc=&outfile;
33%else %let outloc=&outref;
34
35/* credit to mjsq - https://stackoverflow.com/a/55642267 */
36
37/* first get headers */
38data _null_;
39 file &outloc dlm=',' dsd &outencoding lrecl=32767;
40 length header $ 2000;
41 dsid=open("&ds.","i");
42 num=attrn(dsid,"nvars");
43 do i=1 to num;
44 header = trim(left(coalescec(varlabel(dsid,i),varname(dsid,i))));
45 put header @;
46 end;
47 rc=close(dsid);
48run;
49
50/* next, export data */
51data _null_;
52 set &ds.;
53 file &outloc mod dlm=',' dsd &outencoding lrecl=32767;
54 put (_all_) (+0);
55run;
56
57
58%mend mp_ds2csv;