How to modifying a data table with openxlsx2? #1092
-
The data The goal Current solution library(openxlsx2)
# Load the workbook
wb <- wb_load("data_table_test.xlsx")
# Get the data tables info
data_tables_info <- wb_get_tables(wb, sheet = "S1")
# Get the data table position
data_table_pos <- data_tables_info$tab_ref[data_tables_info$tab_name == "data_table"]
# Read the data table
data_table <- wb_to_df(wb, sheet = "S1", dims = data_table_pos)
# modify the data table
data_table$COL_1 <- as.integer(data_table$COL_1) + 1000
# remove the data table from the worksheet
wb <- wb_remove_tables(wb, sheet = "S1", table = "data_table")
# write the data back to the data table
wb <- wb_add_data_table(wb, x = data_table, dims = data_table_pos, sheet = "S1", table_name = "data_table")
# Save the workbook
wb_save(wb, "data_table_test_out.xlsx") Question |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi @maximecharriere , you could try something like the code below, but be aware, with tables updates are always a bit risky, because there might be filters and slicers attached to a table and they are not updated (I believe there is a warning with library(openxlsx2)
# prepare example data
df <- data.frame(
COL_1 = 1:4,
COL_2 = c("foo", "boo", "foo", "boo"),
COL_3 = letters[1:4]
)
# prepare example workbook
wb <- wb_workbook()$
add_worksheet("S1")$
add_data_table(x = df, dims = "C5", table_name = "data_table")$
add_font(bold = TRUE, dims = "D7")$
add_font(color = wb_color("red"), dims = "E8")$
add_fill(color = wb_color("darkgreen"), dims = "E8")
# get table position
data_tables_info <- wb_get_tables(wb, sheet = "S1")
data_table_pos <- data_tables_info$tab_ref[data_tables_info$tab_name == "data_table"]
# Read the data table
data_table <- wb_to_df(wb, sheet = "S1", dims = data_table_pos)
# modify the data table
data_table$COL_1 <- as.integer(data_table$COL_1) + 1000
# get position to update
first_table_cell <- dims_to_dataframe(data_table_pos, fill = TRUE)[1, 1]
col1_pos <- wb_dims(x = data_table, from_dims = first_table_cell, cols = "COL_1")
# write updated data
wb$add_data(x = data_table$COL_1, col_names = FALSE, dims = col1_pos)
if (interactive()) wb$open() |
Beta Was this translation helpful? Give feedback.
Hi @maximecharriere , you could try something like the code below, but be aware, with tables updates are always a bit risky, because there might be filters and slicers attached to a table and they are not updated (I believe there is a warning with
wb_update_table()
regarding this). So if the table is sorted, the sorting will not automatically update. And elements that are not selected are simply hidden in xml, this is also not updated. Therefore with filters there might be additional issues.