Search code examples
sassas-macro

When I am exporting a SAS dataset to csv; it is trimming all the leading spaces in the characters


When I am exporting a SAS dataset to csv; it is trimming all the leading spaces in the characters. Please help me to retain all the leading spaces in the csv output. The statement used is:

Proc Export Data = Globl_Mth_Sumry
OutFile = "&GMUPath.\20&RptYr._&RptMt.\03 Output\01 GMU\&Brnd_Abbr.\&Brnd._&Mkt._Globl_Mth_Sumry_&RptMt.&RptYr.&NeuronQTR..csv" 
DBMS = CSV Replace; 
Run;

So, there is a column containing the list of countries which is like

Asia India China etc. But the csv file is showing it like:- Asia India China.

Please help.


Solution

  • I find this an interesting question, largely because I was confident I knew the answer... to find out I didn't.

    This is technically a solution, and if you're in a time crunch perhaps is sufficient, though I suspect it's too unwieldy to use in a practical fashion. First I generate the data (input using $CHAR8. to preserve leading spaces), then I output it using fixed column output rather than list output.

    data test;
    input
    @1 x $CHAR8.
    @9 y $CHAR8.;
    format x y $char8.;
    datalines;
         USA   China
      Canada N Korea
      Russia  Mexico
    ;;;;
    run;
    
     data _null_;
     file "c:\temp\test.csv" lrecl=80 dropover;
     set test;
     if _n_ = 1 then do;
     put "x,y";
     end;
     put @1 x $char8. @9 "," @10 y $char8.;
     run;
    

    Unfortunately, using DBMS=CSV does not seem to allow $CHAR8. to function as you would expect. I don't know why that is. The solution I expected was to write it out like this:

    data _null_;
    file 'c:\temp\test.csv' delimiter=',' DROPOVER lrecl=32767;
      if _n_ = 1 then        /* write column names or labels */
       do;
         put
            "x"
         ','
            "y"
         ;
       end;
     set  TEST;
     put x $ :char8. y $ :char8.;
      run;
    

    which is essentially the code printed to the log by PROC EXPORT, then with :$CHAR8. after each variable. For whatever reason, that (and a bunch of other similar things) didn't work. ODS CSV also does not seem to work for preserving leading spaces.