As a Data Analyst it is common to create a dataset in SAS and carry out further analysis in Microsoft Excel. But, how do you export data from SAS to Excel?
Exporting data from SAS to Microsoft Excel can be done with the EXPORT procedure and the LIBNAME statement. The EXPORT procedure provides flexibility when it comes to including column labels or header names. Whereas exporting data with a LIBNAME statement gives you more options for subsetting data and creating new columns.
In this article, we discuss both methods in more detail and answer common questions such as:
- How to define a sheet name?
- How to export column labels?
- How to create an Excel file without a header?
Do you know? How to Import an Excel File
Sample Data
In this article, we use a sample dataset to export to Excel (work.my_data). This dataset is based on the CARS dataset from the SASHELP library, but with fewer columns.
The EXPORT Procedure
An easy way to export a table from SAS to Excel is with the EXPORT procedure (PROC EXPORT). This procedure is easy-to-understand and provides many options.
Syntax of PROC EXPORT
To export data from SAS to Excel with PROC EXPORT you need to define at least three parameters:
- DATA=-option to specify the SAS dataset you want to export. For example, DATA=work.my_data.
- OUTFILE=-option to define the output location and the file name. For instance, OUTFILE=”/folders/myfolders/export/cars.xlsx”
- DBMS=-option to specify the file extension such as DBMS=xlsx.
DATA=-option
The DATA=-option specifies the SAS dataset you want to export. You can either use a one- or two-level SAS name (i.e., with or without libref). When you export a dataset to Excel, you can use dataset options such as KEEP, RENAME, and WHERE in the DATA=-option.
OUTFILE=-option
The OUTFILE=-option specifies the location and file name of the exported dataset. The file name includes the extension. Keep in mind that the complete path (location and file name) can’t exceed 201 characters.
DBMS=-option
The DBMS=-option specifies the type of file the EXPORT procedure creates (e.g., .xlsx or .xls). It depends on the file type how much data SAS can export. For example, if you export data to Excel, the SAS dataset cannot exceed the maximum of 1,048,576 rows and 16,384 columns.
Examples
The SAS code below exports the work.my_data dataset to Excel and creates a file called cars.xlsx.
proc export data=work.my_data outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx; run;
Note 1: If you want to create an XLS-file with PROC EXPORT, you need to change the file extension in the OUTFILE=-option and use DBMS=xls.
proc export data=work.my_data outfile="/folders/myfolders/export/cars.xls" dbms=xls; run;
Note 2: You need the SAS/ACCESS Interface to PC Files license to export data from SAS to Excel. To check if this license is available on your SAS installation, you can use the PROC SETINIT statement.
How to Overwrite Existing Files
By default, PROC EXPORT doesn’t overwrite existing files. If you try to do this, SAS will write an error to the log and will stop executing. To change this default behavior, you need the REPLACE option. If you use the REPLACE option, you can export and overwrite an existing file.
This is an example of how to use the REPLACE option.
proc export data=work.my_data outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx replace; run;
Do you know? How to Archive Multiple Excel Files in one ZIP File from SAS
How to Define an Excel Sheet Name
By default, PROC EXPORT creates an Excel file where the sheet name is equal to the filename. However, you can overwrite this default behavior and define the sheet name with the SHEET=-option. You need to write the sheet name between quotation marks, and it cannot exceed 31 characters.
In the example below, we create the Excel file cars.xlsx and call the sheet All Cars.
proc export data=work.my_data outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx replace; sheet="All Cars"; run;
How to Export an Excel File with Multiple Sheets
Many Excel workbooks have multiple worksheets. Nevertheless, PROC EXPORT creates only one file with one sheet. So, how do you create an Excel file with multiple sheets using SAS?
You can create an Excel file with multiple sheets by submitting one PROC EXPORT statement for each sheet. In each PROC EXPORT statement, you change the DATA=-option and the SHEET=-option. But, the OUTFILE=-option and the DBMS=-option remain unchanged.
In the example below, we create an Excel file with two sheets, namely All Cars and Ford Cars. As you can see, we use dataset options, such as KEEP, RENAME, and WHERE in the DROP=-option.
/* One Excel File with Multiple Sheets */ /* Create a Sheet with All Cars */ proc export data=work.my_data outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx replace; sheet="All Cars"; run; /* Create a Sheet with only Ford Cars */ proc export data=work.my_data (where=(Make="Ford") keep=Make Model rename=(Model = Ford_Model)) outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx replace; sheet="Ford Cars"; run;
How to Export a Table to Excel with SAS Labels
SAS datasets have column names and, optionally, column labels. Column labels can contain special characters such as blanks and percentage signs. For this reason, column labels are more elegant and are frequently used in reports. However, by default, PROC EXPORT exports the column names instead of the column labels. So, how do you export the column labels with PROC EXPORT?
You use the LABEL option to export a sheet with the column labels instead of the column names. You place this option after the REPLACE option. If a column doesn’t have a label, then PROC EXPORT exports the column name.
With the SAS code below, we export the column labels instead of the column names.
/* Export the column labels */ proc export data=work.my_data outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx replace label; sheet="All Cars"; run;
With a PROC CONTENTS statement, you can check whether a column has a label. For instance, some of the columns of our sample data work.my_data have labels.
proc contents data=work.my_data; run;
Do you know? How to Change Variable Labels
How to Export a Table to Excel without Header (Column Names)
Typically, you want your Excel file to have a header (i.e., column names). However, sometimes you need to create a file without one. So, how do you export data from SAS to Excel with a header?
You can prevent SAS from exporting the header to Excel by setting the PUTNAMES=-option to No. By default, this option is set to Yes. In contrast to other options, you write the word NO without quotation marks.
In the example below, we use PUTNAMES=NO to prevent SAS from adding column names to the Excel file.
proc export data=work.my_data outfile="/folders/myfolders/export/cars.xlsx" dbms=xlsx replace; sheet="All Cars"; putnames=NO; run;
Do you know? How to Save SAS Output as a PDF file
Export data from SAS to Excel with the LIBNAME Statement
The LIBNAME Statement
A less known, but also very efficient way to export data from SAS to Excel is by creating a library with the LIBNAME statement.
Normally, you use the LIBNAME statement to create a library to store your SAS datasets. However, with the LIBNAME statement’s ENGINE option, you can also create libraries to import and export Excel files. Because of this option, it becomes very convenient to save the output of a DATA step or a SAS procedure directly as an Excel file.
Syntax
You create a library to export data to Excel with the LIBNAME statement. The statement starts with the LIBNAME keyword, followed by the libref and the engine type, and finally, the location and Excel file name.
LIBNAME libref XLSX "path";
- libref: The libref is the name of the library. A libref is at most 8 characters long, starts with a letter or an underscore, and can only include letters, numbers, or underscores.
- engine: The engine provides SAS with instructions on how to treat the data. The default engine is BASE for SAS tables. However, SAS treats the data in the library as an Excel file with the XLSX engine.
- path: The location and the file name (including the file extension).
A normal library (without specifying the engine) contains one or more SAS datasets. However, if you use the XLSX engine, then a library is one Excel file where the “datasets” are the worksheets of the file.
Do you know? 10 FAQs about SAS Libraries
Example
With the LIBNAME statement below, we create the library my_xlsx that refers to the Excel file cars.xlsx.
libname my_xlsx xlsx '/folders/myfolders/export/cars.xlsx';
Note: You can only use the LIBNAME statement to export (and import) Excel files if you use SAS version 9.04.01M2 or higher. With PROC SETINIT or the global macro variable &sysvlong you can check your SAS version.
How to Use a LIBNAME Statement to Export Data to Excel
After you have created a library that refers to an Excel file, you can use this library directly to export data as a worksheet. For example, with the code below, we export the work.my_data dataset and create the worksheet all_cars in the cars.xlsx file.
data my_xlsx.all_cars; set work.my_data; run;
To create an Excel file with multiple sheets, you just need to submit another DATA step. (Don’t change the libref.)
For example:
data my_xlsx.only_ford_cars; set work.my_data (where=(Make = "Ford")); run;
Caution: When you use this method to export data to Excel, SAS replaces without warning existing data. While with PROC EXPORT, you need to explicitly specify to overwrite existing data with the REPLACE option.
Advantages
An advantage of this method is that it also works for SAS procedures like PROC SQL or PROC SORT.
For example, with the code below, we directly export the result of the SORT procedure to an Excel sheet.
proc sort data=work.my_data out=my_xlsx.all_cars_sorted; by EngineSize; run;
Disadvantages
A drawback of this method is that you can’t export column labels. It always exports the column headers. Nor can you create a worksheet without a header.
Did you know? How to use the LIBNAME statement to Import an Excel file
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
I have a love-hate relationship with spreadsheet data. I am interested in finding data to analyze, and if it arrives in the form of a spreadsheet, I’ll take it. And I like to deliver results and reports, but often my constituents ask for it as a spreadsheet that they can then manipulate further. <Sigh.>
A spreadsheet is not a database, so it can be a challenge to whip spreadsheet data into analysis-ready shape. Likewise, saving results as a spreadsheet can lose something in the translation — usually value formatting, appearance attributes, or graphs.
SAS offers many ways to read from and write to Microsoft Excel spreadsheets. They each have pros and cons. This post is an inventory of the methods that I know about for creating Excel files from within SAS.
If you want to cut to the chase and learn by watching, check this tutorial by SAS instructor Kathy Kiraly.
Some «bits» about 32-bit and 64-bit architecture
Before I get to the Big List, let me set the stage by describing a few terms and concepts.
In order to create Excel files directly from SAS, you need SAS/ACCESS to PC Files. This product enables all sorts of file exchanges between SAS and other PC-based applications, including Microsoft Excel, Microsoft Access, SPSS, and more.
SAS/ACCESS to PC Files includes a component called the PC Files Server. The PC Files Server is a service-based application that runs apart from SAS on a Windows node. It accepts requests from SAS to convert data to and from Excel (and other file types). Traditionally, this innovation allows SAS running on UNIX (where there are no native facilities for Excel data) to exchange data with PC-based data programs.
Recent changes in desktop computing have complicated the picture. Newer desktop machines all have 64-bit architecture, and most organizations are now adopting 64-bit versions of Microsoft Windows. All of your 32-bit applications (designed for x86 architecture) still can still run, of course, but there are a few hard-and-fast rules. One of those rules is that a 64-bit application cannot dynamically load 32-bit modules in its process space. And guess what? There is a better-than-even chance that the built-in data providers that you have for Microsoft Excel — the bits that allow SAS to write to Excel on Windows — are 32-bit modules. This means that the PROC EXPORT DBMS=EXCEL program that worked in your 32-bit SAS session will not work in your 64-bit SAS session.
There are two remedies for this bitness mismatch. First, you could install the 64-bit data providers (which accompany the 64-bit version of Microsoft Office). But you cannot have both the 32-bit and 64-bit versions of these data providers on the same machine; if you have 32-bit Microsoft Office, then you’re stuck with the 32-bit providers for now.
The second remedy is to use the PC Files Server, right there on the same Windows machine where SAS is running. This allows a 64-bit SAS process to delegate the data exchange to a 32-bit PC Files Server process. Thanks to the out-of-process communication, this circumvents the bit architecture mismatch. To make this work you don’t have to set up any additional software, but your SAS programs must change to use DBMS=EXCELCS. The EXCELCS keyword tells SAS to use the PC Files Server instead of attempting to use in-process data providers.
Exporting to Excel: ways to get there from SAS
With the architecture lesson behind us, here’s my list for how to put SAS content into Microsoft Excel. I won’t dive into much detail about each method here; you can follow the links to find more documentation.
These methods use features of SAS/ACCESS to PC Files:
LIBNAME EXCEL – reads/writes Excel files at the sheet level when the bitness of SAS (32- or 64-bit) matches the bitness of Microsoft Office installed (or more specifically, the ACE drivers that accompany Office). An Excel file is viewed as a SAS library, while sheets/ranges are the member tables. Requires exclusive lock on an existing Excel file.
LIBNAME PCFILES – does the same as LIBNAME EXCEL, but uses PC Files Server. Good for UNIX and for Windows configurations where bitness of SAS and Microsoft Office don’t match.
LIBNAME XLSX — reads and writes native XLSX files without the need for Microsoft components or the PC Files Server. This works the same way on all platforms: Windows and UNIX based. LIBNAME XLSX is available in SAS 9.4 and later.
PROC EXPORT DBMS=EXCELCS – uses PC Files Server to write an Excel file. There are various options to control the output behavior. Good for UNIX and for Windows configurations where bitness of SAS and Microsoft Office don’t match.
PROC EXPORT DBMS=EXCEL — writes Excel files when the bitness of SAS (32- or 64-bit) matches the bitness of Microsoft Office installed (or more specifically, the ACE drivers that accompany Office).
PROC EXPORT DBMS=XLS – writes Excel (XLS) files directly, no driver or PC Files Server needed. Has limits on volume and format. Works on Windows and UNIX.
PROC EXPORT DBMS=XLSX – new in 9.3M1, writes Excel 2010 files (XLSX format) directly. No driver or PC Files Server needed. Works on Windows and UNIX.
The following methods do not require SAS/ACCESS to PC Files, so they are popular, even if some don’t produce «native» Excel files:
ODS EXCEL — produces a native XLSX file, and can include graphics, formatting, and formulas with the use of special directives. This method is available in SAS 9.4 Maintenance 3 and later. See this post for tips about achieving some fancy effects with ODS EXCEL. This method should replace your use of ODS TAGSETS.EXCELXP if you’re still using that.
PROC EXPORT DBMS=CSV – produces comma separated value files, most often used in Excel.
ODS TAGSETS.CSV (or just DATA step and FILE output) – produces comma separated value files, most often used in Excel.
DATA step, using FILE and PUT to create delimited files — a simple approach that provides a little bit more control than TAGSETS.CSV or PROC EXPORT DBMS=CSV.
ODS TAGSETS.EXCELXP – uses ODS to create an Office XML file. Provides a fair amount of control over the content appearance, but recent versions of Excel do not recognize as a «native» format, so user is presented with a message to that effect when opening in Excel.
FILENAME DDE – uses Windows messages to control what goes into an Excel file, down to the cell level. Works only when SAS for Windows and Excel are on the same machine. Doesn’t work in SAS workspace servers or stored process servers (often accessed with SAS Enterprise Guide). It’s an antiquated approach, but offers tremendous control that many long-time SAS users enjoy — when it works. See why your DDE programs don’t work anymore.
SAS client applications make it easier
While I’ve focused on the SAS programming methods for creating Excel files, applications like SAS Enterprise Guide and the SAS Add-In for Microsoft Office make the operation a breeze. SAS Enterprise Guide can import and export Excel files through point-and-click methods, and SAS/ACCESS to PC Files is not needed to make that work. (However, the work is not captured in a SAS program, so it cannot be run in SAS batch jobs or stored processes.)
SAS Add-In for Microsoft Office turns the problem on its head. By allowing you to access SAS data and analytics from within Microsoft Excel, you pull the results into your Excel session, rather than export them from your SAS session.
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
Содержание
- Как экспортировать данные из SAS в Excel (с примерами)
- Пример 1: экспорт одного набора данных в один лист Excel
- Пример 2: экспорт нескольких наборов данных в несколько листов Excel
- Дополнительные ресурсы
- How to Export Data from SAS to Microsoft Excel
- Sample Data
- Export data from SAS to Excel with PROC EXPORT
- The EXPORT Procedure
- How to Overwrite Existing Files
- How to Define an Excel Sheet Name
- How to Export an Excel File with Multiple Sheets
- How to Export a Table to Excel with SAS Labels
- How to Export a Table to Excel without Header (Column Names)
- Export data from SAS to Excel with the LIBNAME Statement
- The LIBNAME Statement
- Blogs
- SAS export to Excel just got a little bit easier
- About Author
- 69 Comments
Как экспортировать данные из SAS в Excel (с примерами)
Вы можете использовать proc export для быстрого экспорта данных из SAS в файл Excel.
В этой процедуре используется следующий базовый синтаксис:
Вот что делает каждая строка:
- data : имя набора данных для экспорта
- outfile : Место для экспорта файла Excel
- dmbs : формат файла для экспорта
- replace : заменить файл, если он уже существует
- лист : имя для отображения на листе в книге Excel
В следующих примерах показано, как использовать эту функцию на практике.
Пример 1: экспорт одного набора данных в один лист Excel
Предположим, у нас есть следующий набор данных в SAS:
Мы можем использовать следующий код для экспорта этого набора данных в файл Excel с именем my_data.xlsx :
Затем я могу перейти к месту на своем компьютере, куда я экспортировал файл, и просмотреть его в Excel:
Данные в Excel соответствуют набору данных из SAS, а лист в книге Excel называется «Первые данные», как я указал в операторе экспорта proc .
Пример 2: экспорт нескольких наборов данных в несколько листов Excel
Предположим, у нас есть два набора данных в SAS:
Мы можем использовать следующий код для экспорта обоих наборов данных в один и тот же файл Excel на разных листах:
Затем я могу перейти к месту на своем компьютере, куда я экспортировал файл, и просмотреть его в Excel.
Первый лист под названием «Первые данные» содержит первый набор данных:
И второй лист под названием «Вторые данные» содержит второй набор данных:
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные задачи в SAS:
Источник
How to Export Data from SAS to Microsoft Excel
As a Data Analyst it is common to create a dataset in SAS and carry out further analysis in Microsoft Excel. But, how do you export data from SAS to Excel?
Exporting data from SAS to Microsoft Excel can be done with the EXPORT procedure and the LIBNAME statement. The EXPORT procedure provides flexibility when it comes to including column labels or header names. Whereas exporting data with a LIBNAME statement gives you more options for subsetting data and creating new columns.
In this article, we discuss both methods in more detail and answer common questions such as:
- How to define a sheet name?
- How to export column labels?
- How to create an Excel file without a header?
Sample Data
In this article, we use a sample dataset to export to Excel (work.my_data). This dataset is based on the CARS dataset from the SASHELP library, but with fewer columns.
Export data from SAS to Excel with PROC EXPORT
The EXPORT Procedure
An easy way to export a table from SAS to Excel is with the EXPORT procedure (PROC EXPORT). This procedure is easy-to-understand and provides many options.
Syntax of PROC EXPORT
To export data from SAS to Excel with PROC EXPORT you need to define at least three parameters:
- DATA=-option to specify the SAS dataset you want to export. For example, DATA=work.my_data.
- OUTFILE=-option to define the output location and the file name. For instance, OUTFILE=”/folders/myfolders/export/cars.xlsx”
- DBMS=-option to specify the file extension such as DBMS=xlsx.
DATA=-option
The DATA=-option specifies the SAS dataset you want to export. You can either use a one- or two-level SAS name (i.e., with or without libref). When you export a dataset to Excel, you can use dataset options such as KEEP, RENAME, and WHERE in the DATA=-option.
OUTFILE=-option
The OUTFILE=-option specifies the location and file name of the exported dataset. The file name includes the extension. Keep in mind that the complete path (location and file name) can’t exceed 201 characters.
DBMS=-option
The DBMS=-option specifies the type of file the EXPORT procedure creates (e.g., .xlsx or .xls). It depends on the file type how much data SAS can export. For example, if you export data to Excel, the SAS dataset cannot exceed the maximum of 1,048,576 rows and 16,384 columns.
Examples
The SAS code below exports the work.my_data dataset to Excel and creates a file called cars.xlsx.
Note 1: If you want to create an XLS-file with PROC EXPORT, you need to change the file extension in the OUTFILE=-option and use DBMS=xls.
Note 2: You need the SAS/ACCESS Interface to PC Files license to export data from SAS to Excel. To check if this license is available on your SAS installation, you can use the PROC SETINIT statement.
How to Overwrite Existing Files
By default, PROC EXPORT doesn’t overwrite existing files. If you try to do this, SAS will write an error to the log and will stop executing. To change this default behavior, you need the REPLACE option. If you use the REPLACE option, you can export and overwrite an existing file.
This is an example of how to use the REPLACE option.
How to Define an Excel Sheet Name
By default, PROC EXPORT creates an Excel file where the sheet name is equal to the filename. However, you can overwrite this default behavior and define the sheet name with the SHEET=-option. You need to write the sheet name between quotation marks, and it cannot exceed 31 characters.
In the example below, we create the Excel file cars.xlsx and call the sheet All Cars.
How to Export an Excel File with Multiple Sheets
Many Excel workbooks have multiple worksheets. Nevertheless, PROC EXPORT creates only one file with one sheet. So, how do you create an Excel file with multiple sheets using SAS?
You can create an Excel file with multiple sheets by submitting one PROC EXPORT statement for each sheet. In each PROC EXPORT statement, you change the DATA=-option and the SHEET=-option. But, the OUTFILE=-option and the DBMS=-option remain unchanged.
In the example below, we create an Excel file with two sheets, namely All Cars and Ford Cars. As you can see, we use dataset options, such as KEEP, RENAME, and WHERE in the DROP=-option.
How to Export a Table to Excel with SAS Labels
SAS datasets have column names and, optionally, column labels. Column labels can contain special characters such as blanks and percentage signs. For this reason, column labels are more elegant and are frequently used in reports. However, by default, PROC EXPORT exports the column names instead of the column labels. So, how do you export the column labels with PROC EXPORT?
You use the LABEL option to export a sheet with the column labels instead of the column names. You place this option after the REPLACE option. If a column doesn’t have a label, then PROC EXPORT exports the column name.
With the SAS code below, we export the column labels instead of the column names.
With a PROC CONTENTS statement, you can check whether a column has a label. For instance, some of the columns of our sample data work.my_data have labels.
Typically, you want your Excel file to have a header (i.e., column names). However, sometimes you need to create a file without one. So, how do you export data from SAS to Excel with a header?
You can prevent SAS from exporting the header to Excel by setting the PUTNAMES=-option to No. By default, this option is set to Yes. In contrast to other options, you write the word NO without quotation marks.
In the example below, we use PUTNAMES=NO to prevent SAS from adding column names to the Excel file.
Export data from SAS to Excel with the LIBNAME Statement
The LIBNAME Statement
A less known, but also very efficient way to export data from SAS to Excel is by creating a library with the LIBNAME statement.
Normally, you use the LIBNAME statement to create a library to store your SAS datasets. However, with the LIBNAME statement’s ENGINE option, you can also create libraries to import and export Excel files. Because of this option, it becomes very convenient to save the output of a DATA step or a SAS procedure directly as an Excel file.
Syntax
You create a library to export data to Excel with the LIBNAME statement. The statement starts with the LIBNAME keyword, followed by the libref and the engine type, and finally, the location and Excel file name.
- libref: The libref is the name of the library. A libref is at most 8 characters long, starts with a letter or an underscore, and can only include letters, numbers, or underscores.
- engine: The engine provides SAS with instructions on how to treat the data. The default engine is BASE for SAS tables. However, SAS treats the data in the library as an Excel file with the XLSX engine.
- path: The location and the file name (including the file extension).
A normal library (without specifying the engine) contains one or more SAS datasets. However, if you use the XLSX engine, then a library is one Excel file where the “datasets” are the worksheets of the file.
Источник
Blogs
SAS export to Excel just got a little bit easier
Note: as this is a popular topic, I’ve added a few notes with minor updates, including a link to a popular how-to tutorial video.
In case you missed it, the first maintenance release for SAS 9.3 was recently released. Because we’re all friends here, you may call it «SAS 9.3M1» for short.
Maintenance releases are usually about fixing problems that SAS has found or that customers have reported. However, sometimes a new capability might sneak out the door along with it. That’s what happened this time with improved XLSX support in PROC EXPORT.
Now for the first time, this round-trip import/export cycle works just as you would expect with no additional setup required:
Watch this tutorial (from SAS instructor Kathy Kiraly) to learn more about how to import and export XLSX files in SAS with just a few lines of code.
Kathy’s tutorial includes simple shortcuts, such as using the LIBNAME XLSX engine to read Excel files just like data sets.
Remember: using the IMPORT and EXPORT procedures to read and write Microsoft Excel files requires the SAS/ACCESS to PC Files module. With these latest changes, you can get the job done without setting up a PC Files Server, even on systems that don’t have a 32-bit Windows architecture.
Prior to this support, most customers who run SAS for 64-bit Windows or on a UNIX platform would need to use DBMS=EXCELCS for this operation. The EXCELCS method works by delegating the Excel read/write operation to another Windows node that has a PC Files Server instance. (On 64-bit Windows, you can make it work with very little configuration using the «autostart» capability.)
The PC Files Server is still very useful for other scenarios, such as supporting the PCFILES LIBNAME engine, which can read and write Microsoft Excel and Microsoft Access files, among others.
And if you’re looking for a point-and-click method for creating XLSX files in SAS Enterprise Guide, we cracked that nut a while ago. Just look for the Export as a Step task on your data view, or the «Share» tool in SAS Enterprise Guide 8.1.
+Chris Hemedinger is the Director of SAS User Engagement, which includes our SAS Communities and SAS User Groups. Since 1993, Chris has worked for SAS as an author, a software developer, an R&D manager and a consultant. Inexplicably, Chris is still coasting on the limited fame he earned as an author of SAS For Dummies.
Thanks! I have been struggling with this issue!
So, does this latest release fix the known issue with corruption of named ranges in xlsx/xlsm files under 9.2? From the track I had running a while ago, this was due to an issue with the MS Jet Engine which I am guessing has been fixed in 9.3M1.
I cannot say for certain whether this fixes the issue you saw. It’s true that this update allows you to create an XLSX file without invoking the Microsoft drivers (which seemed to be to blame for the issue you reported). But I’m not sure that you can use this method to accomplish your objective. especially if you are wanting to create a macro-enabled file (XLSM). That question might be work tracking again with SAS Technical Support.
Thank you Chris. I don’t have 9.3M1 yet — will need to wait until it is deployed at our site. In the meantime, I will stay with xls files for proc export, or a modified version of exportToXL (DDE maco suite) for xlsx or xlsm. Unfortunately exportToXL doesn’t work with hidden worksheets.
I’m facing some problem in creating EXCEL file under LINUX thru proc export.
Can you please suggest me the best way to create or export data to excel on LINUX platform itself?
If you have SAS 9.3 Maint 1, then you can use the XLSX method described in this post. For a more complete survey of all of the possibilities, check out «How do I export Excel files, let me count the ways».
Hi Chris,
I want to write xlsx file in unix server using unix sas code. My Unix Sas aricheture is ts1m1 64 bit and I am having 32 bit excel microsoft 2007. When I am using below code for exporting the xlsx file in unix server location.
Code used :
proc export data=
outfile=
dbms=xlsx
replace;
run;
xlsx file getting created in the unix location and after ftping to the local machine using ftp application. I am getting this error.
‘Excel found unreadable contents in ‘filename.xlsx’. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click yes
Could you please help me on this
When you FTP the file, are you certain that you are using BINARY mode as the transport? If not, the file could become corrupted in the transfer.
XLSX files are ZIP-formatted archives, so you could try to open in a tool such as 7Zip or WinZip to make sure the file is at least a valid archive.
Chris. What would my proc export statement look like if I have SAS V9.1.3 and want to export to Excel 2010 because that’s what I have on my PC?
Marc,
In SAS 9.1.3 there is not native support for writing to XLSX files. You can still use DBMS=EXCEL of course, but you will still have the limitations of the XLS format: 65K rows, etc.
As an alternative, you can use DBMS=CSV, ODS TAGSETS.EXCELXP, or ODS CSV output. I have a more complete list of methods available here.
Works great; fixes a workflow bind.
But how does one specify a particular sheet (if it’s not the first worksheet in the workbook)
Subci, you currently can’t specify a particular sheet to export to or to import from by using SAS Interface to PC Files. You’d need to download and install SAS 9.3 PC Files Server.
All you need to know is explained here: http://support.sas.com/kb/43/802.html
I have found the following allows me to create worksheets within the same workbook (using the code example in the original post):
proc export
data=sashelp.prdsale
dbms=xlsx
outfile=»c:tempprdsale.xlsx» ;
sheet = sheet1 ;
run;
proc export
data=sashelp.prdsale
dbms=xlsx
outfile=»c:tempprdsale.xlsx» ;
sheet = sheet2 ;
run;
I hope this helps someone, as it was a lifesave for my team! Thanks!
Jessica, thanks for sharing. I believe that the ability to add sheets to an existing workbook is a new feature in SAS 9.4.
Is there a list of options for this output type? I can’t find any documentation on it. The defaults works great, but I’d love to write to a specific worksheet, add autofilters, freeze the first column and/or row, etc. Thanks!
I think what you want is the features of the TAGSETS.TABLEEDITOR, which I didn’t mention in this post. That has the ability to create more control over the output columns like you’re asking for.
Sorry, Doesn’t work.
38 %LET filrf = «/sas/sasdata/sashome/41000769/bilstod/2012/&prognos/Utbet_exc.xlsx»;
170
171 proc export data=bet5_3
172 outfile=&filrf
173 dbms=xlsx replace;
ERROR: DBMS type XLSX not valid for export.
— SAS-programvara —
SAS Enterprise Guide-version: 4.3.0.10196
SAS System-version: none
SAS System-kommando: none
Shared SAS-files: D:AppsSASSharedFiles
JMP-installation:
— Actual process —
Actual catalog: d:appssasenterpriseguide4.3
Commandorow: d:appssasenterpriseguide4.3SEGuide.exe
Space for tempfiles: C:TEMP7SEG55896
Memory used: 202 633 216 bytes
Type of clientsession: Terminal services client
Runs in WOW64 (32-bit subsystem): Nej
— Operativsystem —
Namn: Windows 2003
Version: 5.2.131072.3790
Servicepack: Service Pack 2
.NET Runtime Version: 2.0.50727.3634 (SP 2)
Internet Explorer-version: 6.0.3790.3959
Systemkatalog: C:WINNTsystem32
Standardwebreader: Citrix Metaframe Server FTA
MDAC-version: 2.82.3959.0
In order for this to work, you need SAS 9.3 maint 1 (at least) and SAS/ACCESS to PC Files on the SAS server. It’s not clear from your log whether you have that; I suggest redirecting follow up questions to SAS Technical Support.
Is there any way to pass SAS formats to Excel when using PROC EXPORT DBMS=XLSX? I’m exporting a dataset with some PERCENT-formatted columns, but they just show up as raw numbers in Excel.
If you want to stick with DBMS=XLSX, you might try creating a character-formatted column with put(col,percent5.) — for example — and see if that carries over.
Otherwise, you can use ODS tagsets.EXCELXP or LIBNAME EXCEL (or LIBNAME PCFILES) to put your data to a spreadsheet and perhaps retain the formatting you want. See this blog post for an inventory of various methods.
Thanks so much for this helpful tip! I notice that dbms=xlsx seems to apply some sort of compression to the xlsx file, since when I open it up and immediately resave with a different name, the new file is larger. Do you know anything about this?
Andrew, I don’t know what would make the file larger, exactly. but here’s what I do know. The XLSX file format is a ZIP archive, compressed already. SAS writes to this file directly, so it creates a no-frills version of your SAS content for use in Excel. When you open and resave the file in Excel, perhaps Excel «enriches» the file with additional information, such as formatting instructions, so the resulting file is a bit larger.
That’s my made-up answer. It might be at least partially correct.
Thanks. I guess my particular problem is that when I try to pass SAS-created xlsx files as attachments through outlook to colleagues, they get quarantined for «bad compression», but if I open them, resave, and then attach to an email, they go through fine. could be something specific to my work environment.
Andrew, it could be that the XLSX file doesn’t «smell» like a true XLSX file to your e-mail filters, since it wasn’t created with the Microsoft tools. It might be interesting to examine the file versions, before and after the re-save operation. You could work with SAS Tech Support on this and if a change needs to be made to DBMS=XLSX processing, they can help get that in the system.
Chris, thanks for your help. I was not able to comprehensively follow up on the issue, but I believe that it was a problem with my work environment unrelated to SAS.
Hi Chris,
The above syntax is not working for Mainframes SAS, is there any specific solution to export the data in excel 2007 file (.xlsx) in SAS mainframes.
Thanks and Regards
Babu — I see that z/OS is not listed in the support matrix for PROC EXPORT and XLSX. You can still use ODS TAGSETS.EXCELXP, or straight-line CSV. If you need another option, please contact SAS Technical Support for some ideas.
We just installed 64-bit SAS 9.4 (TS1M0) under Windows 7. Using PROC IMPORT with DBMS=XLSX works, except that the RANGE statement seems to be ignored and always the first worksheet in the Excel file being imported. This makes it pretty useless when I want to import multiple worksheets from a single Excel file. So, I am sticking with using DBMS=EXCELCS with the 32-bit PC Files Server installed, which seems to work fine with a RANGE statement. Any chance of a fix so that the RANGE statement will work anytime soon?
The XLSX method received some updates in SAS 9.4 TS1M1. I believe the RANGE= works better, plus there is support updating/adding a sheet to an existing workbook.
I suggest confirming this for your scenario with SAS Technical Support, and then pursue the M1 update if you can.
With SAS 9.2 this simply does the trick as well
Interesting find! I think in this case, it’s the XLSX extension that is triggering the file format. If you specify the same code (EXCEL2000) and an XLS file extension, you’ll see the file format is different.
Thank you so much Chris your tip works perfectly
I get the following error message when trying to import data from excel. I am using SAS 9.4 and my desktop is running on windows 7 with 64 bit OS.
Proc import out=MHET112_A1
192 datafile= «C:Users. DocumentsMHET112_A.xlxs»
193 dbms=xlxs
194 replace;
ERROR: DBMS type XLXS not valid for import.
NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE IMPORT used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
195 getnames=yes;
196 run;
Are you sure that the file extension isn’t XLSX? The proper file extension for most Microsoft Excel files has the «S» before the final «X».
Hello, after the file import with XLSX I have very strange columns behaviour — length of the actual data is equal to the length of the column, for example I try to create new integer column from string and get the following note:
NOTE: Invalid numeric data, ‘22247. ‘ and new column is empty after that
I concatenated ‘. ‘ to all values and got the following result — ‘22247 . ‘ — can’t compress it either. Do you ever saw such a thing?
How are you importing this XLSX file? Using SAS Enterprise Guide and the Import Data task? Or are you using PROC IMPORT? If you can supply more details, I suggest that you post the question to communities.sas.com. The experts there can probably answer your question quickly.
It was PROC IMPORT. Will try to past it there, thanks
The code works good but. when I open the excel file a msg pops up that the file is corrupted and I couldn’t open it!!
If you want to follow up on this error, post in communities.sas.com with the details of the code you’re running, the version of SAS that you have installed, and the error message. Or, open a track with SAS Technical Support.
How do I change the column width? The width of each column looks either too narrow or too wide in Excel. How do I change it in the Proc Export statement? Thanks!
PROC EXPORT simply exports the data, and doesn’t tell Excel how to format the appearance at all.
There are two other mechanisms that provide a little bit more control. First, you could try ODS EXCEL, which has several appearance-related options. ODS EXCEL is new in SAS 9.4. Or, you could try the new LIBNAME XLSX engine — it doesn’t have formatting options but since it creates a native XLSX file, the output format might look a little bit better.
Thank you very much! Here is my code. The problem was the text in a couple of columns got truncated in the Excel 2010. But these columns look very nice in SAS 9.4 dataset. The columns weren’t truncated in SAS; but it’s trruncated after ods to excel. Please help!
ods excel file=»c:test.xlsx»
style=Pearl
options(sheet_interval=»proc» sheet_label=»none» sheet_name=»Test»);
proc print data=test noobs; run;
ods excel close;
You can use additional options to influence the column widths. For example:
ods excel file=»c:test.xlsx»
style=Pearl
options
(sheet_interval=»proc»
sheet_label=»none» sheet_name=»Test»
absolute_column_width=’20’);
I don’t think there is an «autofit» option.
I used your code and it works, but I have first few lines of comments in the excel before the data.
Is there a way to tell MIXED data in the file. That way it will only copy the data into dataset instead of comments as variable.
proc import
datafile=»c:tempprdsale.xlsx»
dbms=xlsx
out=work.prdsale
replace;
run;
Try the DATAROW= statement in PROC IMPORT, which tells the procedure where to begin reading.
Hi. I’m using this to export, and it works well except that if I export more than 1 spreadsheet to a workbook, the spreadsheets are all linked. If I don’t remember to unlink them, any changes in one affects all the others. Is there some way to stop this? (It happens both in a plain proc export and a ODS export to xlsx; it never happened when I was using xls.)
I wasn’t aware the sheets become linked. Can you share specifics about how you are creating these XLSX files? Perhaps post the details in SAS Support Communities — your fellow users will test and advise!
Kindly do me a favor.
How to IMPORT .xlsx file into SAS UNIX environment.
I tried
PROC IMPORT DATAFILE=»path/abc.xlsx» OUT=ABC DBMS=XLSX REPLACE;
RUN;
But I am getting ERROR: DBMS type XLSX not valid for import.
NOTE: In DBMS I also used DBMS=EXCEL or DBMS=EXCEL2000 but getting same error.
Kindly give your valuable inputs.
First, you need SAS/ACCESS to PC Files — can you verify you have that with proc product_status?
Next, DBMS=XLSX works with SAS 9.4 reliably, but not earlier. For that, you might need to use DBMS=XLS. But for XLSX files, you probably would need to set up a PC Files Server (again, this is only for releases earlier than SAS 9.4).
Enormous thanks, this code worked wonders for me. Thanks once again
But it doesn’t work for multiple sheet by macro. The new sheet will replace the old one. Is any solution for macro output to xlsx?
You don’t mention the SAS version you’re running. Replacing content at the sheet level is supported in SAS 9.4 — is that what you’re running?
Can someone help getting the following error wile exporting class dataset to local machine.
Insufficient authorization to access
/opt/sas/config/Lev1/SASApp_FIN_OPSPAY/\GBMLVFILFS04N02Home4$sahuaadProfileDesktopclass.xls.
Your SAS is running on UNIX (maybe Linux, and maybe SAS University Edition?). If running in SAS Enterprise Guide, you probably need to use this technique. If using SAS University Edition, you need to target the shared folder in your VM (path = ‘/folders/myfolders’). See this FAQ.
Can Someone Help Getting the following error while exporting report_daily dataset to local machine.
ERROR: Temporary file for XLSX file can not be created ->
/opt/sasinside/SASConfig/Lev1/SASApp/D:SASUniversityEditionmyfoldersDaily/MTD_AMDOCS.$$1. Make sure the path name is correct
and that you have write permission.
Using SAS University Edition, you must specify the proper path for your shared folder in the PROC EXPORT file out option, i.e., «/folders/myfolders/Daily/MTD_AMDOCS.xlsx».
I currently use SAS in a Linux environment. I have a 10k obs dataset that will be exported to an Excel spreadsheet (.xlsx file) using proc export.
Everytime I export, I need to manually format the output (column widths, column headers shading, etc.). Would there be a way to export to an excel file using a pre-existing excel template?
That would save me lots of time. Please, advise. Thanks!
You can automate those styles/widths by using ODS EXCEL and its many options. Here’s a good paper on the topic.
If you wanted to use a predefined template and you have SAS Add-In for Microsoft Office, you could design your workbook and then use SAS to pull the content into place.
proc sql;
create table WORK.Validations2 as
select distinct Lease_Type_Desc
from WORK.Validations1
group Lease_Type_Desc;
run;
proc export
data=VALIDATIONS2
dbms=EXCEL2000
outfile=»C:tempprdsale.xlsx»
replace;
run;
I got the output Data but file is not being created.
Why use EXCEL2000? Best advice is to use DBMS=XLSX these days for native Excel files.
Источник