Stata: Append Data to Existing Excel Sheet
This guide demonstrates how to append data from a Stata matrix to an existing Excel sheet without overwriting existing content. The putexcel command offers an append option for this purpose.
Original Stata Code:
matrix result = J(2, 5, 0)
* 创建一个空的结果矩阵
local row = 1
local col = 1
forvalues year=2017/2021{
dis `year'
count if 注册成立年份==`year'
local count = r(N)
* 将结果存储到结果矩阵中
matrix result[1, `col'] = `year'
matrix result[2, `col'] = `count'
local col = `col' + 1
}
* 导出结果矩阵到Excel表格
putexcel set "/Users/Chen/Downloads/项目:产业根值性\结果2.xlsx", sheet("Sheet1") replace
* 写入结果矩阵到Excel表格
putexcel A1=matrix(result)
* 关闭Excel文件
putexcel close
Modified Stata Code:
matrix result = J(2, 5, 0)
* 创建一个空的结果矩阵
local row = 1
local col = 1
forvalues year=2017/2021{
dis `year'
count if 注册成立年份==`year'
local count = r(N)
* 将结果存储到结果矩阵中
matrix result[1, `col'] = `year'
matrix result[2, `col'] = `count'
local col = `col' + 1
}
* 导出结果矩阵到Excel表格
putexcel set "/Users/Chen/Downloads/项目:产业根值性\结果2.xlsx", sheet("Sheet1") replace
* 写入结果矩阵到Excel表格
putexcel A1=matrix(result), sheet("Sheet1") append
* 关闭Excel文件
putexcel close
Explanation of Changes:
The crucial modification is the addition of the append option in the putexcel command. By including append, you instruct Stata to add the data from the result matrix to the existing Sheet1 in the Excel file. This ensures that the new data is appended without overwriting the existing content.
Key Considerations:
- Data Structure: Ensure your data in the
resultmatrix is compatible with the format of the existing Excel file (e.g., numbers, dates, etc.). - Cell Location: The
A1inputexcel A1=matrix(result)specifies the starting cell for the matrix data. Adjust this to match your desired placement within the sheet. - Error Handling: It's good practice to include error handling in your code to manage potential issues during the Excel export process.
By implementing these changes, you can seamlessly append data from your Stata matrix to an existing Excel file, preserving the original data while efficiently adding new information.
原文地址: https://www.cveoy.top/t/topic/fUYl 著作权归作者所有。请勿转载和采集!