Sas reports to excel

  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Вы можете использовать proc export для быстрого экспорта данных из SAS в файл Excel.

В этой процедуре используется следующий базовый синтаксис:

/*export data to file called my_data.xlsx*/
proc export data =my_data
 outfile ="/home/u13181/my_data.xlsx"
 dbms =xlsx
 replace ;
 sheet ="First Data";
run ;

Вот что делает каждая строка:

  • data : имя набора данных для экспорта
  • outfile : Место для экспорта файла Excel
  • dmbs : формат файла для экспорта
  • replace : заменить файл, если он уже существует
  • лист : имя для отображения на листе в книге Excel

В следующих примерах показано, как использовать эту функцию на практике.

Пример 1: экспорт одного набора данных в один лист Excel

Предположим, у нас есть следующий набор данных в SAS:

/*create dataset*/
data my_data;
 input A B C;
 datalines ;
1 4 76
2 3 49
2 3 85
4 5 88
2 2 90
4 6 78
5 9 80
;
run ;

/*view dataset*/
proc print data =my_data;

Мы можем использовать следующий код для экспорта этого набора данных в файл Excel с именем my_data.xlsx :

/*export dataset*/
proc export data =my_data
 outfile ="/home/u13181/my_data.xlsx"
 dbms =xlsx
 replace ;
 sheet ="First Data";
run ;

Затем я могу перейти к месту на своем компьютере, куда я экспортировал файл, и просмотреть его в Excel:

Данные в Excel соответствуют набору данных из SAS, а лист в книге Excel называется «Первые данные», как я указал в операторе экспорта proc .

Пример 2: экспорт нескольких наборов данных в несколько листов Excel

Предположим, у нас есть два набора данных в SAS:

/*create first dataset*/
data my_data;
 input A B C;
 datalines ;
1 4 76
2 3 49
2 3 85
4 5 88
2 2 90
4 6 78
5 9 80
;
run ;

/*create second dataset*/
data my_data2;
 input D E F;
 datalines ;
1 4 90
2 3 49
2 3 85
4 5 88
2 1 90
;
run ;

Мы можем использовать следующий код для экспорта обоих наборов данных в один и тот же файл Excel на разных листах:

/*export first dataset to first sheet in Excel*/
proc export data =my_data
 outfile ="/home/u13181/my_data.xlsx"
 dbms =xlsx
 replace ;
 sheet ="First Data";
run ;

/*export second dataset to second sheet in Excel*/
proc export data =my_data2
 outfile ="/home/u13181/my_data.xlsx"
 dbms =xlsx
 replace ;
 sheet ="Second Data";
run ;

Затем я могу перейти к месту на своем компьютере, куда я экспортировал файл, и просмотреть его в Excel.

Первый лист под названием «Первые данные» содержит первый набор данных:

И второй лист под названием «Вторые данные» содержит второй набор данных:

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные задачи в SAS:

Как нормализовать данные в SAS
Как переименовать переменные в SAS
Как удалить дубликаты в SAS
Как заменить пропущенные значения нулем в SAS


You can use proc export to quickly export data from SAS to an Excel file.

This procedure uses the following basic syntax:

/*export data to file called my_data.xlsx*/
proc export data=my_data
    outfile="/home/u13181/my_data.xlsx"
    dbms=xlsx
    replace;
    sheet="First Data";
run;

Here’s what each line does:

  • data: Name of dataset to export
  • outfile: Location to export Excel file
  • dmbs: File format to use for export
  • replace: Replace the file if it already exists
  • sheet: Name to display on sheet in Excel workbook

The following examples show how to use this function in practice.

Example 1: Export One Dataset to One Excel Sheet

Suppose we have the following dataset in SAS:

/*create dataset*/
data my_data;
    input A B C;
    datalines;
1 4 76
2 3 49
2 3 85
4 5 88
2 2 90
4 6 78
5 9 80
;
run;

/*view dataset*/
proc print data=my_data;

We can use the following code to export this dataset to an Excel file called my_data.xlsx:

/*export dataset*/
proc export data=my_data
    outfile="/home/u13181/my_data.xlsx"
    dbms=xlsx
    replace;
    sheet="First Data";
