-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathwrite.R
1431 lines (1200 loc) · 44.2 KB
/
write.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
#' function to add missing cells to cc and rows
#'
#' Create a cell in the workbook
#'
#' @param wb the workbook update
#' @param sheet_id the sheet to update
#' @param x the newly filled cc frame
#' @param rows the rows needed
#' @param cells_needed the cells needed
#' @param colNames has colNames (only in update_cell)
#' @param removeCellStyle remove the cell style (only in update_cell)
#' @param na.strings Value used for replacing `NA` values from `x`. Default
#' `na_strings()` uses the special `#N/A` value within the workbook.
#' @keywords internal
#' @noRd
inner_update <- function(
wb,
sheet_id,
x,
rows,
cells_needed,
colNames = FALSE,
removeCellStyle = FALSE,
na.strings = na_strings()
) {
cells_needed <- cells_needed[cells_needed != ""]
if (length(cells_needed) == 0) return(wb)
# 1) pull sheet to modify from workbook; 2) modify it; 3) push it back
cc <- wb$worksheets[[sheet_id]]$sheet_data$cc
row_attr <- wb$worksheets[[sheet_id]]$sheet_data$row_attr
# workbooks contain only entries for values currently present.
# if A1 is filled, B1 is not filled and C1 is filled the sheet will only
# contain fields A1 and C1.
cells_in_wb <- cc$r
rows_in_wb <- row_attr$r
# check if there are rows not available
if (!all(rows %in% rows_in_wb)) {
# message("row(s) not in workbook")
missing_rows <- rows[!rows %in% rows_in_wb]
# new row_attr
row_attr_missing <- empty_row_attr(n = length(missing_rows))
row_attr_missing$r <- missing_rows
row_attr <- rbind(row_attr, row_attr_missing)
# order
row_attr <- row_attr[order(as.numeric(row_attr$r)), ]
wb$worksheets[[sheet_id]]$sheet_data$row_attr <- row_attr
# provide output
rows_in_wb <- row_attr$r
}
if (!all(cells_needed %in% cells_in_wb)) {
# message("cell(s) not in workbook")
missing_cells <- cells_needed[!cells_needed %in% cells_in_wb]
# create missing cells
cc_missing <- create_char_dataframe(names(cc), length(missing_cells))
cc_missing$r <- missing_cells
cc_missing$row_r <- gsub("[[:upper:]]", "", cc_missing$r)
cc_missing$c_r <- gsub("[[:digit:]]", "", cc_missing$r)
# assign to cc
cc <- rbind(cc, cc_missing)
# order cc (not really necessary, will be done when saving)
cc <- cc[order(as.integer(cc[, "row_r"]), col2int(cc[, "c_r"])), ]
# update dimensions (only required if new cols and rows are added) ------
all_rows <- as.numeric(unique(cc$row_r))
all_cols <- col2int(unique(cc$c_r))
min_cell <- trimws(paste0(int2col(min(all_cols, na.rm = TRUE)), min(all_rows, na.rm = TRUE)))
max_cell <- trimws(paste0(int2col(max(all_cols, na.rm = TRUE)), max(all_rows, na.rm = TRUE)))
# i know, i know, i'm lazy
wb$worksheets[[sheet_id]]$dimension <- paste0("<dimension ref=\"", min_cell, ":", max_cell, "\"/>")
}
if (is_na_strings(na.strings)) {
na.strings <- NULL
}
if (removeCellStyle) {
cell_style <- "c_s"
} else {
cell_style <- NULL
}
replacement <- c("r", cell_style, "c_t", "c_cm", "c_ph", "c_vm", "v",
"f", "f_t", "f_ref", "f_ca", "f_si", "is", "typ")
sel <- match(x$r, cc$r)
# to avoid bricking the worksheet, we make sure that we do not overwrite the
# reference cell of a shared formula. To be on the save side, we replace all
# values with the formula. If the entire cc is replaced with x, we can skip.
if (length(sf <- cc$f_si[sel & cc$f_t[sel] == "shared" & cc$f_ref[sel] != ""]) && !all(cc$r %in% x$r)) {
# collect all the shared formulas that we have to convert
sel_fsi <- cc$f_si %in% unique(sf)
cc_shared <- cc[sel_fsi, , drop = FALSE]
cc <- shared_as_fml(cc, cc_shared)
msg <- paste0(
"A shared formula reference cell was overwritten. To protect the",
" spreadsheet formulas, the impacted cells were converted from shared",
" formulas to normal formulas."
)
warning(msg, call. = FALSE)
}
cc[sel, replacement] <- x[replacement]
# avoid missings in cc
if (anyNA(cc))
cc[is.na(cc)] <- ""
# push everything back to workbook
wb$worksheets[[sheet_id]]$sheet_data$cc <- cc
wb
}
#' Initialize data cell(s)
#'
#' Create a cell in the workbook
#'
#' @param wb the workbook you want to update
#' @param sheet the sheet you want to update
#' @param new_cells the cell you want to update in Excel connotation e.g. "A1"
#'
#' @keywords internal
#' @noRd
initialize_cell <- function(wb, sheet, new_cells) {
sheet_id <- wb$validate_sheet(sheet)
# create artificial cc for the missing cells
x <- empty_sheet_data_cc(n = length(new_cells))
x$r <- new_cells
x$row_r <- gsub("[[:upper:]]", "", new_cells)
x$c_r <- gsub("[[:digit:]]", "", new_cells)
rows <- x$row_r
cells_needed <- new_cells
inner_update(wb, sheet_id, x, rows, cells_needed)
}
#' Replace data cell(s)
#'
#' Minimal invasive update of cell(s) inside of imported workbooks.
#'
#' @param x cc dataframe of the updated cells
#' @param wb the workbook you want to update
#' @param sheet the sheet you want to update
#' @param cell the cell you want to update in Excel connotation e.g. "A1"
#' @param colNames if TRUE colNames are passed down
#' @param removeCellStyle keep the cell style?
#' @param na.strings optional na.strings argument. if missing #N/A is used. If NULL no cell value is written, if character or numeric this is written (even if NA is part of numeric data)
#'
#' @keywords internal
#' @noRd
update_cell <- function(x, wb, sheet, cell, colNames = FALSE,
removeCellStyle = FALSE, na.strings) {
if (missing(na.strings))
na.strings <- substitute()
sheet_id <- wb$validate_sheet(sheet)
dims <- dims_to_dataframe(cell, fill = TRUE)
rows <- rownames(dims)
cells_needed <- unname(unlist(dims))
inner_update(wb, sheet_id, x, rows, cells_needed, colNames, removeCellStyle, na.strings)
}
#' dummy function to write data
#' @param wb workbook
#' @param sheet sheet
#' @param data data to export
#' @param name If not NULL, a named region is defined.
#' @param colNames include colnames?
#' @param rowNames include rownames?
#' @param startRow row to place it
#' @param startCol col to place it
#' @param applyCellStyle apply styles when writing on the sheet
#' @param removeCellStyle keep the cell style?
#' @param na.strings Value used for replacing `NA` values from `x`. Default
#' looks if `options(openxlsx2.na.strings)` is set. Otherwise [na_strings()]
#' uses the special `#N/A` value within the workbook.
#' @param data_table logical. if `TRUE` and `rowNames = TRUE`, do not write the cell containing `"_rowNames_"`
#' @param inline_strings write characters as inline strings
#' @param dims worksheet dimensions
#' @param enforce enforce dims
#' @param shared shared formula
#' @param sep the separator string used in collapse
#' @details
#' The string `"_openxlsx_NA"` is reserved for `openxlsx2`. If the data frame
#' contains this string, the output will be broken.
#'
#' @examples
#' # create a workbook and add some sheets
#' wb <- wb_workbook()
#'
#' wb$add_worksheet("sheet1")
#' write_data2(wb, "sheet1", mtcars, colNames = TRUE, rowNames = TRUE)
#'
#' wb$add_worksheet("sheet2")
#' write_data2(wb, "sheet2", cars, colNames = FALSE)
#'
#' wb$add_worksheet("sheet3")
#' write_data2(wb, "sheet3", letters)
#'
#' wb$add_worksheet("sheet4")
#' write_data2(wb, "sheet4", as.data.frame(Titanic), startRow = 2, startCol = 2)
#' @noRd
write_data2 <- function(
wb,
sheet,
data,
name = NULL,
colNames = TRUE,
rowNames = FALSE,
startRow = 1,
startCol = 1,
applyCellStyle = TRUE,
removeCellStyle = FALSE,
na.strings = na_strings(),
data_table = FALSE,
inline_strings = TRUE,
dims = NULL,
enforce = FALSE,
shared = FALSE,
sep = ", "
) {
dim_sep <- ";"
if (any(grepl(";|,", dims))) {
if (any(grepl(";", dims))) dim_sep <- ";"
if (any(grepl(",", dims))) dim_sep <- ","
}
is_data_frame <- FALSE
#### prepare the correct data formats for openxml
dc <- openxlsx2_type(data)
# convert factor to character
is_factor <- dc == openxlsx2_celltype[["factor"]]
if (any(is_factor)) {
fcts <- names(dc[is_factor])
data[fcts] <- lapply(data[fcts], to_string)
}
# convert list to character
is_list <- dc == openxlsx2_celltype[["list"]]
if (any(is_list)) {
lsts <- names(dc[is_list])
data[lsts] <- lapply(data[lsts], function(col) {
vapply(col, FUN = stringi::stri_join, collapse = sep, FUN.VALUE = NA_character_)
})
dc[is_list] <- openxlsx2_celltype[["character"]]
}
# remove xml encoding and reapply it afterwards. until v0.3 encoding was not enforced.
# until 1.1 formula encoding was applied in write_formula() and missed formulas written
# as data frames with class formula
is_fml <- dc %in% c(
openxlsx2_celltype[["formula"]], openxlsx2_celltype[["array_formula"]],
openxlsx2_celltype[["cm_formula"]], openxlsx2_celltype[["hyperlink"]]
)
if (any(is_fml)) {
fmls <- names(dc[is_fml])
data[fmls] <- lapply(
data[fmls],
function(val) {
val <- replaceXMLEntities(val)
vapply(val, function(x) xml_value(xml_node_create("fml", x, escapes = TRUE), "fml"), "")
}
)
}
hconvert_date1904 <- grepl('date1904="1"|date1904="true"',
stringi::stri_join(unlist(wb$workbook), collapse = ""),
ignore.case = TRUE)
# TODO need to tell excel that we have a date, apply some kind of numFmt
data <- convert_to_excel_date(df = data, date1904 = hconvert_date1904)
# backward compatible
if (!inherits(data, "data.frame") || inherits(data, "matrix")) {
data <- as.data.frame(data, stringsAsFactors = FALSE)
colNames <- FALSE
}
if (inherits(data, "data.frame") || inherits(data, "matrix")) {
is_data_frame <- TRUE
if (is.data.frame(data)) data <- as.data.frame(data, stringsAsFactors = FALSE)
sel <- !dc %in% c(4, 5, 10)
data[sel] <- lapply(data[sel], as.character)
# add rownames
if (rowNames) {
data <- cbind("_rowNames_" = rownames(data), data, stringsAsFactors = FALSE)
dc <- c(c("_rowNames_" = openxlsx2_celltype[["character"]]), dc)
}
if (nrow(data) == 0) applyCellStyle <- FALSE
# add colnames
if (colNames) {
# its quicker to convert data to character and append the colnames
# then to create a data frame from colnames, construct the required
# length and copy the converted to character data into it.
# data <- rbind(data, colnames(data))
# out <- c(nrow(data), seq_len(nrow(data))[-nrow(data)])
# data <- data[out, , drop = FALSE]
# this is painfully slow, but still somehow the fastest way.
data[nrow(data) + 1L, ] <- colnames(data)
data <- data[c(nrow(data), seq_len(nrow(data) - 1L)), , drop = FALSE]
}
}
sheetno <- wb_validate_sheet(wb, sheet)
# message("sheet no: ", sheetno)
# create a data frame
if (!is_data_frame) {
data <- as.data.frame(t(data), stringsAsFactors = FALSE)
}
# TODO fits_in_dims does not handle "A1,B2" and instead converts it to the
# outer range "A1:B2"
if (!enforce) {
dims <- fits_in_dims(x = data, dims = dims, startCol = startCol, startRow = startRow)
}
if (!is.null(attr(data, "f_ref"))) {
ref <- attr(data, "f_ref")
} else {
ref <- NULL
}
if (!is.null(attr(data, "c_cm"))) {
warning("modifications with cm formulas are experimental. use at own risk")
c_cm <- attr(data, "c_cm")
} else {
c_cm <- ""
}
# TODO writing defined name should handle global and local: localSheetId
# this requires access to wb$workbook.
# TODO The check for existing names is in write_data()
# TODO use wb$add_named_region()
if (!is.null(name) && !any(grepl(dim_sep, dims))) {
## named region
ex_names <- regmatches(wb$workbook$definedNames, regexpr('(?<=name=")[^"]+', wb$workbook$definedNames, perl = TRUE))
ex_names <- replaceXMLEntities(ex_names)
if (name %in% ex_names) {
stop(sprintf("Named region with name '%s' already exists!", name))
} else if (grepl("^[A-Z]{1,3}[0-9]+$", name)) {
stop("name cannot look like a cell reference.")
}
sheet_name <- wb$get_sheet_names(escape = TRUE)[[sheetno]]
if (grepl("[^A-Za-z0-9]", sheet_name)) sheet_name <- shQuote(sheet_name, "sh")
sheet_dim <- paste0(sheet_name, "!", dims)
def_name <- xml_node_create("definedName",
xml_children = sheet_dim,
xml_attributes = c(name = name))
wb$workbook$definedNames <- c(wb$workbook$definedNames, def_name)
}
# from here on only wb$worksheets is required
# rtyp character vector per row
# list(c("A1, ..., "k1"), ..., c("An", ..., "kn"))
rtyp <- dims_to_dataframe(dims, fill = enforce)
rows_attr <- vector("list", nrow(rtyp))
# create <rows ...>
want_rows <- as.integer(dims_to_rowcol(dims)[[2]])
rows_attr <- empty_row_attr(n = length(want_rows))
# number of rows might differ
if (enforce) rows_attr <- empty_row_attr(n = nrow(rtyp))
rows_attr$r <- rownames(rtyp)
# original cc data frame
cc <- empty_sheet_data_cc(n = nrow(data) * ncol(data))
sel <- which(dc == openxlsx2_celltype[["logical"]])
for (i in sel) {
if (colNames) {
data[-1, i] <- as.integer(as.logical(data[-1, i]))
} else {
data[, i] <- as.integer(as.logical(data[, i]))
}
}
sel <- which(dc == openxlsx2_celltype[["character"]] | dc == openxlsx2_celltype[["factor"]]) # character
if (length(sel)) {
data[sel][is.na(data[sel])] <- "_openxlsx_NA"
if (getOption("openxlsx2.force_utf8_encoding", default = FALSE)) {
from_enc <- getOption("openxlsx2.native_encoding")
data[sel] <- lapply(data[sel], stringi::stri_encode, from = from_enc, to = "UTF-8")
}
}
string_nums <- getOption("openxlsx2.string_nums", default = 0)
na_missing <- FALSE
na_null <- FALSE
if (is_na_strings(na.strings)) {
na.strings <- ""
na_missing <- TRUE
} else if (is.null(na.strings)) {
na.strings <- ""
na_null <- TRUE
}
if (enforce) {
clls <- lapply(unlist(strsplit(dims, dim_sep)), FUN = function(x) {
nc <- needed_cells(x)
len <- length(unique(col2int(nc)))
if (length(nc) > 1) {
matrix(nc, ncol = len, byrow = FALSE)
} else {
nc
}
})
clls <- do.call("rbind", clls)
clls <- c(clls)
} else {
clls <- paste0(colnames(rtyp[1, 1]), rownames(rtyp[1, 1]))
}
wide_to_long(
data,
dc,
cc,
ColNames = colNames,
start_col = startCol,
start_row = startRow,
refed = ref,
string_nums = string_nums,
na_null = na_null,
na_missing = na_missing,
na_strings = na.strings,
inline_strings = inline_strings,
c_cm = c_cm,
dims = clls
)
if (enforce) {
# this is required for the worksheet dimension spanning the entire
# initialized worksheet from top left to bottom right
dims <- dataframe_to_dims(rtyp, dim_break = FALSE)
}
# if rownames = TRUE and data_table = FALSE, remove "_rownames_"
if (!data_table && rowNames && colNames) {
cc <- cc[cc$r != paste0(names(rtyp)[1], rownames(rtyp)[1]), ]
}
if (shared) {
# This cc contains only the formula range.
## the top left cell is the reference
## all have shared and all share the same f_si
## only the reference cell has a formula
## only the reference cell has the formula reference
uni_si <- unique(wb$worksheets[[sheetno]]$sheet_data$cc$f_si)
int_si <- as.integer(
replace(
uni_si,
uni_si == "",
"-1"
)
)
cc$f_t <- "shared"
cc[1, "f_ref"] <- dims
cc[2:nrow(cc), "f"] <- ""
cc$f_si <- max(int_si, -1L) + 1L
}
if (is.null(wb$worksheets[[sheetno]]$sheet_data$cc)) {
wb$worksheets[[sheetno]]$dimension <- paste0("<dimension ref=\"", dims, "\"/>")
wb$worksheets[[sheetno]]$sheet_data$row_attr <- rows_attr
wb$worksheets[[sheetno]]$sheet_data$cc <- cc
} else {
# update cell(s)
# message("update_cell()")
wb <- update_cell(
x = cc,
wb = wb,
sheet = sheetno,
cell = dims,
colNames = colNames,
removeCellStyle = removeCellStyle,
na.strings = na.strings
)
}
### Begin styles
if (applyCellStyle) {
## create a cell style format for specific types at the end of the existing
# styles. gets the reference an passes it on.
get_data_class_dims <- function(data_class) {
sel <- dc == openxlsx2_celltype[[data_class]]
# sel = TRUE
sel_cols <- names(rtyp[sel])
sel_rows <- rownames(rtyp)
# ignore first row if colNames
if (colNames) sel_rows <- sel_rows[-1]
dataframe_to_dims(rtyp[rownames(rtyp) %in% sel_rows, sel_cols, drop = FALSE])
}
# if hyperlinks are found, Excel sets something like the following font
# blue with underline
if (any(dc == openxlsx2_celltype[["hyperlink"]])) {
dim_sel <- get_data_class_dims("hyperlink")
# message("hyperlink: ", dim_sel)
# get hyperlink color from template
if (is.null(wb$theme)) {
has_hlink <- 11
} else {
clrs <- xml_node(wb$theme, "a:theme", "a:themeElements", "a:clrScheme")
has_hlink <- which(xml_node_name(clrs, "a:clrScheme") == "a:hlink")
}
if (has_hlink) {
hyperlink_col <- wb_color(theme = has_hlink - 1L)
} else {
hyperlink_col <- wb_color(hex = "FF0000FF")
}
wb$add_font(
sheet = sheetno,
dims = dim_sel,
color = hyperlink_col,
name = wb$get_base_font()$name$val,
size = wb$get_base_font()$size$val,
underline = "single"
)
}
if (any(dc == openxlsx2_celltype[["character"]])) {
if (any(sel <- cc$typ == openxlsx2_celltype[["string_nums"]])) {
# # we cannot select every cell like this, because it is terribly slow.
# dim_sel <- paste0(cc$r[sel], collapse = ";")
dim_sel <- get_data_class_dims("character")
# message("character: ", dim_sel)
wb$add_cell_style(
sheet = sheetno,
dims = dim_sel,
applyNumberFormat = "1",
quotePrefix = "1",
numFmtId = "49"
)
}
}
# options("openxlsx2.numFmt" = NULL)
if (any(dc == openxlsx2_celltype[["numeric"]])) { # numeric or integer
if (!is.null(getOption("openxlsx2.numFmt"))) {
numfmt_numeric <- getOption("openxlsx2.numFmt")
dim_sel <- get_data_class_dims("numeric")
# message("numeric: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_numeric
)
}
}
if (any(dc == openxlsx2_celltype[["short_date"]])) { # Date
numfmt_dt <- getOption("openxlsx2.dateFormat", 14)
dim_sel <- get_data_class_dims("short_date")
# message("short_date: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_dt
)
}
if (any(dc == openxlsx2_celltype[["long_date"]])) {
numfmt_posix <- getOption("openxlsx2.datetimeFormat", default = 22)
dim_sel <- get_data_class_dims("long_date")
# message("long_date: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_posix
)
}
if (any(dc == openxlsx2_celltype[["hms_time"]])) {
numfmt_hms <- getOption("openxlsx2.hmsFormat", default = 21)
dim_sel <- get_data_class_dims("hms_time")
# message("hms: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_hms
)
}
if (any(dc == openxlsx2_celltype[["currency"]])) { # currency
numfmt_currency <- getOption("openxlsx2.currencyFormat", default = 44)
## For vignette: Builtin style for USD
#"_-[$$-409]* #,##0.00_ ;_-[$$-409]* \\-#,##0.00\\ ;_-[$$-409]* "-"??_ ;_-@_ "
dim_sel <- get_data_class_dims("currency")
# message("currency: ", dim_sel)
wb$add_numfmt(
dims = dim_sel,
numfmt = numfmt_currency
)
}
if (any(dc == openxlsx2_celltype[["accounting"]])) { # accounting
numfmt_accounting <- getOption("openxlsx2.accountingFormat", default = 4)
dim_sel <- get_data_class_dims("accounting")
# message("accounting: ", dim_sel)
wb$add_numfmt(
dims = dim_sel,
numfmt = numfmt_accounting
)
}
if (any(dc == openxlsx2_celltype[["percentage"]])) { # percentage
numfmt_percentage <- getOption("openxlsx2.percentageFormat", default = 10)
dim_sel <- get_data_class_dims("percentage")
# message("percentage: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_percentage
)
}
if (any(dc == openxlsx2_celltype[["scientific"]])) {
numfmt_scientific <- getOption("openxlsx2.scientificFormat", default = 48)
dim_sel <- get_data_class_dims("scientific")
# message("scientific: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_scientific
)
}
if (any(dc == openxlsx2_celltype[["comma"]])) {
numfmt_comma <- getOption("openxlsx2.commaFormat", default = 3)
dim_sel <- get_data_class_dims("comma")
# message("comma: ", dim_sel)
wb$add_numfmt(
sheet = sheetno,
dims = dim_sel,
numfmt = numfmt_comma
)
}
}
### End styles
# update shared strings if we use shared strings
if (!inline_strings) {
cc <- wb$worksheets[[sheetno]]$sheet_data$cc
sel <- grepl("<si>", cc$v)
cc_sst <- stringi::stri_unique(cc[sel, "v"])
wb$sharedStrings <- stringi::stri_unique(c(wb$sharedStrings, cc_sst))
sel <- grepl("<si>", cc$v)
cc$v[sel] <- as.character(match(cc$v[sel], wb$sharedStrings) - 1L)
text <- si_to_txt(wb$sharedStrings)
uniqueCount <- length(wb$sharedStrings)
attr(wb$sharedStrings, "uniqueCount") <- uniqueCount
attr(wb$sharedStrings, "text") <- text
wb$worksheets[[sheetno]]$sheet_data$cc <- cc
if (!any(grepl("sharedStrings", wb$workbook.xml.rels))) {
wb$append(
"workbook.xml.rels",
"<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings\" Target=\"sharedStrings.xml\"/>"
)
}
}
### Update calcChain
if (length(wb$calcChain)) {
# if we overwrite a formula cell in the calculation chain, we have to update it
# At the moment we simply remove it from the calculation chain, in the future
# we might want to keep it if we write a formula.
xml <- wb$calcChain
calcChainR <- rbindlist(xml_attr(xml, "calcChain", "c"))
# according to the documentation there can be cases, without the sheetno reference
sel <- calcChainR$r %in% wb$worksheets[[sheetno]]$sheet_data$cc$r & calcChainR$i == sheetno
rmCalcChain <- as.integer(rownames(calcChainR[sel, , drop = FALSE]))
if (length(rmCalcChain)) {
xml <- xml_rm_child(xml, xml_child = "c", which = rmCalcChain)
# xml can not be empty, otherwise excel will complain. If xml is empty, remove all
# calcChain references from the workbook
if (length(xml_node_name(xml, "calcChain")) == 0) {
wb$Content_Types <- wb$Content_Types[-grep("/xl/calcChain", wb$Content_Types)]
wb$workbook.xml.rels <- wb$workbook.xml.rels[-grep("calcChain.xml", wb$workbook.xml.rels)]
wb$worksheets[[sheetno]]$sheetCalcPr <- character()
xml <- character()
}
wb$calcChain <- xml
}
}
### End update calcChain
return(wb)
}
# `write_data_table()` ---------------------------------------------------------
# `write_data_table()` an internal driver function to `write_data` and `write_data_table` ----
#' Write to a worksheet as an Excel table
#'
#' Write 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 data frame.
#' @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 array A bool if the function written is of type array
#' @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).
#' @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 color banded
#' @param bandedCols logical. If TRUE, the columns are color banded
#' @param bandedCols logical. If TRUE, a data table is created
#' @param name If not NULL, a named region is defined.
#' @param applyCellStyle apply styles when writing on the sheet
#' @param removeCellStyle if writing into existing cells, should the cell style be removed?
#' @param na.strings Value used for replacing `NA` values from `x`. Default
#' looks if `options(openxlsx2.na.strings)` is set. Otherwise [na_strings()]
#' uses the special `#N/A` value within the workbook.
#' @param inline_strings optional write strings as inline strings
#' @param total_row optional write total rows
#' @param shared shared formula
#' @noRd
#' @keywords internal
write_data_table <- function(
wb,
sheet,
x,
startCol = 1,
startRow = 1,
dims,
array = FALSE,
colNames = TRUE,
rowNames = FALSE,
tableStyle = "TableStyleLight9",
tableName = NULL,
withFilter = TRUE,
sep = ", ",
firstColumn = FALSE,
lastColumn = FALSE,
bandedRows = TRUE,
bandedCols = FALSE,
name = NULL,
applyCellStyle = TRUE,
removeCellStyle = FALSE,
data_table = FALSE,
na.strings = na_strings(),
inline_strings = TRUE,
total_row = FALSE,
enforce = FALSE,
shared = FALSE
) {
## Input validating
assert_workbook(wb)
assert_class(colNames, "logical")
assert_class(rowNames, "logical")
assert_class(withFilter, "logical")
if (data_table) assert_class(x, "data.frame")
assert_class(firstColumn, "logical")
assert_class(lastColumn, "logical")
assert_class(bandedRows, "logical")
assert_class(bandedCols, "logical")
# force with globalenv() options
x <- force(x)
op <- default_save_opt()
on.exit(options(op), add = TRUE)
odims <- dims
if (!is.null(dims)) {
dims <- dims_to_rowcol(dims, as_integer = TRUE)
# if dims = "K1,A1" startCol = "A" and startRow = "1" are selected
startCol <- min(dims[[1]])
startRow <- min(dims[[2]])
}
# avoid stoi error with NULL
if (is.null(x)) {
return(wb)
}
# overwrite na.strings if nothing was provided
# with whatever is in the option if not set to default
if (is_na_strings(na.strings) && !is.null(getOption("openxlsx2.na.strings"))) {
na.strings <- getOption("openxlsx2.na.strings")
}
if (data_table) {
if (nrow(x) < 1) {
warning("Found data table with zero rows, adding one.",
" Modify na with na.strings")
x[1, ] <- NA
}
if (any(duplicated(tolower(colnames(x))))) {
warning("tables cannot have duplicated column names")
colnames(x) <- fix_pt_names(colnames(x))
}
}
## common part ---------------------------------------------------------------
if ((!is.character(sep)) || (length(sep) != 1))
stop("sep must be a character vector of length 1")
# TODO clean up when moved into wbWorkbook
sheet <- wb$.__enclos_env__$private$get_sheet_index(sheet)
# sheet <- wb$validate_sheet(sheet)
if (wb$is_chartsheet[[sheet]]) stop("Cannot write to chart sheet.")
## convert startRow and startCol
if (!is.numeric(startCol)) {
startCol <- col2int(startCol)
}
startRow <- as.integer(startRow)
## special case - vector of hyperlinks
# TODO: replace the =HYPERLINK() with the relship hyperlinks
is_hyperlink <- FALSE
if (applyCellStyle) {
if (is.null(dim(x))) {
is_hyperlink <- inherits(x, "hyperlink")
} else if (is.data.frame(x)) { # dont check on a matrix
is_hyperlink <- vapply(x, inherits, what = "hyperlink", FALSE)
}
if (any(is_hyperlink)) {
# consider wbHyperlink?
# hlinkNames <- names(x)
if (is.null(dim(x))) {
colNames <- FALSE
if (!any(grepl("=([\\s]*?)HYPERLINK\\(", x[is_hyperlink], perl = TRUE))) {
x[is_hyperlink] <- create_hyperlink(text = x[is_hyperlink])
}
class(x[is_hyperlink]) <- c("character", "hyperlink")
} else {
# workaround for tibbles that break with the class assignment below
if (inherits(x, "tbl_df")) x <- as.data.frame(x, stringsAsFactors = FALSE)
# check should be in create_hyperlink and that apply should not be required either
if (!any(grepl("=([\\s]*?)HYPERLINK\\(", x[is_hyperlink], perl = TRUE))) {
x[is_hyperlink] <- apply(
x[is_hyperlink], 1,
FUN = function(str) create_hyperlink(text = str)
)
}
class(x[, is_hyperlink]) <- c("character", "hyperlink")
}
}
}
### Create data frame --------------------------------------------------------
transpose <- FALSE
# do not transpose if input is a matrix or a data frame. assuming that such input
# is already transposed as required.
if (length(dims[[1]]) > length(dims[[2]]) &&
!inherits(x, "matrix") && !inherits(x, "data.frame"))
transpose <- TRUE
## special case - formula
# only for data frame case where a data frame is passed down containing formulas
if (inherits(x, "formula")) {
x <- data.frame("X" = x, stringsAsFactors = FALSE)
class(x[[1]]) <- if (array) "array_formula" else "formula"
colNames <- FALSE
if (transpose) x <- transpose_df(x)
}
if (is.vector(x) || is.factor(x) || inherits(x, "Date") || inherits(x, "POSIXt")) {
colNames <- FALSE
} ## this will go to coerce.default and rowNames will be ignored
## Coerce to data.frame
if (inherits(x, "hyperlink")) {
## vector of hyperlinks
class(x) <- c("character", "hyperlink")
x <- as.data.frame(x, stringsAsFactors = FALSE)
if (transpose) x <- transpose_df(x)
# colNames <- FALSE
} else if (!inherits(x, "data.frame")) {
x <- as.data.frame(x, stringsAsFactors = FALSE)
if (transpose) x <- transpose_df(x)
# colNames <- FALSE
}
nCol <- ncol(x)
nRow <- nrow(x)
### Beg: Only in data --------------------------------------------------------
if (!data_table) {
## write autoFilter, can only have a single filter per worksheet
if (withFilter) { # TODO: replace ref calculation with wb_dims()
coords <- data.frame("x" = c(startRow, startRow + nRow + colNames - 1L), "y" = c(startCol, startCol + nCol - 1L), stringsAsFactors = FALSE)
ref <- stringi::stri_join(get_cell_refs(coords), collapse = ":")
wb$worksheets[[sheet]]$autoFilter <- sprintf('<autoFilter ref="%s"/>', ref)