Public-Health-Scotland / SBSS

Reproducible Analytical Pipeline of the Scottish Bowel Screening Programme Statistics (SBSS) publication
1 stars 0 forks source link

Use of `write_data()` with openxlsx2 #55

Open olivroy opened 1 year ago

olivroy commented 1 year ago

Hi, this is just a little note to mention that using write_data() is not the approach used with openxlsx2. the write_*() functions may stop being exported in openxlsx2 at some point. (possibly a year from now)

Instead, we recommend using wb$add_data() or wb_add_data().

See https://janmarvin.github.io/openxlsx2/reference/wb_add_data.html.

In your example

# old
write_data(template, "data", KPI_data, startRow = 11, startCol = 16, 
           colNames = FALSE, na.strings = "")
# recommended
# if the data sheet already exists
template$add_data(sheet = "data", x = KPI_data, dims = wb_dims(11, 16), col_names = FALSE, na.strings = "")
wb_save("template", file = "path/to/template.xlsx")

In general

library(openxlsx2)
wb <- wb_workbook()

wb$add_worksheet("new sheet")
wb$add_data(x = mtcars)
wb$add_worksheet("new sheet1")
wb$add_data(x = iris)
# alternatively
wb <- wb %>% wb_add_worksheet("new sheet2") %>% wb_add_data(x = iris)

wb$save("path/to/file.xlsx")