run;

I can then navigate to the location on my computer where I exported the file and view it in Excel:

The data in Excel matches the dataset from SAS and the sheet in the Excel workbook is called “First Data” just like I specified in the proc export statement.

Example 2: Export Multiple Datasets to Multiple Excel Sheets

Suppose we have two datasets in SAS:

/*create first dataset*/
data my_data;
    input A B C;
    datalines;
1 4 76
2 3 49
2 3 85
4 5 88
2 2 90
4 6 78
5 9 80
;
run;

/*create second dataset*/
data my_data2;
    input D E F;
    datalines;
1 4 90
2 3 49
2 3 85
4 5 88
2 1 90
;
run;

We can use the following code to export both datasets to the same Excel file in different sheets:

/*export first dataset to first sheet in Excel*/
proc export data=my_data
    outfile="/home/u13181/my_data.xlsx"
    dbms=xlsx
    replace;
    sheet="First Data";
run;

/*export second dataset to second sheet in Excel*/
proc export data=my_data2
    outfile="/home/u13181/my_data.xlsx"
    dbms=xlsx
    replace;
    sheet="Second Data";
run;

I can then navigate to the location on my computer where I exported the file and view it in Excel.

The first sheet titled “First Data” contains the first dataset:

And the second sheet titled “Second Data” contains the second dataset:

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Normalize Data in SAS
How to Rename Variables in SAS
How to Remove Duplicates in SAS
How to Replace Missing Values with Zero in SAS

Friday. January 17, 2020 — 3 mins

Overview

  • ODS: TAGSETS.EXCELXP VS. EXCEL
  • PROC REPORT

ODS

ODS (Output Delivery System): delivers output in a variety of formats, including HTML, Rich Text Format (RTF), PostScript (PS), Portable Document Format (PDF), and SAS data sets.

Traditional SAS output: designed for line–printer

Basic ODS syntax:

ODS TRACE ON </<options>>; 
	ODS <destination> <FILE=filename>; 
	ODS OUTPUT output-object-name=SAS-data-set-name; 
	ODS <destination> SELECT output-object-name|ALL|NONE; 
		... PROC ...
	ODS <destination> CLOSE;  
ODS TRACE OFF; 
  • Destinations: ODS can be used to route quality presentation files to various destinations, including LISTING (default), HTML, RTF, PRINTER, and PDF.
  • Object: Output objects are created by ODS to store the formatted results of most SAS procedures.
  • Style: Styles define the presentation attributes of a report, such as font and color.

Very often, we report SAS tables to Excel. In this case we can utilize ODS TAGSETS.EXCELXP and ODS EXCEL.

1. ODS Excel

Starting in SAS 9.4 maintenance release 3, ODS Excel destination creates .xlsx files that can be used with Microsoft Office 2010 or later. ODS Excel Formats With SAS format, such as comma7..

Syntax:

ods _all_ close;
ods excel file="/myshare/sample.xlsx" style= <style name> options(<option1 option2>); /*Opens Excel*/
...
ods excel close; /*Closes Excel */

Style

You can view the list of styles that are available at your site by submitting the statements below:

proc template;
     list styles;
run; quit;

2. ODS TAGSETS.EXCELXP

ExcelXP tagset creates a Microsoft XML spreadsheet file, which can be used with Excel 2002 and later. ExcelXP tagset does not create a native Excel format (.xlsx). ExcelXP tagset Formats With TAGTTR, i.e. TAGATTR = <attribute>.

Syntax:

ODS TAGSETS.EXCELXP PATH="/path/" file="file.xls" style=<style> options(<option1> <option2>)
options(<option3>);

To see references to Suboptions, submit the following code:

ODS tagsets.excelxp file="test.xml" options(doc="help");

Example: TAGGATR Formats preserve comma’s & trailing zeroes

