英文:
how to download into stata several excel sheet each one represents a data set for specific year
问题
// 设置工作目录为包含Excel文件的文件夹
cd "C:\Users\noura\OneDrive\Desktop\project excel";
// 循环遍历每一年,将相应的Excel文件导入Stata
foreach file of varlist 2013/2022 {
import excel "`file'.xlsx", firstrow clear
gen year = "`file'"
append using "`file'.xlsx"
}
// 按年份对数据进行排序
sort year
英文:
am new to stata, this is my first time to use it
i have the data set for firms operate in kuwait market for 10 years, from 2013 to 2022, each year in a different excel files. so i have total 10 excel files, which i saved them in one folder, the folder bath "C:\Users\noura\OneDrive\Desktop\project excel"
excel files name:
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
so how i can import the 10 excel files into Stata and make sure that Stata are reading the data as continues years from 2013 to 2022.
what is the codes i should use?
i tried several code but nothing work
// Set the working directory to the folder where your Excel files are saved
cd "C:\Users\noura\OneDrive\Desktop\project excel"
// Loop over each year and import the corresponding Excel file into Stata
foreach file of varlist 2013/2022 {
import excel "`file'.xlsx", firstrow clear
gen year = "`file'"
append using "`file'.xlsx"
}
// Sort the data by year
sort year
答案1
得分: 1
您离解决方案非常接近。首次使用Stata时做得很好。
您的代码问题在于清除命令 clear
:
import excel "file.xlsx", firstrow clear
它清除了内存中的所有数据。因此,在每个循环中,您都在删除以前的所有年份数据。在我修改您示例代码中,我设置了一个 tempfile
用于在每个循环结束时保存数据,然后将年份数据追加到该数据集。
// 将工作目录设置为保存Excel文件的文件夹
cd "C:\Users\noura\OneDrive\Desktop\project excel"
clear
tempfile allyears
save `allyears', emptyok
// 循环处理每一年并将相应的Excel文件导入Stata
foreach file of varlist 2013/2022 {
import excel "`file'.xlsx", firstrow clear
gen year = "`file'"
append using `allyears'
save `allyears', replace
}
// 按年份对数据进行排序
sort year
希望这能帮助您解决问题。
英文:
You were very close to a solution. Well done for being your first time using Stata.
The problem in your code is that clear
in
import excel "`file'.xlsx", firstrow clear
clears all the data currently in memory. So in each loop you are deleting all previous years. In my modification of your example code I have set up a tempfile that you use to save the data to at the end of each loop. And then you append your year data to that data set.
// Set the working directory to the folder where your Excel files are saved
cd "C:\Users\noura\OneDrive\Desktop\project excel"
clear
tempfile allyears
save `allyears', emptyok
// Loop over each year and import the corresponding Excel file into Stata
foreach file of varlist 2013/2022 {
import excel "`file'.xlsx", firstrow clear
gen year = "`file'"
append using `allyears'
save `allyears', replace
}
// Sort the data by year
sort year
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论