-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathclass-workbook.R
8734 lines (7244 loc) · 290 KB
/
class-workbook.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# R6 class ----------------------------------------------------------------
# Lines 7 and 8 are needed until r-lib/roxygen2#1504 is fixed
#' Workbook class
#'
#' @description
#' This is the class used by `openxlsx2` to modify workbooks from R.
#' You can load an existing workbook with [wb_load()] and create a new one with
#' [wb_workbook()].
#'
#' After that, you can modify the `wbWorkbook` object through two primary methods:
#'
#' *Wrapper Function Method*: Utilizes the `wb` family of functions that support
#' piping to streamline operations.
#' ``` r
#' wb <- wb_workbook(creator = "My name here") %>%
#' wb_add_worksheet(sheet = "Expenditure", grid_lines = FALSE) %>%
#' wb_add_data(x = USPersonalExpenditure, row_names = TRUE)
#' ```
#' *Chaining Method*: Directly modifies the object through a series of chained
#' function calls.
#' ``` r
#' wb <- wb_workbook(creator = "My name here")$
#' add_worksheet(sheet = "Expenditure", grid_lines = FALSE)$
#' add_data(x = USPersonalExpenditure, row_names = TRUE)
#' ```
#'
#' While wrapper functions require explicit assignment of their output to reflect
#' changes, chained functions inherently modify the input object. Both approaches
#' are equally supported, offering flexibility to suit user preferences. The
#' documentation mainly highlights the use of wrapper functions.
#'
#' ``` r
#' # Import workbooks
#' path <- system.file("extdata/openxlsx2_example.xlsx", package = "openxlsx2")
#' wb <- wb_load(path)
#'
#' ## or create one yourself
#' wb <- wb_workbook()
#' # add a worksheet
#' wb$add_worksheet("sheet")
#' # add some data
#' wb$add_data("sheet", cars)
#' # Add data with piping in a different location
#' wb <- wb %>% wb_add_data(x = cars, dims = wb_dims(from_col = "D", from_row = 4))
#' # open it in your default spreadsheet software
#' if (interactive()) wb$open()
#' ```
#'
#' Note that the documentation is more complete in each of the wrapper functions.
#' (i.e. `?wb_add_data` rather than `?wbWorkbook`).
#'
#' @param creator character vector of creators. Duplicated are ignored.
#' @param dims Cell range in a sheet
#' @param sheet The name of the sheet
#' @param datetime_created The datetime (as `POSIXt`) the workbook is
#' created. Defaults to the current `Sys.time()` when the workbook object
#' is created, not when the Excel files are saved.
#' @param ... additional arguments
#' @export
wbWorkbook <- R6::R6Class(
"wbWorkbook",
# TODO which can be private?
## public ----
public = list(
#' @field sheet_names The names of the sheets
sheet_names = character(),
#' @field calcChain calcChain
calcChain = character(),
#' @field charts charts
charts = list(),
#' @field is_chartsheet A logical vector identifying if a sheet is a chartsheet.
is_chartsheet = logical(),
#' @field customXml customXml
customXml = NULL,
#' @field connections connections
connections = NULL,
#' @field ctrlProps ctrlProps
ctrlProps = NULL,
#' @field Content_Types Content_Types
Content_Types = genBaseContent_Type(),
#' @field app app
app = character(),
#' @field core The XML core
core = character(),
#' @field custom custom
custom = character(),
#' @field drawings drawings
drawings = NULL,
#' @field drawings_rels drawings_rels
drawings_rels = NULL,
# #' @field drawings_vml drawings_vml
# drawings_vml = NULL,
#' @field embeddings embeddings
embeddings = NULL,
#' @field externalLinks externalLinks
externalLinks = NULL,
#' @field externalLinksRels externalLinksRels
externalLinksRels = NULL,
#' @field headFoot The header and footer
headFoot = NULL,
#' @field media media
media = NULL,
#' @field metadata contains cell/value metadata imported on load from xl/metadata.xml
metadata = NULL,
#' @field persons Persons of the workbook. to be used with [wb_add_thread()]
persons = NULL,
#' @field pivotTables pivotTables
pivotTables = NULL,
#' @field pivotTables.xml.rels pivotTables.xml.rels
pivotTables.xml.rels = NULL,
#' @field pivotDefinitions pivotDefinitions
pivotDefinitions = NULL,
#' @field pivotRecords pivotRecords
pivotRecords = NULL,
#' @field pivotDefinitionsRels pivotDefinitionsRels
pivotDefinitionsRels = NULL,
#' @field queryTables queryTables
queryTables = NULL,
#' @field slicers slicers
slicers = NULL,
#' @field slicerCaches slicerCaches
slicerCaches = NULL,
#' @field sharedStrings sharedStrings
sharedStrings = structure(list(), uniqueCount = 0L),
#' @field styles_mgr styles_mgr
styles_mgr = NULL,
#' @field tables tables
tables = NULL,
#' @field tables.xml.rels tables.xml.rels
tables.xml.rels = NULL,
#' @field theme theme
theme = NULL,
#' @field vbaProject vbaProject
vbaProject = NULL,
#' @field vml vml
vml = NULL,
#' @field vml_rels vml_rels
vml_rels = NULL,
#' @field comments Comments (notes) present in the workbook.
comments = list(),
#' @field threadComments Threaded comments
threadComments = NULL,
#' @field workbook workbook
workbook = genBaseWorkbook(),
#' @field workbook.xml.rels workbook.xml.rels
workbook.xml.rels = genBaseWorkbook.xml.rels(),
#' @field worksheets worksheets
worksheets = list(),
#' @field worksheets_rels worksheets_rels
worksheets_rels = list(),
#' @field sheetOrder The sheet order. Controls ordering for worksheets and
#' worksheet names.
sheetOrder = integer(),
#' @field path path
path = character(), # allows path to be set during initiation or later
#' @description
#' Creates a new `wbWorkbook` object
#' @param title,subject,category,keywords,comments,manager,company workbook properties
#' @param theme Optional theme identified by string or number
#' @param ... additional arguments
#' @return a `wbWorkbook` object
initialize = function(
creator = NULL,
title = NULL,
subject = NULL,
category = NULL,
datetime_created = Sys.time(),
theme = NULL,
keywords = NULL,
comments = NULL,
manager = NULL,
company = NULL,
...
) {
force(datetime_created)
standardize_case_names(...)
self$app <- genBaseApp()
self$charts <- list()
self$is_chartsheet <- logical()
self$connections <- NULL
self$Content_Types <- genBaseContent_Type()
creator <- creator %||%
getOption("openxlsx2.creator",
default = Sys.getenv("USERNAME", unset = Sys.getenv("USER")))
# USERNAME is present for (Windows, Linux) "USER" is present for Mac
datetime_created <- getOption("openxlsx2.datetimeCreated", datetime_created)
assert_class(creator, "character")
assert_class(title, "character", or_null = TRUE)
assert_class(subject, "character", or_null = TRUE)
assert_class(category, "character", or_null = TRUE)
assert_class(keywords, "character", or_null = TRUE)
assert_class(comments, "character", or_null = TRUE)
assert_class(manager, "character", or_null = TRUE)
assert_class(company, "character", or_null = TRUE)
assert_class(datetime_created, "POSIXt")
stopifnot(
length(title) <= 1L,
length(category) <= 1L,
length(datetime_created) == 1L
)
self$set_properties(
creator = creator,
title = title,
subject = subject,
category = category,
datetime_created = datetime_created,
keywords = keywords,
comments = comments,
manager = manager,
company = company
)
self$comments <- list()
self$threadComments <- list()
self$drawings <- list()
self$drawings_rels <- list()
# self$drawings_vml <- list()
self$embeddings <- NULL
self$externalLinks <- NULL
self$externalLinksRels <- NULL
self$headFoot <- NULL
self$media <- list()
self$metadata <- NULL
self$persons <- NULL
self$pivotTables <- NULL
self$pivotTables.xml.rels <- NULL
self$pivotDefinitions <- NULL
self$pivotRecords <- NULL
self$pivotDefinitionsRels <- NULL
self$queryTables <- NULL
self$slicers <- NULL
self$slicerCaches <- NULL
self$sheet_names <- character()
self$sheetOrder <- integer()
self$sharedStrings <- list()
attr(self$sharedStrings, "uniqueCount") <- 0
# add styles_mgr and set default styles. will initialize after theme
self$styles_mgr <- style_mgr$new(self)
self$styles_mgr$styles <- genBaseStyleSheet()
empty_cellXfs <- data.frame(
numFmtId = "0",
fontId = "0",
fillId = "0",
borderId = "0",
xfId = "0",
stringsAsFactors = FALSE
)
self$styles_mgr$styles$cellXfs <- write_xf(empty_cellXfs)
self$tables <- NULL
self$tables.xml.rels <- NULL
if (is.null(theme)) {
self$theme <- NULL
} else {
# read predefined themes
thm_rds <- system.file("extdata", "themes.rds", package = "openxlsx2")
themes <- readRDS(thm_rds)
if (is.character(theme)) {
sel <- match(theme, names(themes))
err <- is.na(sel)
} else {
sel <- theme
err <- sel > length(themes)
}
if (err) {
message("theme ", theme, " not found falling back to default theme")
} else {
self$theme <- stringi::stri_unescape_unicode(themes[[sel]])
# create the default font for the style
font_scheme <- xml_node(self$theme, "a:theme", "a:themeElements", "a:fontScheme")
minor_font <- xml_attr(font_scheme, "a:fontScheme", "a:minorFont", "a:latin")[[1]][["typeface"]]
self$styles_mgr$styles$fonts <- create_font(
sz = 11,
color = wb_color(theme = 1),
name = minor_font,
family = "2",
scheme = "minor"
)
}
}
self$styles_mgr$initialize(self)
self$vbaProject <- NULL
self$vml <- NULL
self$vml_rels <- NULL
private$current_sheet <- 0L
invisible(self)
},
#' @description
#' Append a field. This method is intended for internal use
#' @param field A valid field name
#' @param value A value for the field
append = function(field, value) {
self[[field]] <- c(self[[field]], value)
invisible(self)
},
#' @description
#' Append to `self$workbook$sheets` This method is intended for internal use
#' @param value A value for `self$workbook$sheets`
append_sheets = function(value) {
self$workbook$sheets <- c(self$workbook$sheets, value)
invisible(self)
},
#' @description validate sheet
#' @param sheet A character sheet name or integer location
#' @return The integer position of the sheet
validate_sheet = function(sheet) {
# workbook has no sheets
if (!length(self$sheet_names)) {
return(NA_integer_)
}
# write_comment uses wb_validate and bails otherwise
if (inherits(sheet, "openxlsx2_waiver")) {
sheet <- private$get_sheet_index(sheet)
}
# input is number
if (is.numeric(sheet)) {
badsheet <- !sheet %in% seq_along(self$sheet_names)
if (any(badsheet)) sheet[badsheet] <- NA_integer_
return(sheet)
}
if (!sheet %in% replaceXMLEntities(self$sheet_names)) {
return(NA_integer_)
}
which(replaceXMLEntities(self$sheet_names) == sheet)
},
#' @description
#' Add a chart sheet to the workbook
#' @param tab_color tab_color
#' @param zoom zoom
#' @param visible visible
#' @return The `wbWorkbook` object, invisibly
add_chartsheet = function(
sheet = next_sheet(),
tab_color = NULL,
zoom = 100,
visible = c("true", "false", "hidden", "visible", "veryhidden"),
...
) {
visible <- tolower(as.character(visible))
visible <- match.arg(visible)
# set up so that a single error can be reported on fail
fail <- FALSE
msg <- NULL
private$validate_new_sheet(sheet)
if (is_waiver(sheet)) {
if (sheet == "current_sheet") {
stop("cannot add worksheet to current sheet")
}
# TODO openxlsx2.sheet.default_name is undocumented. should incorporate
# a better check for this
default_sheet_name <- getOption("openxlsx2.sheet.default_name", "Sheet ")
default_sheets <- self$sheet_names[grepl(default_sheet_name, self$sheet_names)]
max_sheet_num <- max(
0,
as.integer(gsub("\\D+", "", default_sheets))
)
sheet <- paste0(
default_sheet_name,
max_sheet_num + 1L
)
}
sheet <- as.character(sheet)
private$validate_new_sheet(sheet)
sheet_name <- replace_legal_chars(sheet)
newSheetIndex <- length(self$worksheets) + 1L
private$set_current_sheet(newSheetIndex)
sheetId <- private$get_sheet_id_max() # checks for self$worksheet length
self$append_sheets(
sprintf(
'<sheet name="%s" sheetId="%s" state="%s" r:id="rId%s"/>',
sheet_name,
sheetId,
visible,
newSheetIndex
)
)
standardize(...)
if (!is.null(tab_color) && !is_wbColour(tab_color)) {
validate_color(tab_color, msg = "Invalid tab_color in add_chartsheet.")
tabColor <- wb_color(tab_color)
} else {
tabColor <- tab_color
}
if (!is.numeric(zoom)) {
fail <- TRUE
msg <- c(msg, "zoom must be numeric")
}
# nocov start
if (zoom < 10) {
zoom <- 10
} else if (zoom > 400) {
zoom <- 400
}
#nocov end
self$append("worksheets",
wbChartSheet$new(
tab_color = tabColor
)
)
self$worksheets[[newSheetIndex]]$set_sheetview(
workbook_view_id = 0,
zoom_scale = zoom,
tab_selected = newSheetIndex == 1
)
self$append("sheet_names", sheet)
## update content_tyes
self$append("Content_Types",
sprintf(
'<Override PartName="/xl/chartsheets/sheet%s.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml"/>',
newSheetIndex
)
)
## Update xl/rels
self$append("workbook.xml.rels",
sprintf(
'<Relationship Id="rId0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet%s.xml"/>',
newSheetIndex
)
)
## create sheet.rels to simplify id assignment
# new_drawings_idx <- length(self$drawings) + 1
# self$drawings[[new_drawings_idx]] <- ""
# self$drawings_rels[[new_drawings_idx]] <- ""
self$worksheets_rels[[newSheetIndex]] <- genBaseSheetRels(newSheetIndex)
self$is_chartsheet[[newSheetIndex]] <- TRUE
# self$vml_rels[[newSheetIndex]] <- list()
# self$vml[[newSheetIndex]] <- list()
self$append("sheetOrder", newSheetIndex)
private$set_single_sheet_name(newSheetIndex, sheet_name, sheet)
invisible(self)
},
#' @description
#' Add worksheet to the `wbWorkbook` object
#' @param grid_lines gridLines
#' @param row_col_headers rowColHeaders
#' @param tab_color tabColor
#' @param zoom zoom
#' @param header header
#' @param footer footer
#' @param odd_header oddHeader
#' @param odd_footer oddFooter
#' @param even_header evenHeader
#' @param even_footer evenFooter
#' @param first_header firstHeader
#' @param first_footer firstFooter
#' @param visible visible
#' @param has_drawing hasDrawing
#' @param paper_size paperSize
#' @param orientation orientation
#' @param hdpi hdpi
#' @param vdpi vdpi
#' @return The `wbWorkbook` object, invisibly
add_worksheet = function(
sheet = next_sheet(),
grid_lines = TRUE,
row_col_headers = TRUE,
tab_color = NULL,
zoom = 100,
header = NULL,
footer = NULL,
odd_header = header,
odd_footer = footer,
even_header = header,
even_footer = footer,
first_header = header,
first_footer = footer,
visible = c("true", "false", "hidden", "visible", "veryhidden"),
has_drawing = FALSE,
paper_size = getOption("openxlsx2.paperSize", default = 9),
orientation = getOption("openxlsx2.orientation", default = "portrait"),
hdpi = getOption("openxlsx2.hdpi", default = getOption("openxlsx2.dpi", default = 300)),
vdpi = getOption("openxlsx2.vdpi", default = getOption("openxlsx2.dpi", default = 300)),
...
) {
standardize(...)
visible <- tolower(as.character(visible))
visible <- match.arg(visible)
orientation <- match.arg(orientation, c("portrait", "landscape"))
# set up so that a single error can be reported on fail
fail <- FALSE
msg <- NULL
private$validate_new_sheet(sheet)
if (is_waiver(sheet)) {
if (sheet == "current_sheet") {
stop("cannot add worksheet to current sheet")
}
# TODO openxlsx2.sheet.default_name is undocumented. should incorporate
# a better check for this
default_sheet_name <- getOption("openxlsx2.sheet.default_name", "Sheet ")
default_sheets <- self$sheet_names[grepl(default_sheet_name, self$sheet_names)]
max_sheet_num <- max(
0,
as.integer(gsub("\\D+", "", default_sheets))
)
sheet <- paste0(
default_sheet_name,
max_sheet_num + 1L
)
}
sheet <- as.character(sheet)
private$validate_new_sheet(sheet)
sheet_name <- replace_legal_chars(sheet)
if (!is.logical(grid_lines) | length(grid_lines) > 1) {
fail <- TRUE
msg <- c(msg, "grid_lines must be a logical of length 1.")
}
if (!is.null(tab_color) && !is_wbColour(tab_color)) {
validate_color(tab_color, msg = "Invalid tab_color in add_worksheet.")
tabColor <- wb_color(tab_color)
} else {
tabColor <- tab_color
}
if (!is.numeric(zoom)) {
fail <- TRUE
msg <- c(msg, "zoom must be numeric")
}
# nocov start
if (zoom < 10) {
zoom <- 10
} else if (zoom > 400) {
zoom <- 400
}
#nocov end
if (!is.null(odd_header) & length(odd_header) != 3) {
fail <- TRUE
msg <- c(msg, lcr("header"))
}
if (!is.null(odd_footer) & length(odd_footer) != 3) {
fail <- TRUE
msg <- c(msg, lcr("footer"))
}
if (!is.null(even_header) & length(even_header) != 3) {
fail <- TRUE
msg <- c(msg, lcr("evenHeader"))
}
if (!is.null(even_footer) & length(even_footer) != 3) {
fail <- TRUE
msg <- c(msg, lcr("evenFooter"))
}
if (!is.null(first_header) & length(first_header) != 3) {
fail <- TRUE
msg <- c(msg, lcr("firstHeader"))
}
if (!is.null(first_footer) & length(first_footer) != 3) {
fail <- TRUE
msg <- c(msg, lcr("firstFooter"))
}
vdpi <- as.integer(vdpi)
hdpi <- as.integer(hdpi)
if (is.na(vdpi)) {
fail <- TRUE
msg <- c(msg, "vdpi must be numeric")
}
if (is.na(hdpi)) {
fail <- TRUE
msg <- c(msg, "hdpi must be numeric")
}
if (fail) {
stop(msg, call. = FALSE)
}
newSheetIndex <- length(self$worksheets) + 1L
private$set_current_sheet(newSheetIndex)
sheetId <- private$get_sheet_id_max() # checks for self$worksheet length
# check for errors ----
visible <- switch(
visible,
true = "visible",
false = "hidden",
veryhidden = "veryHidden",
visible
)
self$append_sheets(
sprintf(
'<sheet name="%s" sheetId="%s" state="%s" r:id="rId%s"/>',
sheet_name,
sheetId,
visible,
newSheetIndex
)
)
## append to worksheets list
self$append("worksheets",
wbWorksheet$new(
tab_color = tabColor,
odd_header = odd_header,
odd_footer = odd_footer,
even_header = even_header,
even_footer = even_footer,
first_header = first_header,
first_footer = first_footer,
paper_size = paper_size,
orientation = orientation,
hdpi = hdpi,
vdpi = vdpi,
grid_lines = grid_lines
)
)
# NULL or TRUE/FALSE
rightToLeft <- getOption("openxlsx2.rightToLeft")
# set preselected set for sheetview
self$worksheets[[newSheetIndex]]$set_sheetview(
workbook_view_id = 0,
zoom_scale = zoom,
show_grid_lines = grid_lines,
show_row_col_headers = row_col_headers,
tab_selected = newSheetIndex == 1,
right_to_left = rightToLeft
)
## update content_tyes
## add a drawing.xml for the worksheet
if (has_drawing) {
self$append("Content_Types", c(
sprintf('<Override PartName="/xl/worksheets/sheet%s.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>', newSheetIndex),
sprintf('<Override PartName="/xl/drawings/drawing%s.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>', newSheetIndex)
))
} else {
self$append("Content_Types",
sprintf(
'<Override PartName="/xl/worksheets/sheet%s.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>',
newSheetIndex
)
)
}
## Update xl/rels
self$append("workbook.xml.rels",
sprintf(
'<Relationship Id="rId0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet%s.xml"/>',
newSheetIndex
)
)
## create sheet.rels to simplify id assignment
new_drawings_idx <- length(self$drawings) + 1
# self$drawings[[new_drawings_idx]] <- ""
# self$drawings_rels[[new_drawings_idx]] <- ""
self$worksheets_rels[[newSheetIndex]] <- genBaseSheetRels(newSheetIndex)
# self$vml_rels[[newSheetIndex]] <- list()
# self$vml[[newSheetIndex]] <- list()
self$is_chartsheet[[newSheetIndex]] <- FALSE
# self$comments[[newSheetIndex]] <- list()
# self$threadComments[[newSheetIndex]] <- list()
self$append("sheetOrder", as.integer(newSheetIndex))
private$set_single_sheet_name(newSheetIndex, sheet_name, sheet)
invisible(self)
},
#' @description
#' Clone a workbooksheet to another workbook
#' @param old name of worksheet to clone
#' @param new name of new worksheet to add
#' @param from name of new worksheet to add
clone_worksheet = function(old = current_sheet(), new = next_sheet(), from = NULL) {
if (is.null(from)) {
from <- self$clone()
external_wb <- FALSE
suffix <- "_n"
} else {
external_wb <- TRUE
suffix <- ""
assert_workbook(from)
}
sheet <- new
private$validate_new_sheet(sheet)
new <- sheet
old <- from$.__enclos_env__$private$get_sheet_index(old)
newSheetIndex <- length(self$worksheets) + 1L
private$set_current_sheet(newSheetIndex)
sheetId <- private$get_sheet_id_max() # checks for length of worksheets
if (!all(from$charts$chartEx == "")) {
warning(
"The file you have loaded contains chart extensions. At the moment,",
" cloning worksheets can damage the output."
)
}
# not the best but a quick fix
new_raw <- new
new <- replace_legal_chars(new)
## copy visibility from cloned sheet!
visible <- rbindlist(xml_attr(from$workbook$sheets[[old]], "sheet"))$state
## Add sheet to workbook.xml
self$append_sheets(
xml_node_create(
"sheet",
xml_attributes = c(
name = new,
sheetId = sheetId,
state = visible,
`r:id` = paste0("rId", newSheetIndex)
)
)
)
## append to worksheets list
self$append("worksheets", from$worksheets[[old]]$clone(deep = TRUE))
## update content_tyes
## add a drawing.xml for the worksheet
# FIXME only add what is needed. If no previous drawing is found, don't
# add a new one
self$append("Content_Types", c(
if (from$is_chartsheet[old]) {
sprintf('<Override PartName="/xl/chartsheets/sheet%s.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml"/>', newSheetIndex)
} else {
sprintf('<Override PartName="/xl/worksheets/sheet%s.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>', newSheetIndex)
}
))
## Update xl/rels
self$append(
"workbook.xml.rels",
if (from$is_chartsheet[old]) {
sprintf('<Relationship Id="rId0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet%s.xml"/>', newSheetIndex)
} else {
sprintf('<Relationship Id="rId0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet%s.xml"/>', newSheetIndex)
}
)
## create sheet.rels to simplify id assignment
self$worksheets_rels[[newSheetIndex]] <- from$worksheets_rels[[old]]
old_drawing_sheet <- NULL
if (length(from$worksheets_rels[[old]])) {
relship <- rbindlist(xml_attr(from$worksheets_rels[[old]], "Relationship"))
relship$typ <- basename(relship$Type)
old_drawing_sheet <- as.integer(gsub("\\D+", "", relship$Target[relship$typ == "drawing"]))
}
if (length(old_drawing_sheet) && length(from$worksheets[[old_drawing_sheet]]$relships$drawing)) {
drawing_id <- from$worksheets[[old_drawing_sheet]]$relships$drawing
new_drawing_sheet <- length(self$drawings) + 1L
self$append("drawings_rels", from$drawings_rels[[drawing_id]])
# give each chart its own filename (images can re-use the same file, but charts can't)
self$drawings_rels[[new_drawing_sheet]] <-
# TODO Can this be simplified? There's a bit going on here
vapply(
self$drawings_rels[[new_drawing_sheet]],
function(rl) {
# is rl here a length of 1?
stopifnot(length(rl) == 1L) # lets find out... if this fails, just remove it
chartfiles <- reg_match(rl, "(?<=charts/)chart[0-9]+\\.xml")
for (cf in chartfiles) {
chartid <- NROW(self$charts) + 1L
newname <- stri_join("chart", chartid, ".xml")
old_chart <- as.integer(gsub("\\D+", "", cf))
self$charts <- rbind(self$charts, from$charts[old_chart, ])
# Read the chartfile and adjust all formulas to point to the new
# sheet name instead of the clone source
chart <- self$charts$chart[chartid]
self$charts$rels[chartid] <- gsub("?drawing[0-9]+.xml", paste0("drawing", chartid, ".xml"), self$charts$rels[chartid])
guard_ws <- function(x) {
if (grepl(" ", x)) x <- shQuote(x, type = "sh")
x
}
old_sheet_name <- guard_ws(from$sheet_names[[old]])
new_sheet_name <- guard_ws(new)
## we need to replace "'oldname'" as well as "oldname"
chart <- gsub(
paste0(">", old_sheet_name, "!"),
paste0(">", new_sheet_name, "!"),
chart,
perl = TRUE
)
self$charts$chart[chartid] <- chart
# two charts can not point to the same rels
if (self$charts$rels[chartid] != "") {
self$charts$rels[chartid] <- gsub(
stri_join(old_chart, ".xml"),
stri_join(chartid, ".xml"),
self$charts$rels[chartid]
)
}
rl <- gsub(stri_join("(?<=charts/)", cf), newname, rl, perl = TRUE)
}
rl
},
NA_character_,
USE.NAMES = FALSE
)
self$append("drawings", from$drawings[[drawing_id]])
}
## TODO Currently it is not possible to clone a sheet with a slicer in a
# safe way. It will always result in a broken xlsx file which is fixable
# but will not contain a slicer.
# most likely needs to add slicerCache for each slicer with updated names
## SLICERS
rid <- as.integer(sub("\\D+", "", get_relship_id(obj = self$worksheets_rels[[newSheetIndex]], "slicer")))
if (length(rid)) {
warning("Cloning slicers is not yet supported. It will not appear on the sheet.")
self$worksheets_rels[[newSheetIndex]] <- relship_no(obj = self$worksheets_rels[[newSheetIndex]], x = "slicer")
newid <- length(self$slicers) + 1
cloned_slicers <- from$slicers[[old]]
slicer_attr <- xml_attr(cloned_slicers, "slicers")
# Replace name with name_n. This will prevent the slicer from loading,
# but the xlsx file is not broken
slicer_child <- xml_node(cloned_slicers, "slicers", "slicer")
slicer_df <- rbindlist(xml_attr(slicer_child, "slicer"))[c("name", "cache", "caption", "rowHeight")]
slicer_df$name <- paste0(slicer_df$name, suffix)
slicer_child <- df_to_xml("slicer", slicer_df)
self$slicers[[newid]] <- xml_node_create("slicers", slicer_child, slicer_attr[[1]])
self$worksheets_rels[[newSheetIndex]] <- c(
self$worksheets_rels[[newSheetIndex]],
sprintf("<Relationship Id=\"rId%s\" Type=\"http://schemas.microsoft.com/office/2007/relationships/slicer\" Target=\"../slicers/slicer%s.xml\"/>",
rid,
newid)
)
self$Content_Types <- c(
self$Content_Types,
sprintf("<Override PartName=\"/xl/slicers/slicer%s.xml\" ContentType=\"application/vnd.ms-excel.slicer+xml\"/>", newid)
)
}
# The IDs in the drawings array are sheet-specific, so within the new
# cloned sheet the same IDs can be used => no need to modify drawings