我在一個 Excel 作業表中向多個資料框添加樣式時遇到問題。我想為一張表中的每個表格分別繪制邊框。
我已經有一個代碼可以自動從串列中添加多個資料框:
library(openxlsx)
# Data
table1 <- data.frame("Num" = c(5,6,8,10), "Call" = c(1,2,3,4), "Name" = c("a", "b", "c", "d"), stringsAsFactors = FALSE)
table2 <- data.frame("Num" = c(8,1,11,54,3,5), "Call" = c(1,2,3,4,5,6), "Name" = c("f", "g", "h", "i", "j", "k"), "Age" = c(55,21,30,74,16,41), stringsAsFactors = FALSE)
df_list <- list(table1=table1, table2=table2)
wb <- createWorkbook()
addWorksheet(wb, sheetName ="first")
s1 <- createStyle(border = "TopBottomLeftRight")
curr_row <- 1
curr_col <- 1
for(i in seq_along(df_list)) {
writeData(wb, "first", names(df_list)[i], startCol = 1, startRow = curr_row)
writeData(wb, "first", df_list[[i]], startCol = 1, startRow = curr_row 1, rowNames = TRUE)
curr_row <- curr_row nrow(df_list[[i]]) 3
}
saveWorkbook(wb, paste0(Sys.Date()," Test_file (openxlsx)",".xlsx"))
所以一個問題是是否有任何解決方案通過回圈添加樣式到每個資料幀?或者我必須為每個表單獨撰寫 addStyle ?
謝謝!
uj5u.com熱心網友回復:
因此,如果我說得對,您希望在每張桌子周圍都有邊框。
附上您可以找到一個示例,其中每個表格周圍都有邊框(不包括表格名稱)。我還添加了一個額外的 table3 來測驗實作。此程序適用于任意數量的行和列。
library(openxlsx)
# Data
table1 <- data.frame("Num" = c(5,6,8,10), "Call" = c(1,2,3,4), "Name" = c("a", "b", "c", "d"), stringsAsFactors = FALSE)
table2 <- data.frame("Num" = c(8,1,11,54,3,5), "Call" = c(1,2,3,4,5,6), "Name" = c("f", "g", "h", "i", "j", "k"), "Age" = c(55,21,30,74,16,41), stringsAsFactors = FALSE)
table3 <- data.frame("Num" = c(8,1,11,54,3,5, 10, 10), "Call" = c(0, 0, 1,2,3,4,5,6), "Name" = c("a", "b", "f", "g", "h", "i", "j", "k"), "Age" = c(0, 0, 55,21,30,74,16,41),
"Test" = c(0, 0, 55,21,30,74,16,41), stringsAsFactors = FALSE)
df_list <- list(table1=table1, table2=table2, table3 = table3)
wb <- createWorkbook()
addWorksheet(wb, sheetName ="first")
s1 <- createStyle(border = "TopBottomLeftRight")
curr_row <- 1
curr_col <- 1
for(i in seq_along(df_list)) {
writeData(wb, "first", names(df_list)[i], startCol = 1, startRow = curr_row)
writeData(wb, "first", df_list[[i]], startCol = 1, startRow = curr_row 1, rowNames = TRUE)
addStyle(wb, sheet = "first", style = s1, rows = (curr_row 1):(nrow(df_list[[i]]) (curr_row 1)), cols = 1:(1 ncol(df_list[[i]])), gridExpand = TRUE)
curr_row <- curr_row nrow(df_list[[i]]) 3
}
saveWorkbook(wb, paste0(Sys.Date()," Test_file (openxlsx)",".xlsx"))
由
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472052.html
