ycphs / openxlsx

openxlsx - a fast way to read and write complex xslx files
https://ycphs.github.io/openxlsx/
Other
226 stars 75 forks source link

addStyle does not allow for rectangular inputs #492

Open thisCoolNerd opened 2 months ago

thisCoolNerd commented 2 months ago

Describe the bug addStyle accepts only one row across columns, one column across rows, or an equal number of columns and rows. It does not accept a combination (e.g., 15 rows across 4 columns).

To Reproduce df <- data.frame( Age = sample(18:65, 15), # Numeric column Gender = sample(c("Male", "Female"), 15, replace = TRUE), # String column Income = sample(20000:100000, 15), # Numeric column Occupation = sample(c("Teacher", "Engineer", "Doctor", "Artist", "Scientist"), 15, replace = TRUE), # String column Married = sample(c("Yes", "No"), 15, replace = TRUE), # String column Children = sample(0:5, 15, replace = TRUE), # Numeric column Owns_House = sample(c(TRUE, FALSE), 15, replace = TRUE), # Logical column Owns_Car = sample(c(TRUE, FALSE), 15, replace = TRUE) # Logical column )

sample_style <- createStyle(valign = "center", halign = "left")

Any empty Excel file can be uploaded here

xl_workbook <- loadWorkbook("excel_error_template.xlsx") writeData(xl_workbook, "contacts", df, startCol = 1, startRow = 1, rowNames = F, colnames = T)

This is where I get an error

addStyle(xl_workbook, "contacts", sample_style, rows = c(2:nrow(df)), cols = c(1:ncol(df)))

This is the error

Error in addStyle(xl.workbook, tab.name, text_align, rows = c(1:nrow(table.df)), : Length of rows and cols must be equal.

Expected behavior I expected that it would apply the style across the selection. Instead, I had to create a loop to hack it, but it's not efficient.

Example files excel_error_template.xlsx

JanMarvin commented 2 months ago

Hi @thisCoolNerd , try something like this in openxlsx2, it's unlikely to be fixed in openxlsx.

df <- data.frame(
  Age = sample(18:65, 15), # Numeric column
  Gender = sample(c("Male", "Female"), 15, replace = TRUE), # String column
  Income = sample(20000:100000, 15), # Numeric column
  Occupation = sample(c("Teacher", "Engineer", "Doctor", "Artist", "Scientist"), 15, replace = TRUE), # String column
  Married = sample(c("Yes", "No"), 15, replace = TRUE), # String column
  Children = sample(0:5, 15, replace = TRUE), # Numeric column
  Owns_House = sample(c(TRUE, FALSE), 15, replace = TRUE), # Logical column
  Owns_Car = sample(c(TRUE, FALSE), 15, replace = TRUE) # Logical column
)

library(openxlsx2)
wb <- wb_workbook()$
  add_worksheet("contacts")$
  add_data(x = df)$
  add_cell_style(vertical = "center", horizontal = "left", dims = wb_dims(x = df, select = "data"))

if (interactive()) wb$open()