You can achieve it using the following workflow:
# load environment
library(xlsx)
# define file path
file_path = '/home/user/Downloads/my_sheet.xlsx'
# load file as a workbook
file = loadWorkbook(file_path)
# check the sheets in the file
tbls = getSheets(file)
# remove the sheet you want to change
removeSheet(file, sheetName = "Sheet1")
# start a new from scratch
new_sheet = createSheet(file, sheetName = "Sheet1")
# create a dataframe
df = data.frame()
# link the dataframe to the new sheet
addDataFrame(df, new_sheet, row.names = FALSE)
# save the workbook/file
saveWorkbook(file, file_path)
Instead of creating a new dataframe from scratch, you can import an old sheet as a dataframe, with read.xlsx(file, sheetIndex, sheetName)
.
Attention: an error is thrown if you use short file paths, such as '~/Downloads/my_sheet.xlsx'
.