首页 > 解决方案 > 如何使用宏读取 SAS 中的多个 excel 文件?

问题描述

我想通过导入多个 excel 文件在 SAS 中创建一个数据集。excel文件里面有相同的变量,保存在同一个目录下,文件名称一致:

excel_20150101 excel_20150201

我将如何在 SAS 中写这个?

标签: macrossas

解决方案


此宏将遍历目录中的所有 Excel 文件,并将导入名为 DS1、DS2、DS3 的数据集中的内容……。DS400(如果有 400 个 Excel 文件)。请确保仅在特定目录中保留 Excel(.xlsx) 文件。

options merror mlogic mprint symbolgen spool;
%macro drive(dir,ext);                                                                                                                  
  %local filrf rc did memcnt name i;                                                                                                    

  /* Assigns a fileref to the directory and opens the directory */                                                           
  %let rc=%sysfunc(filename(filrf,&dir));                                                                                               
  %let did=%sysfunc(dopen(&filrf));                                                                                                     

   /* Loops through entire directory */                                                                                                 
   %do i = 1 %to %sysfunc(dnum(&did));                                                                                                  

     /* Retrieve name and import each Excel file */                                                                                                   
     %let name=%qsysfunc(dread(&did,&i));    
     proc import 
        out=DS&i
        datafile= "Y:\Excel\&name"
        dbms=XLSX replace;
        getnames=yes;
     run;                                                                                                                                                                                                                                                  
   %end;                                                                                                                                

  /* Closes the directory and clear the fileref */                                                                                      
  %let rc=%sysfunc(dclose(&did));                                                                                                       
  %let rc=%sysfunc(filename(filrf));                                                                                                                                                                                                                                          
%mend drive;                                                                                                                            

/* First parameter is the directory of where your files are stored. */                                                                  
/* Second parameter is the extension you are looking for.           */                                                                  
%drive(Y:\Excel,xlsx);     

推荐阅读