1

Lets say I have two excel workbooks (e.g. A.xlsx and B.xlsx) that each contain multiple worksheets (e.g. "a1" and "a2" in A.xlsx; "b1", "b2", and "b3" in B.xlsx). Note that these worksheets all have their own conditional formatting, filtering, zoom, and other viewing options.

Given this setup, is it possible to generate a combined workbook via. R (e.g. C.xlsx) featuring the 5 worksheets from A.xlsx and B.xlsx (e.g. "a1", "a2", "b1", "b2", and "b3" in C.xlsx) that furthermore retains all of the original conditional formatting, filtering, zoom, and other viewing options? Thank you for your help!

user3624032
  • 59
  • 1
  • 5

1 Answers1

1

We could read both the datasets together in map2. Get the sheet names from 'A.xlsx' and 'B.xlsx' data. Create a named vector of filepath with sheet names, loop over the vector with imap, read the sheets with read_excel, bind those together after creating a column for identification of sheetname, and combine the list output from imap to a single list with imap

library(purrr)
library(dplyr)
library(readxl)
library(openxlsx)

# // replace the path/to/your - actual path
fileA <- 'path/to/your/A.xlsx'
fileB <- 'path/to/your/B.xlsx'
nmA <- excel_sheets(path = fileA)
nmB <- excel_sheets(path = fileB)
nm1A <- setNames(rep(fileA, length(nmA)), nmA)
nm1B <- setNames(rep(fileB, length(nmB)), nmB)
lstC <- imap(c(nm1A, nm1B), ~ 
              read_excel(.x, sheet = .y) %>%
                  mutate(sheetname = .y))
names(lstC) <- c(nmA, nmB)
write.xlsx(lstC, '/path/to/your/C.xlsx')
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you for the solution. A couple of issues though, when I run the map2_dfr line of code, it results in the following error "Error: Mapped vectors must have consistent lengths:". I deleted one of the sheets in B.xlsx (b3 to be exact), but it then results in a different error (Error: Sheet 'b1' not found). Many thanks! – user3624032 May 19 '21 at 23:40
  • Can you show the output of `nmA` and `nmB`? I assume that both have the same number of elements – akrun May 19 '21 at 23:42
  • @user3624032 sorry, i wa thinking that it is same length – akrun May 19 '21 at 23:43
  • nma results in: "a1" "a2"; while nmB results in: "b1" "b2". When I had 3 sheets in B.xlsx, nmB results in "b1" "b2" "b3". – user3624032 May 19 '21 at 23:43
  • Thank you for helping - it shows the following error now: "Error in as_mapper(.f, ...) : argument ".f" is missing, with no default" – user3624032 May 19 '21 at 23:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232615/discussion-between-user3624032-and-akrun). – user3624032 May 19 '21 at 23:50
  • @user3624032 can you try now – akrun May 19 '21 at 23:52