如何使用R的Reticulate包和Python的OpenPyxl来隐藏excel中的行



我正在尝试创建一个带有隐藏/折叠行的 excel 文件,就像在 openpyxl 网页上一样,但通过 R 中的reticulate包。 目前,我可以在此过程中执行所有操作,从生成虚拟数据到保存文件,除了操作工作表的row_dimensions。我之所以走这条路,是因为至少从我发现的情况来看,R 的 excel 编写包都无法折叠行。 下面的代码表示当前表单,虽然它不会更改行尺寸,但能够输出到有效的 excel 文件。

rc1<-letters
rc2<-seq(1,1040,40)
rc3<-seq(0,18199,700)
rc<-data.frame(rc1,rc2,rc3)
library(reticulate)
pyxl<-import("openpyxl")
rct<-pyxl$Workbook()
pcta<-rct$active
pcta$title<-"Trial"
library(magrittr)
for (i in 1:length(rc1)) {
  for (j in 1:length(rc)) {
    a<-rc[i,j]
    a %>% pcta$cell(i,j,.)
  }
}
pcta$row_dimensions[1:4]<-10
rct$save("trial.xlsx")

我还尝试分配给单个值,以便在上述代码中的1:4被替换为 1"1" 时导致以下错误。

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: 'float' object is not iterable 
 Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: '<' not supported between instances of 'str' and 'int' 

大约一个小时后发布我自己问题的答案有点尴尬,但我想我会为了其他可能试图解决类似问题的人的利益而发布它。首先,需要在as.integer()内声明数字以避免浮点类型。其次,pcta$row_dimensions[]不是实现这一目标的方法,而是pcta$row_dimensions$group() .我制作了下面的解决方案。

rc1<-letters
rc2<-seq(1,1040,40)
rc3<-seq(0,18199,700)
rc<-data.frame(rc1,rc2,rc3)
library(reticulate)
pyxl<-import("openpyxl")
rct<-pyxl$Workbook()
pcta<-rct$active
pcta$title<-"Trial"
library(magrittr)
for (i in 1:length(rc1)) {
  for (j in 1:length(rc)) {
    a<-rc[i,j]
    a %>% pcta$cell(i,j,.)
  }
}
pcta$row_dimensions$group(as.integer(1),as.integer(5),hidden = TRUE)
rct$save("trial.xlsx")

最新更新