ods tagsets.excelxp path="/path/" file="excelxp.xls" style=printer options(header_data_associations="yes" autofit_height='yes')
options(embedded_titles="yes" embedded_footnotes='yes' absolute_column_width="37,9,9");
proc report data=section1 nowd spanrows split='|' style(header)=[fontweight=bold fontsize=10pt font=(Times, 8pt)];
column name ("Special Census" number pc);
	define name / "Subject" f=$table1f. font=(TimesNewRoman, 10pt)];
	define number / 'Number' style(column)=[tagattr="format:#,##0" font=(TimesNewRoman, 10pt)] ; 
	define pc / 'Percent' style(column)=[tagattr="format:##0.0" font=(TimesNewRoman, 10pt)] ;


Proc Report

To control the report in an Excel Workbook, we can utilize ODS combined with PROC REPORT. The SAS paper Unleash the Power of PROC REPORT with the ODS EXCEL Destination has very detailed examples. Here I list some common used demos.

Demo: Multiple Worksheets

ods tagsets.excelxp path="/path/" file="test.xls" style=<style> options(<option>)
ods tagsets.excelxp options(sheet_name = 'Sheet 1');
	proc report;
	...
	run;
	
ods tagsets.excelxp options(sheet_name = 'Sheet 2');
	proc report;
	...
	run;
ods tagsets.excelxp close;

Example: Cell Merge
SPANROWS option works on column that uses GROUP or ORDER.

ods excel file="&file" options(sheet_name="test");
ods escapechar='~';
ods text="~S={font_size=14pt font_weight=bold vjust=m}~SAS Community";
ods text="~S={font_size=14pt font_weight=bold vjust=m}";

proc report data=sashelp.class nowd spanrows ;
     column ('~S={foreground=purple}Measures' weight height)  
            ('~S={foreground=green}Information' name age sex);
     define sex / order style(column)={vjust=c just=c};
run;

ods excel close;

Demo: Transpose

proc report data=&data nowd;
     column league team,captain;
     define league / group;
     define team / across;
     define captain / display;
run;


Reference

  • Introduction to the Output Delivery System (ODS)
  • ODS TAGSETS.EXCELXP and ODS EXCEL SHOWDOWN
  • Using the New ODS EXCEL Destination in SAS® 9.4
  • Unleash the Power of PROC REPORT with the ODS EXCEL
  • Beyond the Basics: Advanced PROC REPORT Tips and Tricks
  • PROC REPORT STYLE IN HEADER
  • A Deep Dive into the SAS® ODS Excel Destination (TAGATTR)
  • Exporting formulas to Excel using the ODS ExcelXP tagset
  • How to Use Microsoft Formats with ODS

Extra:

  • TABULATE Procedure
  • Introduction to PROC TABULATE

SAS output is rarely the form in which results are presented. Many create results tables in Excel. This page will provide an example of how to generate a multi-tab spreadsheet
containing SAS results.  We will be using the Output Delivery System (ODS)
to do so.  ODS allows you to generate tabular output from your raw output
that can be placed into Excel sheets.  In the code below, we are creating
an Excel file (giving it a name and location), indicating a style to be used
(“minimal” in this example), and specifying a few other options.

ODS TAGSETS.EXCELXP
file='D:worksas9regression.xls'
STYLE=minimal
OPTIONS ( Orientation = 'landscape'
FitToPage = 'yes'
Pages_FitWidth = '1'
Pages_FitHeight = '100' );

After this code, we can analyze our data and a new tab will be created for each separate ODS table from your output.

proc reg data = ats.hsb2;
  model write = female math read;
run;
quit;
proc format;
  value fm 1='Female' 0='Male' ;
  value ses 1='Low' 2='Middle' 3='High';
run;

After completing our analysis, we “close” the Excel file.

ods tagsets.excelxp close;

We can now open the Excel file and see the separate tabs for each ODS table.

Image excelSS1

The style
indicated effects the appearance of the output we see in Excel.  For
example, we used the “minimal” style and we can look at the ANOVA table in the
second tab for an example of this style:

Image excelSS2

To see a list of the
available styles, run the SAS code below:

ods listing;
proc template; 
list styles; 
run; 
quit;

We employed a few of the “options” to format our results in Excel.  To
see the full list of options, run the SAS code below:

filename temp temp;
ods tagsets.ExcelXP file=temp options(doc='help');
ods tagsets.ExcelXP close;

We can look at another style and some additional options.  In the
example code below, we create a two-way frequency table in SAS and output the
results to Excel with the “printer” style and we have added a title to the
output in Excel with the embedded_titles option in our ODS options
statement.


