0

目标是使用 openxlsx 将边框应用于表格的某些部分。接下来,我将展示所需的输出,以一种不是所需的方式构建:打印表格的一部分并在每个步骤中对其进行格式化:

library(openxlsx)
library(tidyverse)
set.seed(15)
###create workbook
wb <- createWorkbook()
addWorksheet(wb, "test2")
#Sample a portion of iris to make it short
iris%>%dplyr::sample_n(15)->sample_iris

#split according to Species
sample_iris%>%filter(Species %in% "setosa")->p1
sample_iris%>%filter(Species %in% "versicolor")->p2
sample_iris%>%filter(Species %in% "virginica")->p3

##write each part and apply borders
writeData(wb, 1,p1, startRow = 1, startCol = 1,borders = "surrounding",borderStyle="thick")
writeData(wb, 1,p2, startRow = 1+dim(p1)[1], startCol = 1,borders = "surrounding",colNames =F,borderStyle="thick")
writeData(wb, 1,p3, startRow = 1+dim(p1)[1]+dim(p2)[1], startCol = 1,borders = "surrounding",colNames =F,borderStyle="thick")
saveWorkbook(wb, "test2.xlsx", overwrite = TRUE)

所以“test2.xlsx”是所需的输出。问题是如何实现它,而不是通过生成文件,而是修改现有文件。我的意思是,如果文件“test1.xlsx”是由

write.xlsx(sample_iris, file = "test1.xlsx")

那么,如何根据需要在现有文件上应用边框?感谢您对此的任何指导

4

1 回答 1

0

接下来是执行任务的代码:

rm(list=ls())
library(tidyverse)
library(openxlsx)

my_borders<-function(wb,sheet_name,a2,vartobrd,borderStyle="thick"){

  btop<-createStyle(border=c("top"),borderStyle=borderStyle)
  bleft<-createStyle(border=c("left"),borderStyle=borderStyle)
  bright<-createStyle(border=c("right"),borderStyle=borderStyle)
  bbottom<-createStyle(border=c("bottom"),borderStyle=borderStyle)
  blb<-createStyle(border=c("left","bottom"),borderStyle=borderStyle)
  bbr<-createStyle(border=c("bottom","right"),borderStyle=borderStyle)

  length_box<-dim(a2)[2]
  floor_bx<-1:length_box%>%.[-c(1,length_box)]
  a2$rnum<-1:dim(a2)[1]
  a2%>%group_by_(vartobrd)%>%summarise(min=min(rnum),max=max(rnum))->box_lm
  box_lm<-as.data.frame(box_lm)

  for(i in seq_along(box_lm[,vartobrd])){
    box_lm%>%filter_(paste0(vartobrd, "%in%","'",  box_lm[i,vartobrd], "'"))%>%
      select(min,max)->minmax_lm
    side_indx<-minmax_lm$min:minmax_lm$max
    cornerindx<-length(side_indx)
    side_indx_sin_corn<-1:(cornerindx-1)
    side_cels<-side_indx[side_indx_sin_corn]
    nside_cels<-length(side_cels)
    corner<-side_indx[cornerindx]
    addStyle(wb, sheet=sheet_name, style = bleft, rows=side_cels+1, cols=rep(1,nside_cels))
    addStyle(wb, sheet=sheet_name, style = bbottom, rows=rep(minmax_lm$max,length_box-2)+1, cols=floor_bx)
    addStyle(wb, sheet=sheet_name, style = bright, rows=side_cels+1, cols=rep(length_box,nside_cels))
    addStyle(wb, sheet=sheet_name, style = blb, rows=corner+1, cols=1)
    addStyle(wb, sheet=sheet_name, style = bbr, rows=corner+1, cols=length_box)
  }
}
#####test the solution
wb <- openxlsx::createWorkbook()
openxlsx::addWorksheet(wb, sheetName = 1)
openxlsx::freezePane(wb, sheet = 1, firstActiveRow = 2)
openxlsx::writeData(wb, x=iris, sheet = 1, colNames =T)  
my_borders(wb,sheet_name=1,a2=iris,borderStyle="thick",vartobrd="Species")
openXL(wb)

我很欣赏对此的任何评论。

于 2018-06-01T02:18:19.963 回答