Via openxlsx
I'm populating an Excel-file, with both data and formulas. For some cells formatting is required, for example on percentages, which can be done by either assigning percentage
to the class or by applying a style. However, this does not work for formulas. Below is an example with 4 entries: the first two are data and are correctly displayed as percentages. Entries 3 and 4 are formulas, with entry 3 using class
to set formatting, while entry 4 uses addStyle
# Create workbook
wb <- createWorkbook()
# Add new orksheet
addWorksheet(wb, sheetName = "Test")
x <- 0.05
class(x) <- c(class(x), "percentage")
writeData(wb, sheet = "Test", x = x, startRow = 1, startCol = 1, rowNames = FALSE, colNames = FALSE)
x <- 0.07
class(x) <- c(class(x), "percentage")
writeData(wb, sheet = "Test", x = x, startRow = 2, startCol = 1, rowNames = FALSE, colNames = FALSE)
x <- "A1+A2"
class(x) <- c(class(x), "percentage")
writeFormula(wb, sheet = "Test", x = x, startRow = 3, startCol = 1)
x <- "A1+A2"
writeFormula(wb, sheet = "Test", x = x, startRow = 4, startCol = 1)
number_format <- createStyle(numFmt = openxlsx_getOp("numFmt", "PERCENTAGE"))
addStyle(wb, sheet = sheet, number_format,
rows = 4:4, cols = 1:1, gridExpand = FALSE)
# Store the Excel-file
saveWorkbook(wb, "test_model1.xlsx", overwrite = TRUE)
The resulting WB:
This is likely due to the formula being written as character. After pressing enter
, the correct formatting does appear. This was also the case at Display as percentages using openxlsx::addStyle without having to click on cell in Excel , but there no solution is provided.
Turns out the problem was in creating the style:
number_format <- createStyle(numFmt = openxlsx_getOp("numFmt", "PERCENTAGE"))
Should be
number_format <- createStyle(numFmt = "percentage")
Also in some cases it helped to first apply the style, and then fill in the data/formula.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.