ODS TAGSETS.EXCELXP
file='D:worksas9tab2.xls'
STYLE=Printer
OPTIONS ( Orientation = 'landscape'
FitToPage = 'yes'
Pages_FitWidth = '1'
Pages_FitHeight = '100' 
embedded_titles = 'yes');

title 'Mean Write Scores by SES and Female';
proc format;
  value fm 1='Female' 0='Male' ;
  value ses 1='Low' 2='Middle' 3='High';
run;
proc tabulate data = ats.hsb2;
  class ses female;
  var write /style = {tagattr='format:000'};
  table ses=''*mean, 
        write=''*[style={tagattr='format:#0.00'}]*female='' /  rtspace=42;
  format female fm. ses ses.;
run;
ods tagsets.excelxp close;

We can view these results to see how the “printer” style appears in Excel:

Image excelSS3

For further details on sending results from SAS to Excel, see Vincent DelGobbo’s paper

Creating Multi-Sheet Excel Workbooks the Easy Way with SAS
.

Suppose I have 2 SAS dataset: test1.sas & Test2.sas. Now I want to export these 2 dataset into excel, where in the excel file Sheet1 will have test1.sas data & in Sheet2 will have test2.sas data.

How to do it?

Reeza's user avatar

Reeza

20.1k4 gold badges21 silver badges37 bronze badges

asked Mar 7, 2012 at 14:21

Beta's user avatar

Start with this paper. This and this are also good references.

Using ODS, you can output your data using reporting procs (Ex. Proc PRINT and REPORT) to XML. Not only can you create multisheet output, but you can format dates, set autofilters and place headers.

answered Mar 7, 2012 at 14:41

Jay Corbett's user avatar

Jay CorbettJay Corbett

27.9k21 gold badges56 silver badges74 bronze badges

1

The ODS methods in @CarolinaJay65’s answer are very flexible, but they might be overkill if you just want a raw export.

A simpler option, if it’s available in your SAS installation, is to use the excel libname engine. This allows you to use an excel workbook as a sas library, with each dataset in the library occupying one sheet in the workbook.

http://www.wuss.org/proceedings09/09WUSSProceedings/papers/app/APP-Benjamin.pdf

If you also want to automate lots of formatting or generate further output (e.g. charts), an alternative to using ODS is to create a VBA macro, save it in a template workbook, and have SAS call that macro to run on your output via a DDE command:

http://www.lexjansen.com/pharmasug/2005/coderscorner/cc21.pdf

This allows you to use excel’s macro recorder to capture the actions you want to automate, rather than having to work out how to produce the equivalent output via ODS / DDE.

answered Mar 10, 2012 at 14:05

user667489's user avatar

user667489user667489

9,4112 gold badges22 silver badges35 bronze badges

0

If it’s not something you want to automate, and you are using the Base SAS IDE, you can simply right-click on the dataset in the SAS Explorer window and select View in Excel.

answered Mar 7, 2012 at 15:32

Robert Penridge's user avatar

Robert PenridgeRobert Penridge

8,3942 gold badges34 silver badges54 bronze badges

1

I’d say the easiest way to export to excel (depending on your version of SAS) is to use PROC EXPORT and specify excel as your dbms. You can specify the same file to be updated but a different tab for each proc export you call.

So as an example with two datasets on two separate tabs:

proc export data=test1 dbms=excel
replace outfile ="C:Your_file_pathyour_file.xls";
sheet = sheet1;
run;

proc export data=test2 dbms=excel
replace outfile ="C:Your_file_pathyour_file.xls";
sheet = sheet2;
run;

answered May 18, 2015 at 5:15

Yarrney's user avatar

If you need to format the output without touching the Excel document (I worked in a banking department where outputs were read only) you can use XML to do this .

answered Feb 13, 2019 at 16:32

Drew's user avatar

DrewDrew

213 bronze badges

Понравилась статья? Поделить с друзьями:
  • Sas add in for excel
  • Sap способы выгрузки в excel
  • Sap работа с excel
  • Sap отчеты в excel
  • Sap нет выгрузки в excel