-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathclass-workbook-wrappers.R
2516 lines (2380 loc) · 79.5 KB
/
class-workbook-wrappers.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
#' Create a new Workbook object
#'
#' Create a new Workbook object
#'
#' @param creator Creator of the workbook (your name). Defaults to login username
#' @param title Workbook properties title
#' @param subject Workbook properties subject
#' @param category Workbook properties category
#' @param datetimeCreated The time of the workbook is created
#' @return A [wbWorkbook] object
#'
#' @export
#' @family workbook wrappers
#'
#' @examples
#' ## Create a new workbook
#' wb <- wb_workbook()
#'
#' ## Set Workbook properties
#' wb <- wb_workbook(
#' creator = "Me",
#' title = "Expense Report",
#' subject = "Expense Report - 2022 Q1",
#' category = "sales"
#' )
wb_workbook <- function(
creator = NULL,
title = NULL,
subject = NULL,
category = NULL,
datetimeCreated = Sys.time()
) {
wbWorkbook$new(
creator = creator,
title = title,
subject = subject,
category = category,
datetimeCreated = datetimeCreated
)
}
#' Save Workbook to file
#'
#' @param wb A `wbWorkbook` object to write to file
#' @param path A path to save the workbook to
#' @param overwrite If `FALSE`, will not overwrite when `path` exists
#'
#' @export
#' @family workbook wrappers
#'
#' @examples
#' ## Create a new workbook and add a worksheet
#' wb <- wb_workbook("Creator of workbook")
#' wb$add_worksheet(sheet = "My first worksheet")
#'
#' ## Save workbook to working directory
#' \donttest{
#' wb_save(wb, path = temp_xlsx(), overwrite = TRUE)
#' }
wb_save <- function(wb, path = NULL, overwrite = TRUE) {
assert_workbook(wb)
wb$clone()$save(path = path, overwrite = overwrite)$path
}
# add data ----------------------------------------------------------------
#' Add data to a worksheet
#'
#' Add data to worksheet with optional styling.
#'
#' @param wb A Workbook object containing a worksheet.
#' @param sheet The worksheet to write to. Can be the worksheet index or name.
#' @param x Object to be written. For classes supported look at the examples.
#' @param startCol A vector specifying the starting column to write to.
#' @param startRow A vector specifying the starting row to write to.
#' @param dims Spreadsheet dimensions that will determine startCol and startRow: "A1", "A1:B2", "A:B"
#' @param array A bool if the function written is of type array
#' @param xy An alternative to specifying `startCol` and
#' `startRow` individually. A vector of the form
#' `c(startCol, startRow)`.
#' @param colNames If `TRUE`, column names of x are written.
#' @param rowNames If `TRUE`, data.frame row names of x are written.
#' @param withFilter If `TRUE`, add filters to the column name row. NOTE can only have one filter per worksheet.
#' @param name If not NULL, a named region is defined.
#' @param sep Only applies to list columns. The separator used to collapse list columns to a character vector e.g. sapply(x$list_column, paste, collapse = sep).
#' @param applyCellStyle Should we write cell styles to the workbook
#' @param removeCellStyle keep the cell style?
#' @param na.strings na.strings
#' @export
#' @details Formulae written using write_formula to a Workbook object will not get picked up by read_xlsx().
#' This is because only the formula is written and left to Excel to evaluate the formula when the file is opened in Excel.
#' The string `"_openxlsx_NA"` is reserved for `openxlsx2`. If the data frame contains this string, the output will be broken.
#' @rdname write_data
#' @family workbook wrappers
#' @return A clone of `wb``
wb_add_data <- function(
wb,
sheet = current_sheet(),
x,
startCol = 1,
startRow = 1,
dims = rowcol_to_dims(startRow, startCol),
array = FALSE,
xy = NULL,
colNames = TRUE,
rowNames = FALSE,
withFilter = FALSE,
name = NULL,
sep = ", ",
applyCellStyle = TRUE,
removeCellStyle = FALSE,
na.strings
) {
assert_workbook(wb)
if (missing(na.strings)) na.strings <- substitute()
wb$clone(deep = TRUE)$add_data(
sheet = sheet,
x = x,
startCol = startCol,
startRow = startRow,
dims = dims,
array = array,
xy = xy,
colNames = colNames,
rowNames = rowNames,
withFilter = withFilter,
name = name,
sep = sep,
applyCellStyle = applyCellStyle,
removeCellStyle = removeCellStyle,
na.strings = na.strings
)
}
#' Add data to a worksheet as an Excel table
#'
#' Add data to a worksheet and format as an Excel table
#'
#' @param wb A Workbook object containing a #' worksheet.
#' @param sheet The worksheet to write to. Can be the worksheet index or name.
#' @param x A dataframe.
#' @param startCol A vector specifying the starting column to write df
#' @param startRow A vector specifying the starting row to write df
#' @param dims Spreadsheet dimensions that will determine startCol and startRow: "A1", "A1:B2", "A:B"
#' @param xy An alternative to specifying startCol and startRow individually. A
#' vector of the form c(startCol, startRow)
#' @param colNames If `TRUE`, column names of x are written.
#' @param rowNames If `TRUE`, row names of x are written.
#' @param tableStyle Any excel table style name or "none" (see "formatting"
#' vignette).
#' @param tableName name of table in workbook. The table name must be unique.
#' @param withFilter If `TRUE`, columns with have filters in the first row.
#' @param sep Only applies to list columns. The separator used to collapse list
#' columns to a character vector e.g. sapply(x$list_column, paste, collapse =
#' sep).
#' \cr\cr
#' \cr**The below options correspond to Excel table options:**
#' \cr
#' \if{html}{\figure{tableoptions.png}{options: width="40\%" alt="Figure: table_options.png"}}
#' \if{latex}{\figure{tableoptions.pdf}{options: width=7cm}}
#'
#' @param firstColumn logical. If TRUE, the first column is bold
#' @param lastColumn logical. If TRUE, the last column is bold
#' @param bandedRows logical. If TRUE, rows are colour banded
#' @param bandedCols logical. If TRUE, the columns are colour banded
#' @param applyCellStyle Should we write cell styles to the workbook
#' @param removeCellStyle keep the cell style?
#' @param na.strings optional
#'
#' @details columns of x with class Date/POSIXt, currency, accounting,
#' hyperlink, percentage are automatically styled as dates, currency,
#' accounting, hyperlinks, percentages respectively. The string `"_openxlsx_NA"`
#' is reserved for `openxlsx2`. If the data frame contains this string, the
#' output will be broken.
#' @family workbook wrappers
#' @export
wb_add_data_table <- function(
wb,
sheet = current_sheet(),
x,
startCol = 1,
startRow = 1,
dims = rowcol_to_dims(startRow, startCol),
xy = NULL,
colNames = TRUE,
rowNames = FALSE,
tableStyle = "TableStyleLight9",
tableName = NULL,
withFilter = TRUE,
sep = ", ",
firstColumn = FALSE,
lastColumn = FALSE,
bandedRows = TRUE,
bandedCols = FALSE,
applyCellStyle = TRUE,
removeCellStyle = FALSE,
na.strings
) {
assert_workbook(wb)
if (missing(na.strings)) na.strings <- substitute()
wb$clone()$add_data_table(
sheet = sheet,
x = x,
startCol = startCol,
startRow = startRow,
dims = dims,
xy = xy,
colNames = colNames,
rowNames = rowNames,
tableStyle = tableStyle,
tableName = tableName,
withFilter = withFilter,
sep = sep,
firstColumn = firstColumn,
lastColumn = lastColumn,
bandedRows = bandedRows,
bandedCols = bandedCols,
applyCellStyle = applyCellStyle,
removeCellStyle = removeCellStyle,
na.strings = na.strings
)
}
#' Add a character vector as an Excel Formula
#'
#' Add a character vector containing Excel formula to a worksheet.
#'
#' @details Currently only the English version of functions are supported. Please don't use the local translation.
#' The examples below show a small list of possible formulas:
#' \itemize{
#' \item{SUM(B2:B4)}
#' \item{AVERAGE(B2:B4)}
#' \item{MIN(B2:B4)}
#' \item{MAX(B2:B4)}
#' \item{...}
#'
#' }
#' @param wb A Workbook object containing a worksheet.
#' @param sheet The worksheet to write to. Can be the worksheet index or name.
#' @param x A character vector.
#' @param startCol A vector specifying the starting column to write to.
#' @param startRow A vector specifying the starting row to write to.
#' @param dims Spreadsheet dimensions that will determine startCol and startRow: "A1", "A1:B2", "A:B"
#' @param array A bool if the function written is of type array
#' @param xy An alternative to specifying `startCol` and
#' `startRow` individually. A vector of the form
#' `c(startCol, startRow)`.
#' @param applyCellStyle Should we write cell styles to the workbook
#' @param removeCellStyle keep the cell style?
#' @family workbook wrappers
#' @export
wb_add_formula <- function(
wb,
sheet = current_sheet(),
x,
startCol = 1,
startRow = 1,
dims = rowcol_to_dims(startRow, startCol),
array = FALSE,
xy = NULL,
applyCellStyle = TRUE,
removeCellStyle = FALSE
) {
assert_workbook(wb)
wb$clone()$add_formula(
sheet = sheet,
x = x,
startCol = startCol,
startRow = startRow,
dims = dims,
array = array,
xy = xy,
applyCellStyle = applyCellStyle,
removeCellStyle = removeCellStyle
)
}
# merge cells -------------------------------------------------------------
#' Worksheet cell merging
#'
#' Merge cells within a worksheet
#'
#' @details As merged region must be rectangular, only min and max of cols and
#' rows are used.
#'
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param cols,rows Column and row specifications to merge on. Note: `min()` and
#' `max()` of each vector are provided for specs. Skipping rows or columns is
#' not recognized.
#'
#' @examples
#' # Create a new workbook
#' wb <- wb_workbook()
#'
#' # Add a worksheets
#' wb$add_worksheet("Sheet 1")
#' wb$add_worksheet("Sheet 2")
#'
#' # Merge cells: Row 2 column C to F (3:6)
#' wb <- wb_merge_cells(wb, "Sheet 1", cols = 2, rows = 3:6)
#'
#' # Merge cells:Rows 10 to 20 columns A to J (1:10)
#' wb <- wb_merge_cells(wb, 1, cols = 1:10, rows = 10:20)
#'
#' # Intersecting merges
#' wb <- wb_merge_cells(wb, 2, cols = 1:10, rows = 1)
#' wb <- wb_merge_cells(wb, 2, cols = 5:10, rows = 2)
#' wb <- wb_merge_cells(wb, 2, cols = c(1, 10), rows = 12) # equivalent to 1:10
#' try(wb_merge_cells(wb, 2, cols = 1, rows = c(1,10))) # intersects existing merge
#'
#' # remove merged cells
#' wb <- wb_unmerge_cells(wb, 2, cols = 1, rows = 1) # removes any intersecting merges
#' wb <- wb_merge_cells(wb, 2, cols = 1, rows = 1:10) # Now this works
#'
#' @name ws_cell_merge
#' @family workbook wrappers
NULL
#' @export
#' @rdname ws_cell_merge
wb_merge_cells <- function(wb, sheet = current_sheet(), rows = NULL, cols = NULL) {
assert_workbook(wb)
wb$clone()$merge_cells(sheet = sheet, rows = rows, cols = cols)
}
#' @export
#' @rdname ws_cell_merge
wb_unmerge_cells <- function(wb, sheet = current_sheet(), rows = NULL, cols = NULL) {
assert_workbook(wb)
wb$clone()$unmerge_cells(sheet = sheet, rows = rows, cols = cols)
}
# worksheets --------------------------------------------------------------
#' Add a worksheet to a workbook
#'
#' @param wb A Workbook object to attach the new worksheet
#' @param sheet A name for the new worksheet
#' @param gridLines A logical. If `FALSE`, the worksheet grid lines will be
#' hidden.
#' @param rowColHeaders A logical. If `FALSE`, the worksheet colname and rowname will be
#' hidden.
#' @param tabColour Colour of the worksheet tab. A valid colour (belonging to
#' colours()) or a valid hex colour beginning with "#"
#' @param zoom A numeric between 10 and 400. Worksheet zoom level as a
#' percentage.
#' @param header,oddHeader,evenHeader,firstHeader,footer,oddFooter,evenFooter,firstFooter
#' Character vector of length 3 corresponding to positions left, center,
#' right. `header` and `footer` are used to default additional arguments.
#' Setting `even`, `odd`, or `first`, overrides `header`/`footer`. Use `NA` to
#' skip a position.
#' @param visible If FALSE, sheet is hidden else visible.
#' @param hasDrawing If TRUE prepare a drawing output (TODO does this work?)
#' @param paperSize An integer corresponding to a paper size. See ?ws_page_setup for
#' details.
#' @param orientation One of "portrait" or "landscape"
#' @param hdpi Horizontal DPI. Can be set with options("openxlsx2.dpi" = X) or
#' options("openxlsx2.hdpi" = X)
#' @param vdpi Vertical DPI. Can be set with options("openxlsx2.dpi" = X) or
#' options("openxlsx2.vdpi" = X)
#' @details Headers and footers can contain special tags \itemize{
#' \item{**&\[Page\]**}{ Page number} \item{**&\[Pages\]**}{ Number of pages}
#' \item{**&\[Date\]**}{ Current date} \item{**&\[Time\]**}{ Current time}
#' \item{**&\[Path\]**}{ File path} \item{**&\[File\]**}{ File name}
#' \item{**&\[Tab\]**}{ Worksheet name} }
#' @return The [wbWorkbook] object `wb`
#'
#' @export
#' @family workbook wrappers
#'
#' @examples
#' ## Create a new workbook
#' wb <- wb_workbook("Fred")
#'
#' ## Add 3 worksheets
#' wb$add_worksheet("Sheet 1")
#' wb$add_worksheet("Sheet 2", gridLines = FALSE)
#' wb$add_worksheet("Sheet 3", tabColour = "red")
#' wb$add_worksheet("Sheet 4", gridLines = FALSE, tabColour = "#4F81BD")
#'
#' ## Headers and Footers
#' wb$add_worksheet("Sheet 5",
#' header = c("ODD HEAD LEFT", "ODD HEAD CENTER", "ODD HEAD RIGHT"),
#' footer = c("ODD FOOT RIGHT", "ODD FOOT CENTER", "ODD FOOT RIGHT"),
#' evenHeader = c("EVEN HEAD LEFT", "EVEN HEAD CENTER", "EVEN HEAD RIGHT"),
#' evenFooter = c("EVEN FOOT RIGHT", "EVEN FOOT CENTER", "EVEN FOOT RIGHT"),
#' firstHeader = c("TOP", "OF FIRST", "PAGE"),
#' firstFooter = c("BOTTOM", "OF FIRST", "PAGE")
#' )
#'
#' wb$add_worksheet("Sheet 6",
#' header = c("&[Date]", "ALL HEAD CENTER 2", "&[Page] / &[Pages]"),
#' footer = c("&[Path]&[File]", NA, "&[Tab]"),
#' firstHeader = c(NA, "Center Header of First Page", NA),
#' firstFooter = c(NA, "Center Footer of First Page", NA)
#' )
#'
#' wb$add_worksheet("Sheet 7",
#' header = c("ALL HEAD LEFT 2", "ALL HEAD CENTER 2", "ALL HEAD RIGHT 2"),
#' footer = c("ALL FOOT RIGHT 2", "ALL FOOT CENTER 2", "ALL FOOT RIGHT 2")
#' )
#'
#' wb$add_worksheet("Sheet 8",
#' firstHeader = c("FIRST ONLY L", NA, "FIRST ONLY R"),
#' firstFooter = c("FIRST ONLY L", NA, "FIRST ONLY R")
#' )
#'
#' ## Need data on worksheet to see all headers and footers
#' wb$add_data(sheet = 5, 1:400)
#' wb$add_data(sheet = 6, 1:400)
#' wb$add_data(sheet = 7, 1:400)
#' wb$add_data(sheet = 8, 1:400)
wb_add_worksheet <- function(
wb,
sheet = next_sheet(),
gridLines = TRUE,
rowColHeaders = TRUE,
tabColour = NULL,
zoom = 100,
header = NULL,
footer = NULL,
oddHeader = header,
oddFooter = footer,
evenHeader = header,
evenFooter = footer,
firstHeader = header,
firstFooter = footer,
visible = c("true", "false", "hidden", "visible", "veryhidden"),
hasDrawing = FALSE,
paperSize = 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))
) {
assert_workbook(wb)
wb$clone()$add_worksheet(
sheet = sheet,
gridLines = gridLines,
rowColHeaders = rowColHeaders,
tabColour = tabColour,
zoom = zoom,
oddHeader = headerFooterSub(oddHeader),
oddFooter = headerFooterSub(oddFooter),
evenHeader = headerFooterSub(evenHeader),
evenFooter = headerFooterSub(evenFooter),
firstHeader = headerFooterSub(firstHeader),
firstFooter = headerFooterSub(firstFooter),
visible = visible,
paperSize = paperSize,
orientation = orientation,
vdpi = vdpi,
hdpi = hdpi
)
}
#' Clone a worksheet to a workbook
#'
#' Clone a worksheet to a Workbook object
#'
#' @param wb A [wbWorkbook] object
#' @param old Name of existing worksheet to copy
#' @param new Name of New worksheet to create
#' @return The `wb` object
#'
#' @export
#' @family workbook wrappers
#'
#' @examples
#' # Create a new workbook
#' wb <- wb_workbook("Fred")
#'
#' # Add worksheets
#' wb$add_worksheet("Sheet 1")
#' wb$clone_worksheet("Sheet 1", "Sheet 2")
wb_clone_worksheet <- function(wb, old = current_sheet(), new = next_sheet()) {
assert_workbook(wb)
wb$clone()$clone_worksheet(old = old, new = new)
}
#' @name wb_freeze_pane
#' @title Freeze a worksheet pane
#' @description Freeze a worksheet pane
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param firstActiveRow Top row of active region
#' @param firstActiveCol Furthest left column of active region
#' @param firstRow If `TRUE`, freezes the first row (equivalent to firstActiveRow = 2)
#' @param firstCol If `TRUE`, freezes the first column (equivalent to firstActiveCol = 2)
#'
#' @export
#' @family workbook wrappers
#'
#' @examples
#' ## Create a new workbook
#' wb <- wb_workbook("Kenshin")
#'
#' ## Add some worksheets
#' wb$add_worksheet("Sheet 1")
#' wb$add_worksheet("Sheet 2")
#' wb$add_worksheet("Sheet 3")
#' wb$add_worksheet("Sheet 4")
#'
#' ## Freeze Panes
#' wb$freeze_pane("Sheet 1", firstActiveRow = 5, firstActiveCol = 3)
#' wb$freeze_pane("Sheet 2", firstCol = TRUE) ## shortcut to firstActiveCol = 2
#' wb$freeze_pane(3, firstRow = TRUE) ## shortcut to firstActiveRow = 2
#' wb$freeze_pane(4, firstActiveRow = 1, firstActiveCol = "D")
wb_freeze_pane <- function(wb, sheet = current_sheet(), firstActiveRow = NULL, firstActiveCol = NULL, firstRow = FALSE, firstCol = FALSE) {
assert_workbook(wb)
wb$clone()$freeze_pane(
sheet = sheet,
firstActiveRow = firstActiveRow,
firstActiveCol = firstActiveCol,
firstRow = firstRow,
firstCol = firstCol
)
}
# heights and columns -----------------------------------------------------
# TODO order these...
#' Set worksheet row heights
#'
#' Set worksheet row heights
#'
#' @param wb A [wbWorkbook] object
#' @param sheet A name or index of a worksheet
#' @param rows Indices of rows to set height
#' @param heights Heights to set rows to specified in Excel column height units.
#'
#' @export
#' @family workbook wrappers
#' @seealso [wb_remove_row_heights()]
#'
#' @examples
#' ## Create a new workbook
#' wb <- wb_workbook()
#'
#' ## Add a worksheet
#' wb$add_worksheet("Sheet 1")
#'
#' ## set row heights
#' wb <- wb_set_row_heights(
#' wb, 1,
#' rows = c(1, 4, 22, 2, 19),
#' heights = c(24, 28, 32, 42, 33)
#' )
#'
#' ## overwrite row 1 height
#' wb <- wb_set_row_heights(wb, 1, rows = 1, heights = 40)
wb_set_row_heights <- function(wb, sheet = current_sheet(), rows, heights) {
assert_workbook(wb)
wb$clone()$set_row_heights(sheet = sheet, rows, heights)
}
#' Set worksheet column widths
#'
#' Set worksheet column widths to specific width or "auto".
#'
#' @param wb A [wbWorkbook] object
#' @param sheet A name or index of a worksheet
#' @param cols Indices of cols to set width
#' @param widths width to set cols to specified in Excel column width units or "auto" for automatic sizing. The widths argument is
#' recycled to the length of cols. The default width is 8.43. Though there is no specific default width for Excel, it depends on
#' Excel version, operating system and DPI settings used. Setting it to specific value also is no guarantee that the output will be
#' of the selected width.
#' @param hidden Logical vector. If TRUE the column is hidden.
#' @details The global min and max column width for "auto" columns is set by (default values show):
#' \itemize{
#' \item{options("openxlsx2.minWidth" = 3)}
#' \item{options("openxlsx2.maxWidth" = 250)} ## This is the maximum width allowed in Excel
#' }
#'
#' NOTE: The calculation of column widths can be slow for large worksheets.
#'
#' NOTE: The `hidden` parameter may conflict with the one set in
#' [wb_group_cols]; changing one will update the other.
#'
#' @export
#' @family workbook wrappers
#' @seealso [wb_remove_col_widths()]
#'
#' @examples
#' ## Create a new workbook
#' wb <- wb_workbook()
#'
#' ## Add a worksheet
#' wb$add_worksheet("Sheet 1")
#'
#' ## set col widths
#' wb$set_col_widths(1, cols = c(1, 4, 6, 7, 9), widths = c(16, 15, 12, 18, 33))
#'
#' ## auto columns
#' wb$add_worksheet("Sheet 2")
#' wb$add_data(sheet = 2, x = iris)
#' wb$set_col_widths(sheet = 2, cols = 1:5, widths = "auto")
wb_set_col_widths <- function(wb, sheet = current_sheet(), cols, widths = 8.43, hidden = FALSE) {
assert_workbook(wb)
wb$clone()$set_col_widths(
sheet = sheet,
cols = cols,
widths = widths,
# TODO allow either 1 or length(cols)
hidden = hidden
)
}
#' @name wb_remove_col_widths
#' @title Remove column widths from a worksheet
#' @description Remove column widths from a worksheet
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param cols Indices of columns to remove custom width (if any) from.
#' @seealso [wb_set_col_widths()]
#' @export
#' @examples
#' ## Create a new workbook
#' wb <- wb_load(file = system.file("extdata", "loadExample.xlsx", package = "openxlsx2"))
#'
#' ## remove column widths in columns 1 to 20
#' wb_remove_col_widths(wb, 1, cols = 1:20)
wb_remove_col_widths <- function(wb, sheet = current_sheet(), cols) {
assert_workbook(wb)
wb$clone()$remove_col_widths(sheet = sheet, cols = cols)
}
#' Remove custom row heights from a worksheet
#'
#' Remove row heights from a worksheet
#'
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param rows Indices of rows to remove custom height (if any) from.
#' @seealso [wb_set_row_heights()]
#' @export
#' @examples
#' ## Create a new workbook
#' wb <- wb_load(file = system.file("extdata", "loadExample.xlsx", package = "openxlsx2"))
#'
#' ## remove any custom row heights in rows 1 to 10
#' wb$remove_row_heights(1, rows = 1:10)
wb_remove_row_heights <- function(wb, sheet = current_sheet(), rows) {
assert_workbook(wb)
wb$clone()$remove_row_heights(sheet = sheet, rows = rows)
}
# images ------------------------------------------------------------------
#' Insert the current plot into a worksheet
#'
#' The current plot is saved to a temporary image file using
#' [grDevices::dev.copy()] This file is then written to the workbook using
#' [wb_add_image()].
#'
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param xy Alternate way to specify `startRow` and `startCol.` A vector of
#' length `2` of form (`startcol`, `startRow`)
#' @param startRow Row coordinate of upper left corner of figure. `xy[[2]]` when
#' `xy` is given.
#' @param startCol Column coordinate of upper left corner of figure. `xy[[1]]`
#' when `xy` is given.
#' @param rowOffset offset within cell (row)
#' @param colOffset offset within cell (column)
#' @param width Width of figure. Defaults to `6`in.
#' @param height Height of figure . Defaults to `4`in.
#' @param fileType File type of image
#' @param units Units of width and height. Can be `"in"`, `"cm"` or `"px"`
#' @param dpi Image resolution
#' @seealso [wb_add_image()]
#' @export
#' @examples
#' if (requireNamespace("ggplot2") && interactive()) {
#' ## Create a new workbook
#' wb <- wb_workbook()
#'
#' ## Add a worksheet
#' wb$add_worksheet("Sheet 1", gridLines = FALSE)
#'
#' ## create plot objects
#' require(ggplot2)
#' p1 <- qplot(mpg,
#' data = mtcars, geom = "density",
#' fill = as.factor(gear), alpha = I(.5), main = "Distribution of Gas Mileage"
#' )
#' p2 <- qplot(age, circumference,
#' data = Orange, geom = c("point", "line"), colour = Tree
#' )
#'
#' ## Insert currently displayed plot to sheet 1, row 1, column 1
#' print(p1) # plot needs to be showing
#' wb$add_plot(1, width = 5, height = 3.5, fileType = "png", units = "in")
#'
#' ## Insert plot 2
#' print(p2)
#' wb$add_plot(1, xy = c("J", 2), width = 16, height = 10, fileType = "png", units = "cm")
#'
#' }
wb_add_plot <- function(
wb,
sheet = current_sheet(),
width = 6,
height = 4,
xy = NULL,
startRow = 1,
startCol = 1,
rowOffset = 0,
colOffset = 0,
fileType = "png",
units = "in",
dpi = 300
) {
assert_workbook(wb)
wb$clone()$add_plot(
sheet = sheet,
width = width,
height = height,
xy = xy,
startRow = startRow,
startCol = startCol,
rowOffset = rowOffset,
colOffset = colOffset,
fileType = fileType,
units = units,
dpi = dpi
)
}
#' @title Remove a worksheet from a workbook
#' @description Remove a worksheet from a Workbook object
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @description Remove a worksheet from a workbook
#' @export
#' @examples
#' ## load a workbook
#' wb <- wb_load(file = system.file("extdata", "loadExample.xlsx", package = "openxlsx2"))
#'
#' ## Remove sheet 2
#' wb <- wb_remove_worksheet(wb, 2)
wb_remove_worksheet <- function(wb, sheet = current_sheet()) {
assert_workbook(wb)
wb$clone()$remove_worksheet(sheet = sheet)
}
# base font ---------------------------------------------------------------
#' @name wb_modify_basefont
#' @title Modify the default font
#' @description Modify the default font for this workbook
#' @param wb A workbook object
#' @param fontSize font size
#' @param fontColour font colour
#' @param fontName Name of a font
#' @details The font name is not validated in anyway. Excel replaces unknown font names
#' with Arial. Base font is black, size 11, Calibri.
#' @export
#' @examples
#' ## create a workbook
#' wb <- wb_workbook()
#' wb$add_worksheet("S1")
#' ## modify base font to size 10 Arial Narrow in red
#' wb$set_base_font(fontSize = 10, fontColour = "#FF0000", fontName = "Arial Narrow")
#'
#' wb$add_data("S1", iris)
#' wb$add_data_table("S1", x = iris, startCol = 10) ## font colour does not affect tables
wb_set_base_font <- function(wb, fontSize = 11, fontColour = wb_colour(theme = "1"), fontName = "Calibri") {
assert_workbook(wb)
wb$clone()$set_base_font(
fontSize = fontSize,
fontColour = fontColour,
fontName = fontName
)
}
#' Return the workbook default font
#'
#' Get the base font used in the workbook.
#' @param wb A [wbWorkbook] object
#'
#' @export
#' @family workbook wrappers
#'
#' @examples
#' ## create a workbook
#' wb <- wb_workbook()
#' wb_get_base_font(wb)
#'
#' ## modify base font to size 10 Arial Narrow in red
#' wb$set_base_font(fontSize = 10, fontColour = "#FF0000", fontName = "Arial Narrow")
#'
#' wb_get_base_font(wb)
wb_get_base_font <- function(wb) {
# TODO all of these class checks need to be cleaned up
assert_workbook(wb)
wb$get_base_font()
}
#' Set document headers and footers
#'
#' Set document headers and footers
#'
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param header document header. Character vector of length 3 corresponding to positions left, center, right. Use NA to skip a position.
#' @param footer document footer. Character vector of length 3 corresponding to positions left, center, right. Use NA to skip a position.
#' @param evenHeader document header for even pages.
#' @param evenFooter document footer for even pages.
#' @param firstHeader document header for first page only.
#' @param firstFooter document footer for first page only.
#' @details Headers and footers can contain special tags
#' \itemize{
#' \item{**&\[Page\]**}{ Page number}
#' \item{**&\[Pages\]**}{ Number of pages}
#' \item{**&\[Date\]**}{ Current date}
#' \item{**&\[Time\]**}{ Current time}
#' \item{**&\[Path\]**}{ File path}
#' \item{**&\[File\]**}{ File name}
#' \item{**&\[Tab\]**}{ Worksheet name}
#' }
#' @export
#' @seealso [wb_add_worksheet()] to set headers and footers when adding a worksheet
#' @examples
#' wb <- wb_workbook()
#'
#' wb$add_worksheet("S1")
#' wb$add_worksheet("S2")
#' wb$add_worksheet("S3")
#' wb$add_worksheet("S4")
#'
#' wb$add_data(1, 1:400)
#' wb$add_data(2, 1:400)
#' wb$add_data(3, 3:400)
#' wb$add_data(4, 3:400)
#'
#' wb$set_header_footer(
#' sheet = "S1",
#' header = c("ODD HEAD LEFT", "ODD HEAD CENTER", "ODD HEAD RIGHT"),
#' footer = c("ODD FOOT RIGHT", "ODD FOOT CENTER", "ODD FOOT RIGHT"),
#' evenHeader = c("EVEN HEAD LEFT", "EVEN HEAD CENTER", "EVEN HEAD RIGHT"),
#' evenFooter = c("EVEN FOOT RIGHT", "EVEN FOOT CENTER", "EVEN FOOT RIGHT"),
#' firstHeader = c("TOP", "OF FIRST", "PAGE"),
#' firstFooter = c("BOTTOM", "OF FIRST", "PAGE")
#' )
#'
#' wb$set_header_footer(
#' sheet = 2,
#' header = c("&[Date]", "ALL HEAD CENTER 2", "&[Page] / &[Pages]"),
#' footer = c("&[Path]&[File]", NA, "&[Tab]"),
#' firstHeader = c(NA, "Center Header of First Page", NA),
#' firstFooter = c(NA, "Center Footer of First Page", NA)
#' )
#'
#' wb$set_header_footer(
#' sheet = 3,
#' header = c("ALL HEAD LEFT 2", "ALL HEAD CENTER 2", "ALL HEAD RIGHT 2"),
#' footer = c("ALL FOOT RIGHT 2", "ALL FOOT CENTER 2", "ALL FOOT RIGHT 2")
#' )
#'
#' wb$set_header_footer(
#' sheet = 4,
#' firstHeader = c("FIRST ONLY L", NA, "FIRST ONLY R"),
#' firstFooter = c("FIRST ONLY L", NA, "FIRST ONLY R")
#' )
wb_set_header_footer <- function(
wb,
sheet = current_sheet(),
header = NULL,
footer = NULL,
evenHeader = NULL,
evenFooter = NULL,
firstHeader = NULL,
firstFooter = NULL
) {
assert_workbook(wb)
wb$clone()$set_header_footer(
sheet = sheet,
header = header,
footer = footer,
evenHeader = evenHeader,
evenFooter = evenFooter,
firstHeader = firstHeader,
firstFooter = firstFooter
)
}
#' @name ws_page_setup
#' @title Set page margins, orientation and print scaling
#' @description Set page margins, orientation and print scaling
#' @param wb A workbook object
#' @param sheet A name or index of a worksheet
#' @param orientation Page orientation. One of "portrait" or "landscape"
#' @param scale Print scaling. Numeric value between 10 and 400
#' @param left left page margin in inches
#' @param right right page margin in inches
#' @param top top page margin in inches
#' @param bottom bottom page margin in inches
#' @param header header margin in inches
#' @param footer footer margin in inches
#' @param fitToWidth If `TRUE`, worksheet is scaled to fit to page width on printing.
#' @param fitToHeight If `TRUE`, worksheet is scaled to fit to page height on printing.
#' @param paperSize See details. Default value is 9 (A4 paper).
#' @param printTitleRows Rows to repeat at top of page when printing. Integer vector.
#' @param printTitleCols Columns to repeat at left when printing. Integer vector.
#' @param summaryRow Location of summary rows in groupings. One of "Above" or "Below".
#' @param summaryCol Location of summary columns in groupings. One of "Right" or "Left".
#' @export
#' @details
#' paperSize is an integer corresponding to:
#' \itemize{
#' \item{**1**}{ Letter paper (8.5 in. by 11 in.)}
#' \item{**2**}{ Letter small paper (8.5 in. by 11 in.)}
#' \item{**3**}{ Tabloid paper (11 in. by 17 in.)}
#' \item{**4**}{ Ledger paper (17 in. by 11 in.)}
#' \item{**5**}{ Legal paper (8.5 in. by 14 in.)}
#' \item{**6**}{ Statement paper (5.5 in. by 8.5 in.)}
#' \item{**7**}{ Executive paper (7.25 in. by 10.5 in.)}
#' \item{**8**}{ A3 paper (297 mm by 420 mm)}
#' \item{**9**}{ A4 paper (210 mm by 297 mm)}
#' \item{**10**}{ A4 small paper (210 mm by 297 mm)}
#' \item{**11**}{ A5 paper (148 mm by 210 mm)}
#' \item{**12**}{ B4 paper (250 mm by 353 mm)}
#' \item{**13**}{ B5 paper (176 mm by 250 mm)}
#' \item{**14**}{ Folio paper (8.5 in. by 13 in.)}
#' \item{**15**}{ Quarto paper (215 mm by 275 mm)}
#' \item{**16**}{ Standard paper (10 in. by 14 in.)}
#' \item{**17**}{ Standard paper (11 in. by 17 in.)}
#' \item{**18**}{ Note paper (8.5 in. by 11 in.)}
#' \item{**19**}{ #9 envelope (3.875 in. by 8.875 in.)}
#' \item{**20**}{ #10 envelope (4.125 in. by 9.5 in.)}
#' \item{**21**}{ #11 envelope (4.5 in. by 10.375 in.)}
#' \item{**22**}{ #12 envelope (4.75 in. by 11 in.)}
#' \item{**23**}{ #14 envelope (5 in. by 11.5 in.)}
#' \item{**24**}{ C paper (17 in. by 22 in.)}
#' \item{**25**}{ D paper (22 in. by 34 in.)}
#' \item{**26**}{ E paper (34 in. by 44 in.)}
#' \item{**27**}{ DL envelope (110 mm by 220 mm)}
#' \item{**28**}{ C5 envelope (162 mm by 229 mm)}
#' \item{**29**}{ C3 envelope (324 mm by 458 mm)}
#' \item{**30**}{ C4 envelope (229 mm by 324 mm)}
#' \item{**31**}{ C6 envelope (114 mm by 162 mm)}
#' \item{**32**}{ C65 envelope (114 mm by 229 mm)}
#' \item{**33**}{ B4 envelope (250 mm by 353 mm)}
#' \item{**34**}{ B5 envelope (176 mm by 250 mm)}
#' \item{**35**}{ B6 envelope (176 mm by 125 mm)}
#' \item{**36**}{ Italy envelope (110 mm by 230 mm)}
#' \item{**37**}{ Monarch envelope (3.875 in. by 7.5 in.).}
#' \item{**38**}{ 6 3/4 envelope (3.625 in. by 6.5 in.)}
#' \item{**39**}{ US standard fanfold (14.875 in. by 11 in.)}
#' \item{**40**}{ German standard fanfold (8.5 in. by 12 in.)}
#' \item{**41**}{ German legal fanfold (8.5 in. by 13 in.)}
#' \item{**42**}{ ISO B4 (250 mm by 353 mm)}
#' \item{**43**}{ Japanese double postcard (200 mm by 148 mm)}
#' \item{**44**}{ Standard paper (9 in. by 11 in.)}
#' \item{**45**}{ Standard paper (10 in. by 11 in.)}
#' \item{**46**}{ Standard paper (15 in. by 11 in.)}
#' \item{**47**}{ Invite envelope (220 mm by 220 mm)}
#' \item{**50**}{ Letter extra paper (9.275 in. by 12 in.)}
#' \item{**51**}{ Legal extra paper (9.275 in. by 15 in.)}
#' \item{**52**}{ Tabloid extra paper (11.69 in. by 18 in.)}
#' \item{**53**}{ A4 extra paper (236 mm by 322 mm)}
#' \item{**54**}{ Letter transverse paper (8.275 in. by 11 in.)}
#' \item{**55**}{ A4 transverse paper (210 mm by 297 mm)}
#' \item{**56**}{ Letter extra transverse paper (9.275 in. by 12 in.)}
#' \item{**57**}{ SuperA/SuperA/A4 paper (227 mm by 356 mm)}
#' \item{**58**}{ SuperB/SuperB/A3 paper (305 mm by 487 mm)}
#' \item{**59**}{ Letter plus paper (8.5 in. by 12.69 in.)}
#' \item{**60**}{ A4 plus paper (210 mm by 330 mm)}
#' \item{**61**}{ A5 transverse paper (148 mm by 210 mm)}
#' \item{**62**}{ JIS B5 transverse paper (182 mm by 257 mm)}
#' \item{**63**}{ A3 extra paper (322 mm by 445 mm)}
#' \item{**64**}{ A5 extra paper (174 mm by 235 mm)}
#' \item{**65**}{ ISO B5 extra paper (201 mm by 276 mm)}