2

I am trying to use openxlsx::write.xlsx to write results into Excel spreadsheet in R.

  1. if the file exists and a new sheet is to be added, I can use append=T. Instead of using if to check the file, are there any ways to automatically check?

  2. if the file and sheet both exist and this sheet is to be updated, how should I do to overwrite the results? Thanks.

IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
Harry
  • 331
  • 1
  • 4
  • 14
  • This could be useful:https://stackoverflow.com/questions/28053185/using-write-xlsx-to-replace-an-existing-sheet-with-r-package-xlsx. – sm925 Jan 03 '20 at 21:49
  • `write.xlsx` from what package? That function isn't in base R – IceCreamToucan Jan 03 '20 at 21:53
  • @samadhi Thanks. In the current code, openxlsx package is used. To use xlsx, I need to detach, and then attached again. I am curious the difference between the two packages? – Harry Jan 03 '20 at 22:15
  • @IceCreamToucan it's from openxlsx. – Harry Jan 03 '20 at 22:16

2 Answers2

3

Here is an openxlsx answer. In order to demonstrate, we need some data.

## Create a simple test file 
library(openxlsx)
hs <- createStyle(textDecoration = "Bold")
l <- list("IRIS" = iris, "MTCARS" = mtcars)
write.xlsx(l, file = "TestFile.xlsx", borders = "columns", headerStyle = hs)

Question 1

You can check whether or not the file exists with

## Check existence of file
file.exists("TestFile.xlsx")

You can check if the tab (sheet) exists within the workbook

## Check available sheets
getSheetNames("TestFile.xlsx")

Steps for question 2:
1. Read the file into a Workbook object.
2. Pull the data from the sheet you want to modify into a data.frame.
3. Modify the data.frame to taste
4. Save the data back into the Workbook
5. Save the Workbook out to disk
In order to have a simple example to work with, let's create a simple test file.

## Load existing file
wb = loadWorkbook("TestFile.xlsx")

## Pull all data from sheet 1
Data = read.xlsx(wb, sheet=1)

## Change a single element for demonstration
## ** Beware!! **    Because of the header,
##   the 2,2 position in the data 
##   is row 3 column 2 in the spreadsheet
Data[2,2] = 1492

## Put the data back into the workbook
writeData(wb, sheet=1, Data)

## Save to disk
saveWorkbook(wb, "TestFile.xlsx", overwrite = TRUE)

You can open up the spreadsheet and check that the change has been made.

If you want to completely change the sheet (as in your comment), you can just delete the old sheet and replace it with a new one using the same name.

removeWorksheet(wb, "IRIS")
addWorksheet(wb, "IRIS")
NewData = data.frame(X1=1:4, X2= LETTERS[1:4], X3=9:6)
writeData(wb, "IRIS", NewData)
saveWorkbook(wb, "TestFile.xlsx", overwrite = TRUE)
G5W
  • 36,531
  • 10
  • 47
  • 80
  • Thanks for the answer! It does work! I realize there are two more questions, 1) how to check if a spreadsheet exist using openxlsx package; 2) this method can only update new data, remaining old one. Say Data_old is a 10*10 matrix and Data_new is 4*4 matrix. So is it possible to erase the spreadsheet and then write new data. – Harry Jan 04 '20 at 00:54
2

You can check if sheet exists before and if so remove it, if not append it to existing file this command also will create file if it does not exist.

library(xlsx)

path <- "testing.xlsx"
sheet_name = "new_sheet"

data <-
  data.frame(
    B = c(1, 2, 3, 4)
  )

if(sheet_name %in% names(getSheets(loadWorkbook(path)))){
  wb <- loadWorkbook(path)
  removeSheet(wb, sheetName = sheet_name)
  saveWorkbook(wb, path)
}

write.xlsx(data, path, sheetName = sheet_name, append = TRUE)
Nareman Darwish
  • 1,251
  • 7
  • 14
  • Thanks Nareman. In the current code, openxlsx package is used. Are there any reasons to choose one over the other? I get the code from somewhere else. – Harry Jan 03 '20 at 22:13
  • 1
    I honestly do not know which one is better. Maybe this could be a call to ask such questions to others in the community. – Nareman Darwish Jan 03 '20 at 22:16
  • 3
    @NaremanDarwish the xlsx package requires Java v 1.6 or greater to be installed on your system, whereas openxlsx doesn't. – Allan Cameron Jan 03 '20 at 23:53