awalker89 / openxlsx

R package for .xlsx file reading and writing.
Other
363 stars 79 forks source link

writeDataTable doesn't handle NULL data.frames or data.tables #549

Open ScThSz opened 1 year ago

ScThSz commented 1 year ago

Hello,

I've come across an issue in using openxlsx::writeDataTable with null data.frames and data.tables. I'm wondering if I'm missing something there but the documentation doesn't seem to mention anything.

Expected Behavior

I have a set of data.tables/data.frames that I want to write to an Excel file, some of them can be empty. If the dt/df is empty I would expect the excel tab to be named according to the "sheet" argument and that the content is empty.

Actual Behavior

Currently this seems to raise an Index out of bounds error coming from: https://github.com/ycphs/openxlsx/blob/master/R/workbook_write_data.R#L37 as "nCols" will be 0 and 1:nCols will result in an integer vector of length 2 (1, 0). Maybe seq_len or something could fix that problem?

Steps to Reproduce the Problem

` library(openxlsx) library(data.table)

wb <- openxlsx::createWorkbook() openxlsx::addWorksheet(wb, sheetName = "test") openxlsx::writeDataTable(wb, sheet = "test", x = data.table::data.table()) openxlsx::writeDataTable(wb, sheet = "test", x = data.frame()) # doesn't seem to work with base dataframes either `

sessionInfo()

R version 4.1.2 (2021-11-01) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Debian GNU/Linux 10 (buster)

Matrix products: default BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3 LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.3.5.so

locale: [1] LC_CTYPE=de_DE.UTF-8 LC_NUMERIC=C LC_TIME=de_DE.UTF-8 LC_COLLATE=de_DE.UTF-8
[5] LC_MONETARY=de_DE.UTF-8 LC_MESSAGES=de_DE.UTF-8 LC_PAPER=de_DE.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C

attached base packages: [1] stats graphics grDevices utils datasets methods base

other attached packages: [1] data.table_1.14.2 openxlsx_4.2.4 devtools_2.4.2 usethis_2.1.3

loaded via a namespace (and not attached): [1] Rcpp_1.0.7 rstudioapi_0.13 magrittr_2.0.1 pkgload_1.2.3 R6_2.5.1 rlang_1.0.2
[7] fastmap_1.1.0 tools_4.1.2 pkgbuild_1.2.0 sessioninfo_1.2.1 cli_3.3.0 withr_2.5.0
[13] ellipsis_0.3.2 remotes_2.4.1 rprojroot_2.0.2 lifecycle_1.0.1 crayon_1.4.2 brio_1.1.2
[19] zip_2.2.0 processx_3.5.2 purrr_0.3.4 callr_3.7.0 fs_1.5.0 ps_1.6.0
[25] testthat_3.1.4 memoise_2.0.0 glue_1.6.2 cachem_1.0.6 stringi_1.7.6 compiler_4.1.2
[31] desc_1.4.0 prettyunits_1.1.1