@@ -20,6 +20,7 @@ data_with_subtotal <- function(workbook, data, sheet.name){
20
20
}
21
21
return (index )
22
22
}
23
+
23
24
24
25
# Excel aggregate function list
25
26
function_table <-
@@ -37,13 +38,21 @@ data_with_subtotal <- function(workbook, data, sheet.name){
37
38
" VAR" ,
38
39
" VARP"
39
40
)
40
- )
41
+ )
42
+
43
+ if (attr(wb , " Class" ) %> % is.null ){
44
+ # Number of sheet with subtotals
45
+ sheet.counts <- 1
46
+ # Set up function list
47
+ addWorksheet(wb , " function.list" , visible = FALSE )
48
+ writeDataTable(wb , " function.list" , function_table )
49
+ } else {
50
+ # Number of sheet with subtotals
51
+ sheet.counts <- as.integer((attr(wb , " Class" ))[2 ]) + 1
52
+ }
41
53
42
- # Set up function list
43
- addWorksheet(wb , " function.list" , visible = FALSE )
44
- writeDataTable(wb , " function.list" , function_table )
45
54
addWorksheet(wb , sheet.name )
46
- table.name <- " data"
55
+ table.name <- glue( " data{sheet.counts} " )
47
56
writeDataTable(wb , sheet.name , data , tableName = table.name , stack = TRUE )
48
57
49
58
# Detect last row and last column
@@ -53,7 +62,8 @@ data_with_subtotal <- function(workbook, data, sheet.name){
53
62
for (i in 1 : ncol(data )) {
54
63
writeFormula(wb ,
55
64
sheet.name ,
56
- glue(" =SUBTOTAL(function.list!$C2,data[{names(data)[i]}])" ),
65
+ glue(" =SUBTOTAL(function.list!$C{sheet.counts + 1}," ,
66
+ " {table.name}[{names(data)[i]}])" ),
57
67
i ,
58
68
last.row )
59
69
}
@@ -71,32 +81,21 @@ data_with_subtotal <- function(workbook, data, sheet.name){
71
81
value =
72
82
glue(" 'function.list'!$B$2:$B${nrow(function_table) + 1}" )
73
83
)
84
+
74
85
writeData(wb , " function.list" , " Detected Function" , 3 , 1 )
75
86
writeFormula(
76
87
wb ,
77
88
" function.list" ,
78
89
glue(" =INDEX(function.list!$A$2:$A{nrow(function_table) + 1}, " ,
79
- " MATCH(data !${excel_col_num(last.col)}${last.row}, " ,
90
+ " MATCH({sheet.name} !${excel_col_num(last.col)}${last.row}, " ,
80
91
" function.list!$B$2:$B{nrow(function_table) + 1}, 1))" ),
81
92
3 ,
82
- 2
93
+ sheet.counts + 1
83
94
)
84
- setColWidths(wb , sheet.name , cols = 1 : ncol(data ), widths = " auto" )
95
+ setColWidths(wb , sheet.name , cols = 1 : ncol(data ), widths = 20 )
96
+
97
+ # Set attribute
98
+ wb <<-
99
+ wb %> %
100
+ structure(. , " Class" = c(" subtotal" , sheet.counts ))
85
101
}
86
-
87
- # -------------------------------------------------------------------------------
88
- # Example
89
- # -------------------------------------------------------------------------------
90
-
91
- wb <- createWorkbook()
92
- set.seed(1024 )
93
-
94
- # Function allows one to add data table to existing workbook.
95
- data_with_subtotal(
96
- workbook = wb ,
97
- data = sample_n(iris , 20 , replace = FALSE ),
98
- sheet.name = " data"
99
- )
100
-
101
- # Save workbook
102
- saveWorkbook(wb , " output/subtotal irist sample.xlsx" , overwrite = TRUE )
0 commit comments