79171563

Date: 2024-11-08 21:11:12
Score: 0.5
Natty:
Report link

A more scalable workaround can be done that is similar to one suggested by @MKa which involved modifying the dataframe values in R as a formula:

library(openxlsx)
df <- data.frame(A = c('Dog', '5', '7.04'), B = c('Cat', '12', '1.23'))
wb <- createWorkbook()
addWorksheet(wb, "Sheet2")

# Modify df vals to formula class
df$A <- ifelse(!is.na(as.numeric(df$A)), 
           df$A,
           paste0("=\"", df$A, "\""))
class(df$A) <- "formula"
df$B <- ifelse(!is.na(as.numeric(df$B)), 
           df$B,
           paste0("=\"", df$B, "\""))
class(df$B) <- "formula"

writeDataTable(wb, "Sheet2", df)
saveWorkbook(wb, 'excel_file.xlsx', overwrite = T)

Main caveat is issues reading the same file using openxlsx:

Formulae written using writeFormula to a Workbook object will not get picked up by read.xlsx(). This is because only the formula is written and left to be evaluated when the file is opened in Excel. Opening, saving and closing the file with Excel will resolve this.

There are solutions to read the file still using other libraries but may not be ideal:

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @MKa
  • Low reputation (1):
Posted by: Richard Gallardo