Skip to content

Commit

Permalink
Merge pull request #494 from jistria/reset-col-widths-after-save
Browse files Browse the repository at this point in the history
Fix resaving workbook after resetting col widths
  • Loading branch information
JanMarvin authored Aug 29, 2024
2 parents 2bf325a + ae3d9f8 commit 4780b16
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

* Fixed warning on `dataValidation(..., type = "list")` ([#342](https://github.com/ycphs/openxlsx/issues/342))
* Added optional argument to `loadWorkbook` to decide if empty/blank cells should be converted to NA_character_ (the default) or left blank as is
* `saveWorkbook()` now succeeds when called after the user has set column widths for a range of columns (e.g. 1:2), saved the workbook, then set column widths for a new range that is inclusive of the previous one (e.g. 1:5) ([#493](https://github.com/ycphs/openxlsx/issues/493)).

## Improvements

Expand Down
5 changes: 4 additions & 1 deletion R/workbook_column_widths.R
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,10 @@ Workbook$methods(setColWidths = function(sheet) {
}
}

cols <- cols[!cols %in% names(worksheets[[sheet]]$cols)]
remaining_cols <- !cols %in% names(worksheets[[sheet]]$cols)
cols <- cols[remaining_cols]
widths <- widths[remaining_cols]
hidden <- hidden[remaining_cols]
}

# Add remaining columns
Expand Down
33 changes: 33 additions & 0 deletions tests/testthat/test-setColWidths.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

context("Setting column widths")

test_that("Resetting col widths", {
# Write some data to a workbook object.
wb <- createWorkbook()
addWorksheet(wb, "iris")
writeData(wb, "iris", iris)

# Set column widths and perform the pre-save operation to prepare col xml
# (typically called by `saveWorkbook()`).
setColWidths(wb, "iris", cols = 1:2, 12)
wb$setColWidths(1)

# Set column widths again for a different range inclusive of the previous one,
# perform the pre-save operation to prepare col xml, and test for an error
# (reported in https://github.com/ycphs/openxlsx/issues/493).
setColWidths(wb, "iris", cols = 1:5, 15)
expect_error(wb$setColWidths(1), NA)

# Test that the resulting col xml meets expectations.
expected_col_xml <- c(
"1" = "<col min=\"1\" max=\"1\" width=\"15.71\" hidden=\"0\" customWidth=\"1\"/>",
"2" = "<col min=\"2\" max=\"2\" width=\"15.71\" hidden=\"0\" customWidth=\"1\"/>",
"3" = "<col min=\"3\" max=\"3\" width=\"15.71\" hidden=\"0\" customWidth=\"1\"/>",
"4" = "<col min=\"4\" max=\"4\" width=\"15.71\" hidden=\"0\" customWidth=\"1\"/>",
"5" = "<col min=\"5\" max=\"5\" width=\"15.71\" hidden=\"0\" customWidth=\"1\"/>"
)
expect_equal(
wb$worksheets[[1]]$cols,
expected_col_xml
)
})

0 comments on commit 4780b16

Please sign in to comment.