Search code examples
excelrformulaxlsxlsx

Pass a formula to an xls file using R's xlsx package


Here is the code I used.

library(xlsx)
wb <- loadWorkbook('D:/test.xls') 
sheets <- getSheets(wb) 
sheet <- sheets[['my_sheet']]

addDataFrame(x = ds, sheet = sheet, row.names = FALSE, col.names = FALSE, startRow=3, startColumn=1) 

cell.1 <- createCell(rows[1], colIndex=34)[[1,1]]
setCellValue(cell.1, "=A32*B33")
saveWorkbook(wb, 'D:/test.xls')

Adding a dataframe worked without a problem. But when opening the xls file, I saw the text "=A32*B33" in cell A34 (an extra ENTER needs to be pressed in order for the formula to work). Can you help me enter a formula correctly?


Solution

  • I have used package xlsx in the past, and despite great promise, found it severely lacking in functionality and ease of use. When I searched the package manual a minute ago, it doesn't seem possible to do what you want to do.

    The good news is there is an alternative in the form of package XLConnect. XLConnect uses the same Java code (from the Apache POI project) as xlsx, so you still have the same high level of interoperability between operating systems.

    XLConnect has a function that does what you need: setCellFormula().

    References:


    PS. Can you tell I like this package?