Openxlsx多次验证会破坏输出文件

时间:2018-02-17 17:35:28

标签: r

我正在尝试添加多个验证并将公式添加到Excel文件中。这是我使用的代码:

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)

如果我只使用一个dataValidation它会打开okey,如果有多个抱怨该文件已损坏...

1 个答案:

答案 0 :(得分:2)

不幸的是,这看起来像data validation type 'list' fails when there are more than one on a sheet #266中发现的错误。

幸运的是,there's a pull request that attempts to fix this issue。使用devtools::dev_mode(),您可以安装tkunstek/openxlsx版本,而无需删除并重新安装openxlsx的CRAN版本。

# 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

答案来自How to install development version of R packages github repository