Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[write_data] escape all formulas in write_data #834

Merged
merged 2 commits into from Oct 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions NEWS.md
@@ -1,7 +1,13 @@
# openxlsx2 (development version)

## New features

* Add new params to `wb_add_pivot_table()`. It is now possible to set the `show_data_as` value and set a tabular table design. [833](https://github.com/JanMarvin/openxlsx2/pull/833)

## Fixes

* Previously formulas written as data frames were not xml escaped. [834](https://github.com/JanMarvin/openxlsx2/pull/834)


***************************************************************************

Expand Down
11 changes: 10 additions & 1 deletion R/write.R
Expand Up @@ -227,6 +227,16 @@ write_data2 <- function(
# dc <- openxlsx2_type(data)
}

# since 1.2
is_fml <- dc == openxlsx2_celltype[["formula"]] | dc == openxlsx2_celltype[["array_formula"]] | dc == openxlsx2_celltype[["cm_formula"]] | dc == openxlsx2_celltype[["hyperlink"]]
if (any(is_fml)) {
fmls <- names(dc[is_fml])
data[fmls] <- lapply(
data[fmls],
function(val) xml_value(xml_node_create("fml", val, escapes = TRUE), "fml")
)
}

hconvert_date1904 <- grepl('date1904="1"|date1904="true"',
stri_join(unlist(wb$workbook), collapse = ""),
ignore.case = TRUE)
Expand Down Expand Up @@ -1034,7 +1044,6 @@ write_formula <- function(
assert_class(x, "character")
# remove xml encoding and reapply it afterwards. until v0.3 encoding was not enforced
x <- replaceXMLEntities(x)
x <- vapply(x, function(val) xml_value(xml_node_create("fml", val, escapes = TRUE), "fml"), NA_character_)
dfx <- data.frame("X" = x, stringsAsFactors = FALSE)

formula <- "formula"
Expand Down
22 changes: 22 additions & 0 deletions tests/testthat/test-formulas.R
Expand Up @@ -66,3 +66,25 @@ test_that("setting ref works", {
expect_equal(exp, got)

})

test_that("formual escaping works", {

df_tmp <- data.frame(
f = paste0("'A&B'!A1")
)
class(df_tmp$f) <- c(class(df_tmp$f), "formula")

wb <- wb_workbook()$
add_worksheet("A&B")$
add_worksheet("Fml")$
add_data(x = df_tmp, col_names = FALSE)$
add_formula(dims = "A2", x = "'A&B'!A1")$
add_formula(dims = "A3", x = "SUM('A&B'!A1)", array = TRUE)

expect_warning(wb$add_formula(dims = "A4", x = "SUM('A&B'!A1)", cm = TRUE))

exp <- c("'A&amp;B'!A1", "'A&amp;B'!A1", "SUM('A&amp;B'!A1)", "SUM('A&amp;B'!A1)")
got <- wb$worksheets[[2]]$sheet_data$cc$f
expect_equal(exp, got)

})