Sometimes, we would like to work with data that are stored in another file format such as Microsoft Excel. It is easy to import data from Excel using Stata's import excel command. It is also easy to export data from Stata to Excel using the export excel command.
Let's begin by opening a Stata system dataset named auto.
. sysuse auto (1978 automobile data)
Next, let's use Stata's export excel command to export our auto dataset to an Excel file named myauto.
. export excel myauto, sheet(auto) firstrow(variables) file myauto.xlsx saved
Note that I included two options after the comma: sheet() and firstrow(). The sheet(auto) option saves the data to a sheet named "auto" in the Excel file. And the firstrow(variables) option saves the variable names to the first row of the Excel file. You can verify that the Excel file was exported successfully by typing ls, and you should see a file named "myauto.xlsx".
. ls 7.6k 2/08/24 15:42 myauto.xlsx
Now we can import our Excel data back into Stata. Let's first type clear to clear Stata's memory.
. clear
Then we use import excel to import the data from the Excel file.
. import excel myauto, sheet(auto) firstrow (12 vars, 74 obs)
The sheet(auto) option looks the same as it did in our export excel command. Here we simply type firstrow to import the variable names from the first row of the Excel file.
Let's type describe to verify that our data imported successfully.
. describe Contains data Observations: 74 Variables: 12
Variable Storage Display Value |
name type format label Variable label |
make str17 %17s make price int %10.0gc price mpg byte %10.0g mpg rep78 byte %10.0g rep78 headroom double %10.0g headroom trunk byte %10.0g trunk weight int %10.0gc weight length int %10.0g length turn byte %10.0g turn displacement int %10.0g displacement gear_ratio double %14.2f gear_ratio foreign str8 %9s foreign |
Finally, we save the data we just imported in Stata's .dta format.
. save myauto file myauto.dta saved
You can watch a demonstration of these commands by clicking on the link to the YouTube video below. You can read more about these commands by clicking on the links to the Stata manual entries below.
Read more in the Stata Data Management Reference Manual; see [D] clear, [D] describe, [D] dir and ls, [D] import excel, [D] sysuse, and [D] save.