Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openxlsx multiple validations corrupts output file

Tags:

r

I'm trying to add multiple validations and add formulas to an excel file. Here is the code I use:

library(openxlsx)
fileTemplate <- 'New01.xlsx'
wbTemplate <- loadWorkbook(fileTemplate)
addWorksheet(wbTemplate, "Sheet1")
writeData(wbTemplate, "Sheet1", dataset)
len <- NROW(dataset)
dataValidation(wbTemplate, 2, col = 2, rows = 2:len, type = "list", value = "'Data Validation'!$A$2:$A$19")
dataValidation(wbTemplate, 2, col = 3, rows = 2:len, type = "list", value = "'Data Validation'!$B$2:$B$501")
dataValidation(wbTemplate, 2, col = 5, rows = 2:len, type = "list", value = "'Data Validation'!$C$2:$C$6")
openXL(wbTemplate)

if I just use one dataValidation it opens okey, if more than one it complains about the file being corrupt...

like image 463
user1298416 Avatar asked Oct 29 '22 18:10

user1298416


1 Answers

Unfortunately, this looks like a bug found in data validation type 'list' fails when there are more than one on a sheet #266.

Fortunately, there's a pull request that attempts to fix this issue. Using devtools::dev_mode(), you can install the tkunstek/openxlsx version without having to remove and reinstall the CRAN version of openxlsx.

# install the devtools package
install.packages( pkgs = "devtools" )

# load necessary packages
library( devtools )

# create a new library for storing installed packages.
dev_mode(on = TRUE )

# download the PR request that fixes
# the dataValidation error
install_github( repo = "tkunstek/openxlsx" )

# load the library
library( openxlsx )

# create workbook
wb <- createWorkbook()

# initialize worksheet
addWorksheet( wb = wb, sheetName = "Sheet1" )

# add iris to Sheet1
writeData( wb = wb
           , sheet = "Sheet1"
           , x = iris
)

# add Excel data validation to cells
dataValidation( wb = wb
                , sheet = "Sheet1"
                , cols = 1:4
                , rows = 2:( 1 + nrow( iris ) )
                , type = "decimal"
                , operator = "between"
                , value = c( 0, 10 )
)
dataValidation( wb = wb
                , sheet = "Sheet1"
                , cols = 5
                , rows = 2:( 1 + nrow( iris ) )
                , type = "textLength"
                , operator = "lessThanOrEqual"
                , value = 10
                )

# view the data in Excel
# notice that the file is no longer corrupt
openXL( file = wb )

# turn off dev_mode
dev_mode( on = FALSE )  # return to CRAN version of openxlsx

# end of script

Answer comes from How to install development version of R packages github repository.

like image 166
Cristian E. Nuno Avatar answered Nov 15 '22 05:11

Cristian E. Nuno