Skip to content

Commit

Permalink
adds functions for reading excel sheets and writing them as csv into …
Browse files Browse the repository at this point in the history
…a destination folder
  • Loading branch information
vh-d committed Feb 1, 2019
1 parent 6f15849 commit 175b69f
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 0 deletions.
71 changes: 71 additions & 0 deletions R/excel.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#' Reads all sheets from an excel xlsx file into a list
#'
#' @param file file name
#' @param ... args passed to openxlsx::readWorkbook
#'
#' @return a list of data.frames
#' @export
excel_worksheets <- function(file, ...) {

if (!requireNamespace("openxlsx")) stop("openxlsx package required!")

wb <- openxlsx::loadWorkbook(file)
sh_names <- openxlsx::sheets(wb)

sheets <-
lapply(
X = sh_names,
FUN = openxlsx::readWorkbook,
# arguments passed to readWorkbook
xlsxFile = wb,
...
)
names(sheets) <- sh_names

return(sheets)
}


#' Reads all sheets from an excel xlsx file into a list
#'
#' @param file file name
#'
#' @export
excel_worksheets_readxl <- function(file) {

if (!requireNamespace("readxl")) stop("readxl package required!")
sh_names <- readxl::excel_sheets(path = file)

sheets <- lapply(sh_names, readxl::read_xlsx, path = file, col_types = "text")
names(sheets) <- sh_names

return(sheets)
}


#' Writes list of data.frames as csv files into a folder
#'
#' @param sheets a list of data.frames
#' @param path path to a destination dir
#' @param ... args passed to fwrite
#' @export
worksheets_to_csvs <- function(sheets, path, ...) {
if (!requireNamespace("data.table")) stop("data.table package required!")
stopifnot(is.list(sheets))

sh_names <- names(sheets)
if (is.null(sh_names)) sh_names <- seq_along(sheets)

invisible(
sapply(sh_names,
function(s) {
if (!is.null(sheets[[s]])) {
data.table::fwrite(
x = sheets[[s]],
file = file.path(path, paste0(s, ".csv")),
...)
}
})
)

}
19 changes: 19 additions & 0 deletions man/excel_worksheets.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions man/excel_worksheets_readxl.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions man/worksheets_to_csvs.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 175b69f

Please sign in to comment.