Title: | Read, Write and Edit 'xlsx' Files |
---|---|
Description: | Simplifies the creation of 'xlsx' files by providing a high level interface to writing, styling and editing worksheets. |
Authors: | Jordan Mark Barbone [aut] , Jan Marvin Garbuszus [aut, cre], Olivier Roy [ctb], openxlsx authors [cph] (openxlsx package), Arseny Kapoulkine [ctb, cph] (Author of included pugixml code) |
Maintainer: | Jan Marvin Garbuszus <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.11.0.9000 |
Built: | 2024-11-25 20:24:30 UTC |
Source: | https://github.com/JanMarvin/openxlsx2 |
Get and set table of sheets and their state as selected and active in a workbook
Multiple sheets can be selected, but only a single one can be active (visible). The visible sheet, must not necessarily be a selected sheet.
wb_get_active_sheet(wb) wb_set_active_sheet(wb, sheet) wb_get_selected(wb) wb_set_selected(wb, sheet)
wb_get_active_sheet(wb) wb_set_active_sheet(wb, sheet) wb_get_selected(wb) wb_set_selected(wb, sheet)
wb |
a workbook |
sheet |
a sheet name of the workbook |
a data frame with tabSelected and names
wb <- wb_load(file = system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")) # testing is the selected sheet wb_get_selected(wb) # change the selected sheet to Sheet2 wb <- wb_set_selected(wb, "Sheet2") # get the active sheet wb_get_active_sheet(wb) # change the selected sheet to Sheet2 wb <- wb_set_active_sheet(wb, sheet = "Sheet2")
wb <- wb_load(file = system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")) # testing is the selected sheet wb_get_selected(wb) # change the selected sheet to Sheet2 wb <- wb_set_selected(wb, "Sheet2") # get the active sheet wb_get_active_sheet(wb) # change the selected sheet to Sheet2 wb <- wb_set_active_sheet(wb, sheet = "Sheet2")
loads character string to pugixml and returns an externalptr
as_xml(x, ...)
as_xml(x, ...)
x |
input as xml |
... |
additional arguments passed to |
might be useful for larger documents where single nodes are shortened and otherwise the full tree has to be reimported. unsure where we have such a case. is useful, for printing nodes from a larger tree, that have been exported as characters (at some point in time we have to convert the xml to R)
tmp_xlsx <- tempfile() xlsxFile <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") unzip(xlsxFile, exdir = tmp_xlsx) wb <- wb_load(xlsxFile) styles_xml <- sprintf("%s/xl/styles.xml", tmp_xlsx) # is external pointer sxml <- read_xml(styles_xml) # is character font <- xml_node(sxml, "styleSheet", "fonts", "font") # is again external pointer as_xml(font)
tmp_xlsx <- tempfile() xlsxFile <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") unzip(xlsxFile, exdir = tmp_xlsx) wb <- wb_load(xlsxFile) styles_xml <- sprintf("%s/xl/styles.xml", tmp_xlsx) # is external pointer sxml <- read_xml(styles_xml) # is character font <- xml_node(sxml, "styleSheet", "fonts", "font") # is again external pointer as_xml(font)
Modify / get the default font for the workbook. This will alter the latin major and minor font in the workbooks theme.
wb_set_base_font( wb, font_size = 11, font_color = wb_color(theme = "1"), font_name = "Aptos Narrow", ... ) wb_get_base_font(wb)
wb_set_base_font( wb, font_size = 11, font_color = wb_color(theme = "1"), font_name = "Aptos Narrow", ... ) wb_get_base_font(wb)
wb |
A workbook object |
font_size |
Font size |
font_color |
Font color |
font_name |
Name of a font |
... |
Additional arguments |
The font name is not validated in anyway. Spreadsheet software replaces unknown font names with system defaults.
The default base font is Aptos Narrow, black, size 11. If font_name
differs
from the name in wb_get_base_font()
, the theme is updated to use the newly
selected font name.
Other workbook styling functions:
wb_add_dxfs_style()
,
wb_add_style()
,
wb_base_colors
Other workbook wrappers:
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
## create a workbook wb <- wb_workbook(theme = "Office 2013 - 2022 Theme") wb$add_worksheet("S1") ## modify base font to size 10 Aptos Narrow in red wb$set_base_font(font_size = 10, font_color = wb_color("red"), font_name = "Aptos Narrow") wb$add_data(x = iris) ## font color does not affect tables wb$add_data_table(x = iris, dims = wb_dims(from_col = 10)) ## get the base font wb_get_base_font(wb)
## create a workbook wb <- wb_workbook(theme = "Office 2013 - 2022 Theme") wb$add_worksheet("S1") ## modify base font to size 10 Aptos Narrow in red wb$set_base_font(font_size = 10, font_color = wb_color("red"), font_name = "Aptos Narrow") wb$add_data(x = iris) ## font color does not affect tables wb$add_data_table(x = iris, dims = wb_dims(from_col = 10)) ## get the base font wb_get_base_font(wb)
Cleans a worksheet name by removing legal characters.
clean_worksheet_name(x, replacement = " ")
clean_worksheet_name(x, replacement = " ")
x |
A vector, coerced to |
replacement |
A single value to replace illegal characters by. |
Illegal characters are considered \
, /
, ?
, *
, :
, [
, and
]
. These must be intentionally removed from worksheet names prior to
creating a new worksheet.
x with bad characters removed
Remove / set worksheet column widths to specified width or "auto".
wb_set_col_widths( wb, sheet = current_sheet(), cols, widths = 8.43, hidden = FALSE ) wb_remove_col_widths(wb, sheet = current_sheet(), cols)
wb_set_col_widths( wb, sheet = current_sheet(), cols, widths = 8.43, hidden = FALSE ) wb_remove_col_widths(wb, sheet = current_sheet(), cols)
wb |
A |
sheet |
A name or index of a worksheet, a vector in the case of |
cols |
Indices of cols to set/remove column widths. |
widths |
Width to set |
Logical vector recycled to the length of |
The global min and max column width for "auto" columns is set by (default values show):
options("openxlsx2.minWidth" = 3)
options("openxlsx2.maxWidth" = 250)
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.
NOTE: The default column width varies by spreadsheet software, operating system,
and DPI settings used. Setting widths
to specific value also is no guarantee
that the output will have consistent column widths.
For automatic text wrapping of columns use wb_add_cell_style(wrap_text = TRUE)
Other workbook wrappers:
base_font-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
## Create a new workbook wb <- wb_workbook() ## Add a worksheet wb$add_worksheet("Sheet 1") ## set col widths wb$set_col_widths(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") ## removing column widths ## Create a new workbook wb <- wb_load(file = system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")) ## remove column widths in columns 1 to 20 wb_remove_col_widths(wb, 1, cols = 1:20)
## Create a new workbook wb <- wb_workbook() ## Add a worksheet wb$add_worksheet("Sheet 1") ## set col widths wb$set_col_widths(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") ## removing column widths ## Create a new workbook wb <- wb_load(file = system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")) ## remove column widths in columns 1 to 20 wb_remove_col_widths(wb, 1, cols = 1:20)
Converts an Excel column label to an integer.
col2int(x)
col2int(x)
x |
A character vector |
An integer column label (or NULL
if x
is NULL
)
col2int(LETTERS)
col2int(LETTERS)
Convert from Excel date number to R Date type
convert_date(x, origin = "1900-01-01", ...) convert_datetime(x, origin = "1900-01-01", ...) convert_hms(x)
convert_date(x, origin = "1900-01-01", ...) convert_datetime(x, origin = "1900-01-01", ...) convert_hms(x)
x |
A vector of integers |
origin |
date. Default value is for Windows Excel 2010 |
... |
Arguments passed on to
|
Excel stores dates as number of days from some origin day
A date, datetime, or hms.
# date -- ## 2014 April 21st to 25th convert_date(c(41750, 41751, 41752, 41753, 41754, NA)) convert_date(c(41750.2, 41751.99, NA, 41753)) # datetime -- ## 2014-07-01, 2014-06-30, 2014-06-29 x <- c(41821.8127314815, 41820.8127314815, NA, 41819, NaN) convert_datetime(x) convert_datetime(x, tz = "Australia/Perth") convert_datetime(x, tz = "UTC") # hms --- ## 12:13:14 x <- 0.50918982 convert_hms(x)
# date -- ## 2014 April 21st to 25th convert_date(c(41750, 41751, 41752, 41753, 41754, NA)) convert_date(c(41750.2, 41751.99, NA, 41753)) # datetime -- ## 2014-07-01, 2014-06-30, 2014-06-29 x <- c(41821.8127314815, 41820.8127314815, NA, 41819, NaN) convert_datetime(x) convert_datetime(x, tz = "Australia/Perth") convert_datetime(x, tz = "UTC") # hms --- ## 12:13:14 x <- 0.50918982 convert_hms(x)
convert back to an Excel Date
convert_to_excel_date(df, date1904 = FALSE)
convert_to_excel_date(df, date1904 = FALSE)
df |
dataframe |
date1904 |
take different origin |
xlsxFile <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb1 <- wb_load(xlsxFile) df <- wb_to_df(wb1) # conversion is done on dataframes only convert_to_excel_date(df = df["Var5"], date1904 = FALSE)
xlsxFile <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb1 <- wb_load(xlsxFile) df <- wb_to_df(wb1) # conversion is done on dataframes only convert_to_excel_date(df = df["Var5"], date1904 = FALSE)
Border styles can any of the following: "thin", "thick", "slantDashDot", "none", "mediumDashed", "mediumDashDot", "medium", "hair", "double", "dotted", "dashed", "dashedDotDot", "dashDot"
Border colors can be created with wb_color()
create_border( diagonal_down = "", diagonal_up = "", outline = "", bottom = NULL, bottom_color = NULL, diagonal = NULL, diagonal_color = NULL, end = "", horizontal = "", left = NULL, left_color = NULL, right = NULL, right_color = NULL, start = "", top = NULL, top_color = NULL, vertical = "", ... )
create_border( diagonal_down = "", diagonal_up = "", outline = "", bottom = NULL, bottom_color = NULL, diagonal = NULL, diagonal_color = NULL, end = "", horizontal = "", left = NULL, left_color = NULL, right = NULL, right_color = NULL, start = "", top = NULL, top_color = NULL, vertical = "", ... )
diagonal_down |
x |
diagonal_up |
x |
outline |
x |
bottom |
X |
bottom_color , diagonal_color , left_color , right_color , top_color
|
a color created with |
diagonal |
X |
end |
x, |
horizontal |
x |
left |
x |
right |
x |
start |
x |
top |
x |
vertical |
x |
... |
x |
Other style creating functions:
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Helper to create a cell style
create_cell_style( border_id = "", fill_id = "", font_id = "", num_fmt_id = "", pivot_button = "", quote_prefix = "", xf_id = "", horizontal = "", indent = "", justify_last_line = "", reading_order = "", relative_indent = "", shrink_to_fit = "", text_rotation = "", vertical = "", wrap_text = "", ext_lst = "", hidden = "", locked = "", ... )
create_cell_style( border_id = "", fill_id = "", font_id = "", num_fmt_id = "", pivot_button = "", quote_prefix = "", xf_id = "", horizontal = "", indent = "", justify_last_line = "", reading_order = "", relative_indent = "", shrink_to_fit = "", text_rotation = "", vertical = "", wrap_text = "", ext_lst = "", hidden = "", locked = "", ... )
border_id |
dummy |
fill_id |
dummy |
font_id |
dummy |
num_fmt_id |
a numFmt ID for a builtin style |
pivot_button |
dummy |
quote_prefix |
dummy |
xf_id |
dummy |
horizontal |
alignment can be ”, 'general', 'left', 'center', 'right', 'fill', 'justify', 'centerContinuous', 'distributed' |
indent |
dummy |
justify_last_line |
dummy |
reading_order |
dummy |
relative_indent |
dummy |
shrink_to_fit |
dummy |
text_rotation |
dummy |
vertical |
alignment can be ”, 'top', 'center', 'bottom', 'justify', 'distributed' |
wrap_text |
dummy |
ext_lst |
dummy |
dummy |
|
locked |
dummy |
... |
reserved for additional arguments |
"ID" | "numFmt" |
"0" | "General" |
"1" | "0" |
"2" | "0.00" |
"3" | "#,##0" |
"4" | "#,##0.00" |
"9" | "0%" |
"10" | "0.00%" |
"11" | "0.00E+00" |
"12" | "# ?/?" |
"13" | "# ??/??" |
"14" | "mm-dd-yy" |
"15" | "d-mmm-yy" |
"16" | "d-mmm" |
"17" | "mmm-yy" |
"18" | "h:mm AM/PM" |
"19" | "h:mm:ss AM/PM" |
"20" | "h:mm" |
"21" | "h:mm:ss" |
"22" | "m/d/yy h:mm" |
"37" | "#,##0 ;(#,##0)" |
"38" | "#,##0 ;[Red](#,##0)" |
"39" | "#,##0.00;(#,##0.00)" |
"40" | "#,##0.00;[Red](#,##0.00)" |
"45" | "mm:ss" |
"46" | "[h]:mm:ss" |
"47" | "mmss.0" |
"48" | "##0.0E+0" |
"49" | "@" |
Other style creating functions:
create_border()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Create custom color themes that can be used with wb_set_base_colors()
. The color input will be checked with wb_color()
, so it must be either a color R from grDevices::colors()
or a hex value.
Default values for the dark argument are: black
, white
, darkblue
and lightgray
. For the accent argument, the six inner values of grDevices::palette()
. The link argument uses blue
and purple
by default for active and visited links.
create_colors_xml(name = "Base R", dark = NULL, accent = NULL, link = NULL)
create_colors_xml(name = "Base R", dark = NULL, accent = NULL, link = NULL)
name |
the color name |
dark |
four colors: dark, light, brighter dark, darker light |
accent |
six accent colors |
link |
two link colors: link and visited link |
Other style creating functions:
create_border()
,
create_cell_style()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
colors <- create_colors_xml() wb <- wb_workbook()$add_worksheet()$set_base_colors(xml = colors)
colors <- create_colors_xml() wb <- wb_workbook()$add_worksheet()$set_base_colors(xml = colors)
Create a new style to apply to worksheet cells. Created styles have to be assigned to a workbook to use them
create_dxfs_style( font_name = NULL, font_size = NULL, font_color = NULL, num_fmt = NULL, border = NULL, border_color = wb_color(getOption("openxlsx2.borderColor", "black")), border_style = getOption("openxlsx2.borderStyle", "thin"), bg_fill = NULL, fg_color = NULL, gradient_fill = NULL, text_bold = NULL, text_strike = NULL, text_italic = NULL, text_underline = NULL, ... )
create_dxfs_style( font_name = NULL, font_size = NULL, font_color = NULL, num_fmt = NULL, border = NULL, border_color = wb_color(getOption("openxlsx2.borderColor", "black")), border_style = getOption("openxlsx2.borderStyle", "thin"), bg_fill = NULL, fg_color = NULL, gradient_fill = NULL, text_bold = NULL, text_strike = NULL, text_italic = NULL, text_underline = NULL, ... )
font_name |
A name of a font. Note the font name is not validated.
If |
font_size |
Font size. A numeric greater than 0. By default, the workbook base font size is used. (Defaults to 11) |
font_color |
Color of text in cell. A valid hex color beginning with "#"
or one of colors(). If |
num_fmt |
Cell formatting. Some custom openxml format |
border |
|
border_color |
"black" |
border_style |
"thin" |
bg_fill |
Cell background fill color. |
fg_color |
Cell foreground fill color. |
gradient_fill |
An xml string beginning with |
text_bold |
bold |
text_strike |
strikeout |
text_italic |
italic |
text_underline |
underline 1, true, single or double |
... |
Additional arguments |
It is possible to override border_color and border_style with {left, right, top, bottom}_color, {left, right, top, bottom}_style.
A dxfs style node
wb_add_style()
wb_add_dxfs_style()
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
# do not apply anything style1 <- create_dxfs_style() # change font color and background color style2 <- create_dxfs_style( font_color = wb_color(hex = "FF9C0006"), bgFill = wb_color(hex = "FFFFC7CE") ) # change font (type, size and color) and background # the old default in openxlsx and openxlsx2 <= 0.3 style3 <- create_dxfs_style( font_name = "Aptos Narrow", font_size = 11, font_color = wb_color(hex = "FF9C0006"), bgFill = wb_color(hex = "FFFFC7CE") ) ## See package vignettes for further examples
# do not apply anything style1 <- create_dxfs_style() # change font color and background color style2 <- create_dxfs_style( font_color = wb_color(hex = "FF9C0006"), bgFill = wb_color(hex = "FFFFC7CE") ) # change font (type, size and color) and background # the old default in openxlsx and openxlsx2 <= 0.3 style3 <- create_dxfs_style( font_name = "Aptos Narrow", font_size = 11, font_color = wb_color(hex = "FF9C0006"), bgFill = wb_color(hex = "FFFFC7CE") ) ## See package vignettes for further examples
Create fill pattern
create_fill( gradientFill = "", patternType = "", bgColor = NULL, fgColor = NULL, ... )
create_fill( gradientFill = "", patternType = "", bgColor = NULL, fgColor = NULL, ... )
gradientFill |
complex fills |
patternType |
various: default is "none", but also "solid", or a color like "gray125" |
bgColor |
hex8 color with alpha, red, green, blue only for patternFill |
fgColor |
hex8 color with alpha, red, green, blue only for patternFill |
... |
... |
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Create font format
create_font( b = "", charset = "", color = wb_color(hex = "FF000000"), condense = "", extend = "", family = "2", i = "", name = "Aptos Narrow", outline = "", scheme = "minor", shadow = "", strike = "", sz = "11", u = "", vert_align = "", ... )
create_font( b = "", charset = "", color = wb_color(hex = "FF000000"), condense = "", extend = "", family = "2", i = "", name = "Aptos Narrow", outline = "", scheme = "minor", shadow = "", strike = "", sz = "11", u = "", vert_align = "", ... )
b |
bold |
charset |
charset |
color |
rgb color: default "FF000000" |
condense |
condense |
extend |
extend |
family |
font family: default "2" |
i |
italic |
name |
font name: default "Aptos Narrow" |
outline |
outline |
scheme |
font scheme: default "minor" |
shadow |
shadow |
strike |
strike |
sz |
font size: default "11", |
u |
underline |
vert_align |
vertical alignment |
... |
... |
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_numfmt()
,
create_tablestyle()
font <- create_font() # openxml has the alpha value leading hex8 <- unlist(xml_attr(read_xml(font), "font", "color")) hex8 <- paste0("#", substr(hex8, 3, 8), substr(hex8, 1, 2)) # # write test color # col <- crayon::make_style(col2rgb(hex8, alpha = TRUE)) # cat(col("Test"))
font <- create_font() # openxml has the alpha value leading hex8 <- unlist(xml_attr(read_xml(font), "font", "color")) hex8 <- paste0("#", substr(hex8, 3, 8), substr(hex8, 1, 2)) # # write test color # col <- crayon::make_style(col2rgb(hex8, alpha = TRUE)) # cat(col("Test"))
Wrapper to create internal hyperlink string to pass to wb_add_formula()
.
Either link to external URLs or local files or straight to cells of local Excel sheets.
Note that for an external URL, only file
and text
should be supplied.
You can supply dims
to wb_add_formula()
to control the location of the link.
create_hyperlink(sheet, row = 1, col = 1, text = NULL, file = NULL)
create_hyperlink(sheet, row = 1, col = 1, text = NULL, file = NULL)
sheet |
Name of a worksheet |
row |
integer row number for hyperlink to link to |
col |
column number of letter for hyperlink to link to |
text |
Display text |
file |
Hyperlink or Excel file name to point to. If |
wb <- wb_workbook()$ add_worksheet("Sheet1")$add_worksheet("Sheet2")$add_worksheet("Sheet3") ## Internal Hyperlink - create hyperlink formula manually x <- '=HYPERLINK(\"#Sheet2!B3\", "Text to Display - Link to Sheet2")' wb$add_formula(sheet = "Sheet1", x = x, dims = "A1") ## Internal - No text to display using create_hyperlink() function x <- create_hyperlink(sheet = "Sheet3", row = 1, col = 2) wb$add_formula(sheet = "Sheet1", x = x, dims = "A2") ## Internal - Text to display x <- create_hyperlink(sheet = "Sheet3", row = 1, col = 2,text = "Link to Sheet 3") wb$add_formula(sheet = "Sheet1", x = x, dims = "A3") ## Link to file - No text to display fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") x <- create_hyperlink(sheet = "Sheet1", row = 3, col = 10, file = fl) wb$add_formula(sheet = "Sheet1", x = x, dims = "A4") ## Link to file - Text to display fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") x <- create_hyperlink(sheet = "Sheet2", row = 3, col = 10, file = fl, text = "Link to File.") wb$add_formula(sheet = "Sheet1", x = x, dims = "A5") ## Link to external file - Text to display x <- '=HYPERLINK("[C:/Users]", "Link to an external file")' wb$add_formula(sheet = "Sheet1", x = x, dims = "A6") x <- create_hyperlink(text = "test.png", file = "D:/somepath/somepicture.png") wb$add_formula(x = x, dims = "A7") ## Link to an URL. x <- create_hyperlink(text = "openxlsx2 website", file = "https://janmarvin.github.io/openxlsx2/") wb$add_formula(x = x, dims = "A8") # if (interactive()) wb$open()
wb <- wb_workbook()$ add_worksheet("Sheet1")$add_worksheet("Sheet2")$add_worksheet("Sheet3") ## Internal Hyperlink - create hyperlink formula manually x <- '=HYPERLINK(\"#Sheet2!B3\", "Text to Display - Link to Sheet2")' wb$add_formula(sheet = "Sheet1", x = x, dims = "A1") ## Internal - No text to display using create_hyperlink() function x <- create_hyperlink(sheet = "Sheet3", row = 1, col = 2) wb$add_formula(sheet = "Sheet1", x = x, dims = "A2") ## Internal - Text to display x <- create_hyperlink(sheet = "Sheet3", row = 1, col = 2,text = "Link to Sheet 3") wb$add_formula(sheet = "Sheet1", x = x, dims = "A3") ## Link to file - No text to display fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") x <- create_hyperlink(sheet = "Sheet1", row = 3, col = 10, file = fl) wb$add_formula(sheet = "Sheet1", x = x, dims = "A4") ## Link to file - Text to display fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") x <- create_hyperlink(sheet = "Sheet2", row = 3, col = 10, file = fl, text = "Link to File.") wb$add_formula(sheet = "Sheet1", x = x, dims = "A5") ## Link to external file - Text to display x <- '=HYPERLINK("[C:/Users]", "Link to an external file")' wb$add_formula(sheet = "Sheet1", x = x, dims = "A6") x <- create_hyperlink(text = "test.png", file = "D:/somepath/somepicture.png") wb$add_formula(x = x, dims = "A7") ## Link to an URL. x <- create_hyperlink(text = "openxlsx2 website", file = "https://janmarvin.github.io/openxlsx2/") wb$add_formula(x = x, dims = "A8") # if (interactive()) wb$open()
Create number format
create_numfmt(numFmtId, formatCode)
create_numfmt(numFmtId, formatCode)
numFmtId |
an id, the list can be found in the Details of |
formatCode |
a format code |
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_tablestyle()
Create a sparkline to be added a workbook with wb_add_sparklines()
create_sparklines( sheet = current_sheet(), dims, sqref, type = NULL, negative = NULL, display_empty_cells_as = "gap", markers = NULL, high = NULL, low = NULL, first = NULL, last = NULL, color_series = wb_color(hex = "FF376092"), color_negative = wb_color(hex = "FFD00000"), color_axis = wb_color(hex = "FFD00000"), color_markers = wb_color(hex = "FFD00000"), color_first = wb_color(hex = "FFD00000"), color_last = wb_color(hex = "FFD00000"), color_high = wb_color(hex = "FFD00000"), color_low = wb_color(hex = "FFD00000"), manual_max = NULL, manual_min = NULL, line_weight = NULL, date_axis = NULL, display_x_axis = NULL, display_hidden = NULL, min_axis_type = NULL, max_axis_type = NULL, right_to_left = NULL, ... )
create_sparklines( sheet = current_sheet(), dims, sqref, type = NULL, negative = NULL, display_empty_cells_as = "gap", markers = NULL, high = NULL, low = NULL, first = NULL, last = NULL, color_series = wb_color(hex = "FF376092"), color_negative = wb_color(hex = "FFD00000"), color_axis = wb_color(hex = "FFD00000"), color_markers = wb_color(hex = "FFD00000"), color_first = wb_color(hex = "FFD00000"), color_last = wb_color(hex = "FFD00000"), color_high = wb_color(hex = "FFD00000"), color_low = wb_color(hex = "FFD00000"), manual_max = NULL, manual_min = NULL, line_weight = NULL, date_axis = NULL, display_x_axis = NULL, display_hidden = NULL, min_axis_type = NULL, max_axis_type = NULL, right_to_left = NULL, ... )
sheet |
sheet |
dims |
Cell range of cells used to create the sparklines |
sqref |
Cell range of the destination of the sparklines. |
type |
Either |
negative |
negative |
display_empty_cells_as |
Either |
markers |
markers add marker to line |
high |
highlight highest value |
low |
highlight lowest value |
first |
highlight first value |
last |
highlight last value |
color_series |
colorSeries |
color_negative |
colorNegative |
color_axis |
colorAxis |
color_markers |
colorMarkers |
color_first |
colorFirst |
color_last |
colorLast |
color_high |
colorHigh |
color_low |
colorLow |
manual_max |
manualMax |
manual_min |
manualMin |
line_weight |
lineWeight |
date_axis |
dateAxis |
display_x_axis |
displayXAxis |
displayHidden |
|
min_axis_type |
minAxisType |
max_axis_type |
maxAxisType |
right_to_left |
rightToLeft |
... |
additional arguments |
Colors are all predefined to be rgb. Maybe theme colors can be used too.
A string containing XML code
# create sparklineGroup sparklines <- c( create_sparklines("Sheet 1", "A3:L3", "M3", type = "column", first = "1"), create_sparklines("Sheet 1", "A2:L2", "M2", markers = "1"), create_sparklines("Sheet 1", "A4:L4", "M4", type = "stacked", negative = "1") ) t1 <- AirPassengers t2 <- do.call(cbind, split(t1, cycle(t1))) dimnames(t2) <- dimnames(.preformat.ts(t1)) wb <- wb_workbook()$ add_worksheet("Sheet 1")$ add_data(x = t2)$ add_sparklines(sparklines = sparklines)
# create sparklineGroup sparklines <- c( create_sparklines("Sheet 1", "A3:L3", "M3", type = "column", first = "1"), create_sparklines("Sheet 1", "A2:L2", "M2", markers = "1"), create_sparklines("Sheet 1", "A4:L4", "M4", type = "stacked", negative = "1") ) t1 <- AirPassengers t2 <- do.call(cbind, split(t1, cycle(t1))) dimnames(t2) <- dimnames(.preformat.ts(t1)) wb <- wb_workbook()$ add_worksheet("Sheet 1")$ add_data(x = t2)$ add_sparklines(sparklines = sparklines)
Create a custom (pivot) table style. These functions are for expert use only. Use other styling functions instead.
create_tablestyle( name, whole_table = NULL, header_row = NULL, total_row = NULL, first_column = NULL, last_column = NULL, first_row_stripe = NULL, second_row_stripe = NULL, first_column_stripe = NULL, second_column_stripe = NULL, first_header_cell = NULL, last_header_cell = NULL, first_total_cell = NULL, last_total_cell = NULL, ... ) create_pivottablestyle( name, whole_table = NULL, header_row = NULL, grand_total_row = NULL, first_column = NULL, grand_total_column = NULL, first_row_stripe = NULL, second_row_stripe = NULL, first_column_stripe = NULL, second_column_stripe = NULL, first_header_cell = NULL, first_subtotal_column = NULL, second_subtotal_column = NULL, third_subtotal_column = NULL, first_subtotal_row = NULL, second_subtotal_row = NULL, third_subtotal_row = NULL, blank_row = NULL, first_column_subheading = NULL, second_column_subheading = NULL, third_column_subheading = NULL, first_row_subheading = NULL, second_row_subheading = NULL, third_row_subheading = NULL, page_field_labels = NULL, page_field_values = NULL, ... )
create_tablestyle( name, whole_table = NULL, header_row = NULL, total_row = NULL, first_column = NULL, last_column = NULL, first_row_stripe = NULL, second_row_stripe = NULL, first_column_stripe = NULL, second_column_stripe = NULL, first_header_cell = NULL, last_header_cell = NULL, first_total_cell = NULL, last_total_cell = NULL, ... ) create_pivottablestyle( name, whole_table = NULL, header_row = NULL, grand_total_row = NULL, first_column = NULL, grand_total_column = NULL, first_row_stripe = NULL, second_row_stripe = NULL, first_column_stripe = NULL, second_column_stripe = NULL, first_header_cell = NULL, first_subtotal_column = NULL, second_subtotal_column = NULL, third_subtotal_column = NULL, first_subtotal_row = NULL, second_subtotal_row = NULL, third_subtotal_row = NULL, blank_row = NULL, first_column_subheading = NULL, second_column_subheading = NULL, third_column_subheading = NULL, first_row_subheading = NULL, second_row_subheading = NULL, third_row_subheading = NULL, page_field_labels = NULL, page_field_values = NULL, ... )
name |
name |
whole_table |
wholeTable |
header_row , total_row
|
...Row |
first_column , last_column
|
...Column |
first_row_stripe , second_row_stripe
|
...RowStripe |
first_column_stripe , second_column_stripe
|
...ColumnStripe |
first_header_cell , last_header_cell
|
...HeaderCell |
first_total_cell , last_total_cell
|
...TotalCell |
... |
additional arguments |
grand_total_row |
totalRow |
grand_total_column |
lastColumn |
first_subtotal_column , second_subtotal_column , third_subtotal_column
|
...SubtotalColumn |
first_subtotal_row , second_subtotal_row , third_subtotal_row
|
...SubtotalRow |
blank_row |
blankRow |
first_column_subheading , second_column_subheading , third_column_subheading
|
...ColumnSubheading |
first_row_subheading , second_row_subheading , third_row_subheading
|
...RowSubheading |
page_field_labels |
pageFieldLabels |
page_field_values |
pageFieldValues |
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
Modify and get workbook creators
wb_add_creators(wb, creators) wb_set_creators(wb, creators) wb_remove_creators(wb, creators) wb_get_creators(wb)
wb_add_creators(wb, creators) wb_set_creators(wb, creators) wb_remove_creators(wb, creators) wb_get_creators(wb)
wb |
A |
creators |
A character vector of names |
wb_set_creators()
, wb_add_creators()
, and wb_remove_creators()
return
the wbWorkbook
object
wb_get_creators()
returns a character
vector of creators
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
# workbook made with default creator (see [wbWorkbook]) wb <- wb_workbook() wb_get_creators(wb) # add a new creator (assuming "test" isn't your default creator) wb <- wb_add_creators(wb, "test") wb_get_creators(wb) # remove the creator (should be the same as before) wb <- wb_remove_creators(wb, "test") wb_get_creators(wb)
# workbook made with default creator (see [wbWorkbook]) wb <- wb_workbook() wb_get_creators(wb) # add a new creator (assuming "test" isn't your default creator) wb <- wb_add_creators(wb, "test") wb_get_creators(wb) # remove the creator (should be the same as before) wb <- wb_remove_creators(wb, "test") wb_get_creators(wb)
dims
Internal helpers to (de)construct a dims argument from/to a row and column vector. Exported for user convenience.
dims_to_rowcol(x, as_integer = FALSE) rowcol_to_dims(row, col, single = TRUE)
dims_to_rowcol(x, as_integer = FALSE) rowcol_to_dims(row, col, single = TRUE)
x |
a dimension object "A1" or "A1:A1" |
as_integer |
If the output should be returned as integer, (defaults to string) |
row |
a numeric vector of rows |
col |
a numeric or character vector of cols |
single |
argument indicating if |
A dims
string for _to_dim
i.e "A1:A1"
A list of rows and columns for to_rowcol
dims_to_rowcol("A1:J10") wb_dims(1:10, 1:10)
dims_to_rowcol("A1:J10") wb_dims(1:10, 1:10)
Add or remove excel column filters to a worksheet
wb_add_filter(wb, sheet = current_sheet(), rows, cols) wb_remove_filter(wb, sheet = current_sheet())
wb_add_filter(wb, sheet = current_sheet(), rows, cols) wb_remove_filter(wb, sheet = current_sheet())
wb |
A workbook object |
sheet |
A worksheet name or index.
In |
rows |
A row number. |
cols |
columns to add filter to. |
Adds filters to worksheet columns, same as with_filter = TRUE
in wb_add_data()
wb_add_data_table()
automatically adds filters to first row of a table.
NOTE Can only have a single filter per worksheet unless using tables.
wb_add_data()
, wb_add_data_table()
Other worksheet content functions:
col_widths-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_worksheet("Sheet 3") wb$add_data(1, iris) wb$add_filter(1, row = 1, cols = seq_along(iris)) ## Equivalently wb$add_data(2, x = iris, with_filter = TRUE) ## Similarly wb$add_data_table(3, iris) wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_worksheet("Sheet 3") wb$add_data(1, iris) wb_add_filter(wb, 1, row = 1, cols = seq_along(iris)) ## Equivalently wb$add_data(2, x = iris, with_filter = TRUE) ## Similarly wb$add_data_table(3, iris) ## remove filters wb_remove_filter(wb, 1:2) ## remove filters wb_remove_filter(wb, 3) ## Does not affect tables!
wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_worksheet("Sheet 3") wb$add_data(1, iris) wb$add_filter(1, row = 1, cols = seq_along(iris)) ## Equivalently wb$add_data(2, x = iris, with_filter = TRUE) ## Similarly wb$add_data_table(3, iris) wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_worksheet("Sheet 3") wb$add_data(1, iris) wb_add_filter(wb, 1, row = 1, cols = seq_along(iris)) ## Equivalently wb$add_data(2, x = iris, with_filter = TRUE) ## Similarly wb$add_data_table(3, iris) ## remove filters wb_remove_filter(wb, 1:2) ## remove filters wb_remove_filter(wb, 3) ## Does not affect tables!
format strings independent of the cell style.
fmt_txt( x, bold = FALSE, italic = FALSE, underline = FALSE, strike = FALSE, size = NULL, color = NULL, font = NULL, charset = NULL, outline = NULL, vert_align = NULL ) ## S3 method for class 'fmt_txt' x + y ## S3 method for class 'fmt_txt' as.character(x, ...) ## S3 method for class 'fmt_txt' print(x, ...)
fmt_txt( x, bold = FALSE, italic = FALSE, underline = FALSE, strike = FALSE, size = NULL, color = NULL, font = NULL, charset = NULL, outline = NULL, vert_align = NULL ) ## S3 method for class 'fmt_txt' x + y ## S3 method for class 'fmt_txt' as.character(x, ...) ## S3 method for class 'fmt_txt' print(x, ...)
x , y
|
an openxlsx2 fmt_txt string |
bold |
bold |
italic |
italic |
underline |
underline |
strike |
strike |
size |
the font size |
color |
a wbColor color for the font |
font |
the font name |
charset |
integer value from the table below |
outline |
TRUE or FALSE |
vert_align |
baseline, superscript, or subscript |
... |
additional arguments for default print |
The result is an xml string. It is possible to paste multiple fmt_txt()
strings together to create a string with differing styles.
Using fmt_txt(charset = 161)
will give the Greek Character Set
charset | "Character Set" |
0 | "ANSI_CHARSET" |
1 | "DEFAULT_CHARSET" |
2 | "SYMBOL_CHARSET" |
77 | "MAC_CHARSET" |
128 | "SHIFTJIS_CHARSET" |
129 | "HANGUL_CHARSET" |
130 | "JOHAB_CHARSET" |
134 | "GB2312_CHARSET" |
136 | "CHINESEBIG5_CHARSET" |
161 | "GREEK_CHARSET" |
162 | "TURKISH_CHARSET" |
163 | "VIETNAMESE_CHARSET" |
177 | "HEBREW_CHARSET" |
178 | "ARABIC_CHARSET" |
186 | "BALTIC_CHARSET" |
204 | "RUSSIAN_CHARSET" |
222 | "THAI_CHARSET" |
238 | "EASTEUROPE_CHARSET" |
255 | "OEM_CHARSET" |
You can join additional objects into fmt_txt() objects using "+".
Though be aware that fmt_txt("sum:") + (2 + 2)
is different to fmt_txt("sum:") + 2 + 2
.
fmt_txt("bar", underline = TRUE) fmt_txt("foo ", bold = TRUE) + fmt_txt("bar") as.character(fmt_txt(2))
fmt_txt("bar", underline = TRUE) fmt_txt("foo ", bold = TRUE) + fmt_txt("bar") as.character(fmt_txt(2))
Group a selection of rows or cols
wb_group_cols( wb, sheet = current_sheet(), cols, collapsed = FALSE, levels = NULL ) wb_ungroup_cols(wb, sheet = current_sheet(), cols) wb_group_rows( wb, sheet = current_sheet(), rows, collapsed = FALSE, levels = NULL ) wb_ungroup_rows(wb, sheet = current_sheet(), rows)
wb_group_cols( wb, sheet = current_sheet(), cols, collapsed = FALSE, levels = NULL ) wb_ungroup_cols(wb, sheet = current_sheet(), cols) wb_group_rows( wb, sheet = current_sheet(), rows, collapsed = FALSE, levels = NULL ) wb_ungroup_rows(wb, sheet = current_sheet(), rows)
wb |
A |
sheet |
A name or index of a worksheet |
collapsed |
If |
levels |
levels |
rows , cols
|
Indices of rows and columns to group |
If row was previously hidden, it will now be shown.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
# create matrix t1 <- AirPassengers t2 <- do.call(cbind, split(t1, cycle(t1))) dimnames(t2) <- dimnames(.preformat.ts(t1)) wb <- wb_workbook() wb$add_worksheet("AirPass") wb$add_data("AirPass", t2, row_names = TRUE) # groups will always end on/show the last row. in the example 1950, 1955, and 1960 wb <- wb_group_rows(wb, "AirPass", 2:3, collapsed = TRUE) # group years < 1950 wb <- wb_group_rows(wb, "AirPass", 4:8, collapsed = TRUE) # group years 1951-1955 wb <- wb_group_rows(wb, "AirPass", 9:13) # group years 1956-1960 wb <- wb_group_cols(wb, "AirPass", 2:4, collapsed = TRUE) wb <- wb_group_cols(wb, "AirPass", 5:7, collapsed = TRUE) wb <- wb_group_cols(wb, "AirPass", 8:10, collapsed = TRUE) wb <- wb_group_cols(wb, "AirPass", 11:13) ### create grouping levels grp_rows <- list( "1" = seq(2, 3), "2" = seq(4, 8), "3" = seq(9, 13) ) grp_cols <- list( "1" = seq(2, 4), "2" = seq(5, 7), "3" = seq(8, 10), "4" = seq(11, 13) ) wb <- wb_workbook() wb$add_worksheet("AirPass") wb$add_data("AirPass", t2, row_names = TRUE) wb$group_cols("AirPass", cols = grp_cols) wb$group_rows("AirPass", rows = grp_rows)
# create matrix t1 <- AirPassengers t2 <- do.call(cbind, split(t1, cycle(t1))) dimnames(t2) <- dimnames(.preformat.ts(t1)) wb <- wb_workbook() wb$add_worksheet("AirPass") wb$add_data("AirPass", t2, row_names = TRUE) # groups will always end on/show the last row. in the example 1950, 1955, and 1960 wb <- wb_group_rows(wb, "AirPass", 2:3, collapsed = TRUE) # group years < 1950 wb <- wb_group_rows(wb, "AirPass", 4:8, collapsed = TRUE) # group years 1951-1955 wb <- wb_group_rows(wb, "AirPass", 9:13) # group years 1956-1960 wb <- wb_group_cols(wb, "AirPass", 2:4, collapsed = TRUE) wb <- wb_group_cols(wb, "AirPass", 5:7, collapsed = TRUE) wb <- wb_group_cols(wb, "AirPass", 8:10, collapsed = TRUE) wb <- wb_group_cols(wb, "AirPass", 11:13) ### create grouping levels grp_rows <- list( "1" = seq(2, 3), "2" = seq(4, 8), "3" = seq(9, 13) ) grp_cols <- list( "1" = seq(2, 4), "2" = seq(5, 7), "3" = seq(8, 10), "4" = seq(11, 13) ) wb <- wb_workbook() wb$add_worksheet("AirPass") wb$add_data("AirPass", t2, row_names = TRUE) wb$group_cols("AirPass", cols = grp_cols) wb$group_rows("AirPass", rows = grp_rows)
Converts an integer to an Excel column label.
int2col(x)
int2col(x)
x |
A numeric vector. |
int2col(1:10)
int2col(1:10)
Create / delete a named region. You can also specify a named region by using
the name
argument in wb_add_data(x = iris, name = "my-region")
.
It is important to note that named regions are not case-sensitive and must be unique.
wb_add_named_region( wb, sheet = current_sheet(), dims = "A1", name, local_sheet = FALSE, overwrite = FALSE, comment = NULL, hidden = NULL, custom_menu = NULL, description = NULL, is_function = NULL, function_group_id = NULL, help = NULL, local_name = NULL, publish_to_server = NULL, status_bar = NULL, vb_procedure = NULL, workbook_parameter = NULL, xml = NULL, ... ) wb_remove_named_region(wb, sheet = current_sheet(), name = NULL) wb_get_named_regions(wb, tables = FALSE, x = NULL)
wb_add_named_region( wb, sheet = current_sheet(), dims = "A1", name, local_sheet = FALSE, overwrite = FALSE, comment = NULL, hidden = NULL, custom_menu = NULL, description = NULL, is_function = NULL, function_group_id = NULL, help = NULL, local_name = NULL, publish_to_server = NULL, status_bar = NULL, vb_procedure = NULL, workbook_parameter = NULL, xml = NULL, ... ) wb_remove_named_region(wb, sheet = current_sheet(), name = NULL) wb_get_named_regions(wb, tables = FALSE, x = NULL)
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
dims |
Worksheet cell range of the region ("A1:D4"). |
name |
Name for region. A character vector of length 1. Note that region names must be case-insensitive unique. |
local_sheet |
If |
overwrite |
Boolean. Overwrite if exists? Default to |
comment |
description text for named region |
Should the named region be hidden? |
|
custom_menu , description , is_function , function_group_id , help , local_name , publish_to_server , status_bar , vb_procedure , workbook_parameter , xml
|
Unknown XML feature |
... |
additional arguments |
tables |
Should included both data tables and named regions in the result? |
x |
Deprecated. Use |
You can use the wb_dims()
helper to specify the cell range of the named region
A workbook, invisibly.
A data frame with the all named regions in wb
. Or NULL
, if none are found.
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
## create named regions wb <- wb_workbook() wb$add_worksheet("Sheet 1") ## specify region wb$add_data(x = iris, start_col = 1, start_row = 1) wb$add_named_region( name = "iris", dims = wb_dims(x = iris) ) ## using add_data 'name' argument wb$add_data(sheet = 1, x = iris, name = "iris2", start_col = 10) ## delete one wb$remove_named_region(name = "iris2") wb$get_named_regions() ## read named regions df <- wb_to_df(wb, named_region = "iris") head(df) # Extract named regions from a file out_file <- temp_xlsx() wb_save(wb, out_file, overwrite = TRUE) # Load the file as a workbook first, then get named regions. wb1 <- wb_load(out_file) wb1$get_named_regions()
## create named regions wb <- wb_workbook() wb$add_worksheet("Sheet 1") ## specify region wb$add_data(x = iris, start_col = 1, start_row = 1) wb$add_named_region( name = "iris", dims = wb_dims(x = iris) ) ## using add_data 'name' argument wb$add_data(sheet = 1, x = iris, name = "iris2", start_col = 10) ## delete one wb$remove_named_region(name = "iris2") wb$get_named_regions() ## read named regions df <- wb_to_df(wb, named_region = "iris") head(df) # Extract named regions from a file out_file <- temp_xlsx() wb_save(wb, out_file, overwrite = TRUE) # Load the file as a workbook first, then get named regions. wb1 <- wb_load(out_file) wb1$get_named_regions()
The openxlsx2 package allows the user to set global options to simplify formatting:
If the built-in defaults don't suit you, set one or more of these options.
Typically, this is done in the .Rprofile
startup file
options("openxlsx2.borderColor" = "black")
options("openxlsx2.borderStyle" = "thin")
options("openxlsx2.dateFormat" = "mm/dd/yyyy")
options("openxlsx2.datetimeFormat" = "yyyy-mm-dd hh:mm:ss")
options("openxlsx2.maxWidth" = NULL)
(Maximum width allowed in Excel is 250)
options("openxlsx2.minWidth" = NULL)
options("openxlsx2.numFmt" = NULL)
options("openxlsx2.paperSize" = 9)
corresponds to a A4 paper size
options("openxlsx2.orientation" = "portrait")
page orientation
options("openxlsx2.sheet.default_name" = "Sheet")
options("openxlsx2.rightToLeft" = NULL)
options("openxlsx2.soon_deprecated" = FALSE)
Set to TRUE
if you want a
warning if using some functions deprecated recently in openxlsx2
options("openxlsx2.creator")
A default name for the creator of new
wbWorkbook
object with wb_workbook()
or new comments with wb_add_comment()
options("openxlsx2.thread_id")
the default person id when adding a threaded comment
to a cell with wb_add_thread()
options("openxlsx2.accountingFormat" = 4)
options("openxlsx2.currencyFormat" = 4)
options("openxlsx2.commaFormat" = 3)
options("openxlsx2.percentageFormat" = 10)
options("openxlsx2.scientificFormat" = 48)
options("openxlsx2.string_nums" = TRUE)
numerics in character columns
will be converted. "1"
will be written as 1
options("openxlsx2.na.strings" = "#N/A")
consulted by write_xlsx()
,
wb_add_data()
and wb_add_data_table()
.
options("openxlsx2.compression_level" = 6)
compression level for the output file. Increasing compression and time consumed from 1-9.
These functions are provided for compatibility with older versions of openxlsx2
,
and may be defunct as soon as the next release. This guide helps you update your
code to the latest standards.
As of openxlsx2 v1.0, API change should be minimal.
These functions are used internally by openxlsx2. It is no longer advertised to use them in scripts. They originate from openxlsx, but do not fit openxlsx2's API.
You should be able to modify
You should be able to change those with minimal changes
First of all, you can set an option that will add warnings when using deprecated functions.
options("openxlsx2.soon_deprecated" = TRUE)
For consistency, arguments were renamed to snake_case for the 0.8 release.
It is now recommended to use dims
(the cell range) in favor of row
, col
, start_row
, start_col
See wb_dims()
as it provides many options on how to provide cell range
These functions were renamed for consistency.
wb_get_named_regions()
will no longer allow providing a file.
## Before wb_get_named_regions(file) ## Now wb <- wb_load(file) wb_get_named_regions(wb) # also possible wb_load(file)$get_named_regions()`
Adds a person to a workbook, so that they can be the author of threaded
comments in a workbook with wb_add_thread()
wb_add_person(wb, name = NULL, id = NULL, user_id = NULL, provider_id = "None") wb_get_person(wb, name = NULL)
wb_add_person(wb, name = NULL, id = NULL, user_id = NULL, provider_id = "None") wb_get_person(wb, name = NULL)
wb |
a Workbook |
name |
the name of the person to display. |
id |
(optional) the display id |
user_id |
(optional) the user id |
provider_id |
(optional) the provider id |
print pugi_xml
## S3 method for class 'pugi_xml' print(x, indent = " ", raw = FALSE, attr_indent = FALSE, ...)
## S3 method for class 'pugi_xml' print(x, indent = " ", raw = FALSE, attr_indent = FALSE, ...)
x |
something to print |
indent |
indent used default is " " |
raw |
print as raw text |
attr_indent |
print attributes indented on new line |
... |
to please check |
# a pointer x <- read_xml("<a><b/></a>") print(x) print(x, raw = TRUE)
# a pointer x <- read_xml("<a><b/></a>") print(x) print(x, raw = TRUE)
This function is useful for workbooks that are loaded. It can be used to set the
workbook title
, subject
and category
field. Use wb_workbook()
to easily set these properties with a new workbook.
wb_get_properties(wb) wb_set_properties( wb, creator = NULL, title = NULL, subject = NULL, category = NULL, datetime_created = NULL, datetime_modified = NULL, modifier = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, custom = NULL )
wb_get_properties(wb) wb_set_properties( wb, creator = NULL, title = NULL, subject = NULL, category = NULL, datetime_created = NULL, datetime_modified = NULL, modifier = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, custom = NULL )
wb |
A Workbook object |
creator |
Creator of the workbook (your name). Defaults to login username or |
title , subject , category , keywords , comments , manager , company
|
Workbook property, a string. |
datetime_created |
The time of the workbook is created |
datetime_modified |
The time of the workbook was last modified |
modifier |
A character string indicating who was the last person to modify the workbook |
custom |
A named vector of custom properties added to the workbook |
To set properties, the following XML core properties are used.
title = dc:title
subject = dc:subject
creator = dc:creator
keywords = cp:keywords
comments = dc:description
modifier = cp:lastModifiedBy
datetime_created = dcterms:created
datetime_modified = dcterms:modified
category = cp:category
In addition, manager and company are used.
A wbWorkbook object, invisibly.
file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb <- wb_load(file) wb$get_properties() # Add a title to properties wb$set_properties(title = "my title") wb$get_properties()
file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb <- wb_load(file) wb$get_properties() # Add a title to properties wb$set_properties(title = "my title") wb$get_properties()
returns xml values as character
xml_node(xml, level1 = NULL, level2 = NULL, level3 = NULL, ...) xml_node_name(xml, level1 = NULL, level2 = NULL, ...) xml_value(xml, level1 = NULL, level2 = NULL, level3 = NULL, ...) xml_attr(xml, level1 = NULL, level2 = NULL, level3 = NULL, ...)
xml_node(xml, level1 = NULL, level2 = NULL, level3 = NULL, ...) xml_node_name(xml, level1 = NULL, level2 = NULL, ...) xml_value(xml, level1 = NULL, level2 = NULL, level3 = NULL, ...) xml_attr(xml, level1 = NULL, level2 = NULL, level3 = NULL, ...)
xml |
something xml |
level1 |
to please check |
level2 |
to please check |
level3 |
to please check |
... |
additional arguments passed to |
This function returns XML nodes as used in openxlsx2. In theory they could be returned as pointers as well, but this has not yet been implemented. If no level is provided, the nodes on level1 are returned
x <- read_xml("<a><b/></a>") # return a xml_node(x, "a") # return b. requires the path to the node xml_node(x, "a", "b") xml_node_name("<a/>") xml_node_name("<a><b/></a>", "a") x <- read_xml("<a>1</a>") xml_value(x, "a") x <- read_xml("<a><b r=\"1\">2</b></a>") xml_value(x, "a", "b") x <- read_xml("<a a=\"1\" b=\"2\">1</a>") xml_attr(x, "a") x <- read_xml("<a><b r=\"1\">2</b></a>") xml_attr(x, "a", "b") x <- read_xml("<a a=\"1\" b=\"2\">1</a>") xml_attr(x, "a") x <- read_xml("<b><a a=\"1\" b=\"2\"/></b>") xml_attr(x, "b", "a")
x <- read_xml("<a><b/></a>") # return a xml_node(x, "a") # return b. requires the path to the node xml_node(x, "a", "b") xml_node_name("<a/>") xml_node_name("<a><b/></a>", "a") x <- read_xml("<a>1</a>") xml_value(x, "a") x <- read_xml("<a><b r=\"1\">2</b></a>") xml_value(x, "a", "b") x <- read_xml("<a a=\"1\" b=\"2\">1</a>") xml_attr(x, "a") x <- read_xml("<a><b r=\"1\">2</b></a>") xml_attr(x, "a", "b") x <- read_xml("<a a=\"1\" b=\"2\">1</a>") xml_attr(x, "a") x <- read_xml("<b><a a=\"1\" b=\"2\"/></b>") xml_attr(x, "b", "a")
read xml file
read_xml( xml, pointer = TRUE, escapes = FALSE, declaration = FALSE, whitespace = TRUE, empty_tags = FALSE, skip_control = TRUE )
read_xml( xml, pointer = TRUE, escapes = FALSE, declaration = FALSE, whitespace = TRUE, empty_tags = FALSE, skip_control = TRUE )
xml |
something to read character string or file |
pointer |
should a pointer be returned? |
escapes |
bool if characters like "&" should be escaped. The default is no escapes. Assuming that the input already provides valid information. |
declaration |
should the declaration be imported |
whitespace |
should whitespace pcdata be imported |
empty_tags |
should |
skip_control |
should whitespace character be exported |
Read xml files or strings to pointer and checks if the input is valid XML. If the input is read into a character object, it will be reevaluated every time it is called. A pointer is evaluated once, but lives only for the lifetime of the R session or once it is gc().
# a pointer x <- read_xml("<a><b/></a>") print(x) print(x, raw = TRUE) str(x) # a character y <- read_xml("<a><b/></a>", pointer = FALSE) print(y) print(y, raw = TRUE) str(y) # Errors if the import was unsuccessful try(z <- read_xml("<a><b/>")) xml <- '<?xml test="yay" ?><a>A & B</a>' # difference in escapes read_xml(xml, escapes = TRUE, pointer = FALSE) read_xml(xml, escapes = FALSE, pointer = FALSE) read_xml(xml, escapes = TRUE) read_xml(xml, escapes = FALSE) # read declaration read_xml(xml, declaration = TRUE)
# a pointer x <- read_xml("<a><b/></a>") print(x) print(x, raw = TRUE) str(x) # a character y <- read_xml("<a><b/></a>", pointer = FALSE) print(y) print(y, raw = TRUE) str(y) # Errors if the import was unsuccessful try(z <- read_xml("<a><b/>")) xml <- '<?xml test="yay" ?><a>A & B</a>' # difference in escapes read_xml(xml, escapes = TRUE, pointer = FALSE) read_xml(xml, escapes = FALSE, pointer = FALSE) read_xml(xml, escapes = TRUE) read_xml(xml, escapes = FALSE) # read declaration read_xml(xml, declaration = TRUE)
Set / remove custom worksheet row heights
wb_set_row_heights( wb, sheet = current_sheet(), rows, heights = NULL, hidden = FALSE ) wb_remove_row_heights(wb, sheet = current_sheet(), rows)
wb_set_row_heights( wb, sheet = current_sheet(), rows, heights = NULL, hidden = FALSE ) wb_remove_row_heights(wb, sheet = current_sheet(), rows)
wb |
A wbWorkbook object |
sheet |
A name or index of a worksheet. (A vector is accepted for |
rows |
Indices of rows to set / remove (if any) custom height. |
heights |
Heights to set |
Option to hide rows. A logical vector of length 1 or length of |
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
## 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) ## remove any custom row heights in row 1 wb$remove_row_heights(sheet = 1, rows = 1)
## 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) ## remove any custom row heights in row 1 wb$remove_row_heights(sheet = 1, rows = 1)
Gets / Sets the worksheet names for a wbWorkbook object.
wb_set_sheet_names(wb, old = NULL, new) wb_get_sheet_names(wb, escape = FALSE)
wb_set_sheet_names(wb, old = NULL, new) wb_get_sheet_names(wb, escape = FALSE)
wb |
A wbWorkbook object |
old |
The name (or index) of the old sheet name. If |
new |
The name of the new sheet |
escape |
Should the xml special characters be escaped? |
This only changes the sheet name as shown in spreadsheet software and will not alter it elsewhere. Not in formulas, chart references, named regions, pivot tables or anywhere else.
set_
: The wbWorkbook
object.
get_
: A named character vector of sheet names in order. The
names represent the original value of the worksheet prior to any character
substitutions.
Get and set worksheet visible state. This allows to hide worksheets from the workbook.
The visibility of a worksheet can either be "visible", "hidden", or "veryHidden".
You can set this when creating a worksheet with wb_add_worksheet(visible = FALSE)
wb_get_sheet_visibility(wb) wb_set_sheet_visibility(wb, sheet = current_sheet(), value)
wb_get_sheet_visibility(wb) wb_set_sheet_visibility(wb, sheet = current_sheet(), value)
wb |
A |
sheet |
Worksheet identifier |
value |
a logical/character vector the same length as sheet, if providing a character vector, you can provide any of "hidden", "visible", or "veryHidden" |
wb_set_sheet_visibility
: The Workbook object, invisibly.
wb_get_sheet_visibility()
: A character vector of the worksheet visibility value
wb <- wb_workbook() wb$add_worksheet(sheet = "S1", visible = FALSE) wb$add_worksheet(sheet = "S2", visible = TRUE) wb$add_worksheet(sheet = "S3", visible = FALSE) wb$get_sheet_visibility() wb$set_sheet_visibility(1, TRUE) ## show sheet 1 wb$set_sheet_visibility(2, FALSE) ## hide sheet 2 wb$set_sheet_visibility(3, "hidden") ## hide sheet 3 wb$set_sheet_visibility(3, "veryHidden") ## hide sheet 3 from UI
wb <- wb_workbook() wb$add_worksheet(sheet = "S1", visible = FALSE) wb$add_worksheet(sheet = "S2", visible = TRUE) wb$add_worksheet(sheet = "S3", visible = FALSE) wb$get_sheet_visibility() wb$set_sheet_visibility(1, TRUE) ## show sheet 1 wb$set_sheet_visibility(2, FALSE) ## hide sheet 2 wb$set_sheet_visibility(3, "hidden") ## hide sheet 3 wb$set_sheet_visibility(3, "veryHidden") ## hide sheet 3 from UI
Get all styles on a sheet
styles_on_sheet(wb, sheet)
styles_on_sheet(wb, sheet)
wb |
workbook |
sheet |
worksheet |
helper function to create temporary directory for testing purpose
temp_xlsx(name = "temp_xlsx", macros = FALSE)
temp_xlsx(name = "temp_xlsx", macros = FALSE)
name |
for the temp file |
macros |
logical if the file extension is xlsm or xlsx |
openxlsx2
waiversWaiver functions for openxlsx2
functions.
current_sheet()
uses wb_get_active_sheet()
by default if performing
actions on a worksheet, for example when you add data.
next_sheet()
is used when you add a new worksheet, a new chartsheet or
when you add a pivot table
current_sheet() next_sheet() na_strings()
current_sheet() next_sheet() na_strings()
An object of class openxlsx2_waiver
wb wrapper to create borders for cell regions.
wb_add_border( wb, sheet = current_sheet(), dims = "A1", bottom_color = wb_color(hex = "FF000000"), left_color = wb_color(hex = "FF000000"), right_color = wb_color(hex = "FF000000"), top_color = wb_color(hex = "FF000000"), bottom_border = "thin", left_border = "thin", right_border = "thin", top_border = "thin", inner_hgrid = NULL, inner_hcolor = NULL, inner_vgrid = NULL, inner_vcolor = NULL, ... )
wb_add_border( wb, sheet = current_sheet(), dims = "A1", bottom_color = wb_color(hex = "FF000000"), left_color = wb_color(hex = "FF000000"), right_color = wb_color(hex = "FF000000"), top_color = wb_color(hex = "FF000000"), bottom_border = "thin", left_border = "thin", right_border = "thin", top_border = "thin", inner_hgrid = NULL, inner_hcolor = NULL, inner_vgrid = NULL, inner_vcolor = NULL, ... )
wb |
A |
sheet |
A worksheet |
dims |
Cell range in the worksheet e.g. "A1", "A1:A5", "A1:H5" |
bottom_color , left_color , right_color , top_color , inner_hcolor , inner_vcolor
|
a color, either something openxml knows or some RGB color |
left_border , right_border , top_border , bottom_border , inner_hgrid , inner_vgrid
|
the border style, if |
... |
additional arguments |
Other styles:
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb <- wb_add_border(wb, 1, dims = "A1:K1", left_border = NULL, right_border = NULL, top_border = NULL, bottom_border = "double") wb <- wb_add_border(wb, 1, dims = "A5", left_border = "dotted", right_border = "dotted", top_border = "hair", bottom_border = "thick") wb <- wb_add_border(wb, 1, dims = "C2:C5") wb <- wb_add_border(wb, 1, dims = "G2:H3") wb <- wb_add_border(wb, 1, dims = "G12:H13", left_color = wb_color(hex = "FF9400D3"), right_color = wb_color(hex = "FF4B0082"), top_color = wb_color(hex = "FF0000FF"), bottom_color = wb_color(hex = "FF00FF00")) wb <- wb_add_border(wb, 1, dims = "A20:C23") wb <- wb_add_border(wb, 1, dims = "B12:D14", left_color = wb_color(hex = "FFFFFF00"), right_color = wb_color(hex = "FFFF7F00"), bottom_color = wb_color(hex = "FFFF0000")) wb <- wb_add_border(wb, 1, dims = "D28:E28") # With chaining wb <- wb_workbook() wb$add_worksheet("S1")$add_data("S1", mtcars) wb$add_border(1, dims = "A1:K1", left_border = NULL, right_border = NULL, top_border = NULL, bottom_border = "double") wb$add_border(1, dims = "A5", left_border = "dotted", right_border = "dotted", top_border = "hair", bottom_border = "thick") wb$add_border(1, dims = "C2:C5") wb$add_border(1, dims = "G2:H3") wb$add_border(1, dims = "G12:H13", left_color = wb_color(hex = "FF9400D3"), right_color = wb_color(hex = "FF4B0082"), top_color = wb_color(hex = "FF0000FF"), bottom_color = wb_color(hex = "FF00FF00")) wb$add_border(1, dims = "A20:C23") wb$add_border(1, dims = "B12:D14", left_color = wb_color(hex = "FFFFFF00"), right_color = wb_color(hex = "FFFF7F00"), bottom_color = wb_color(hex = "FFFF0000")) wb$add_border(1, dims = "D28:E28") # if (interactive()) wb$open() wb <- wb_workbook() wb$add_worksheet("S1")$add_data("S1", mtcars) wb$add_border(1, dims = "A2:K33", inner_vgrid = "thin", inner_vcolor = c(rgb="FF808080"))
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb <- wb_add_border(wb, 1, dims = "A1:K1", left_border = NULL, right_border = NULL, top_border = NULL, bottom_border = "double") wb <- wb_add_border(wb, 1, dims = "A5", left_border = "dotted", right_border = "dotted", top_border = "hair", bottom_border = "thick") wb <- wb_add_border(wb, 1, dims = "C2:C5") wb <- wb_add_border(wb, 1, dims = "G2:H3") wb <- wb_add_border(wb, 1, dims = "G12:H13", left_color = wb_color(hex = "FF9400D3"), right_color = wb_color(hex = "FF4B0082"), top_color = wb_color(hex = "FF0000FF"), bottom_color = wb_color(hex = "FF00FF00")) wb <- wb_add_border(wb, 1, dims = "A20:C23") wb <- wb_add_border(wb, 1, dims = "B12:D14", left_color = wb_color(hex = "FFFFFF00"), right_color = wb_color(hex = "FFFF7F00"), bottom_color = wb_color(hex = "FFFF0000")) wb <- wb_add_border(wb, 1, dims = "D28:E28") # With chaining wb <- wb_workbook() wb$add_worksheet("S1")$add_data("S1", mtcars) wb$add_border(1, dims = "A1:K1", left_border = NULL, right_border = NULL, top_border = NULL, bottom_border = "double") wb$add_border(1, dims = "A5", left_border = "dotted", right_border = "dotted", top_border = "hair", bottom_border = "thick") wb$add_border(1, dims = "C2:C5") wb$add_border(1, dims = "G2:H3") wb$add_border(1, dims = "G12:H13", left_color = wb_color(hex = "FF9400D3"), right_color = wb_color(hex = "FF4B0082"), top_color = wb_color(hex = "FF0000FF"), bottom_color = wb_color(hex = "FF00FF00")) wb$add_border(1, dims = "A20:C23") wb$add_border(1, dims = "B12:D14", left_color = wb_color(hex = "FFFFFF00"), right_color = wb_color(hex = "FFFF7F00"), bottom_color = wb_color(hex = "FFFF0000")) wb$add_border(1, dims = "D28:E28") # if (interactive()) wb$open() wb <- wb_workbook() wb$add_worksheet("S1")$add_data("S1", mtcars) wb$add_border(1, dims = "A2:K33", inner_vgrid = "thin", inner_vcolor = c(rgb="FF808080"))
Add cell style to a cell region
wb_add_cell_style( wb, sheet = current_sheet(), dims = "A1", apply_alignment = NULL, apply_border = NULL, apply_fill = NULL, apply_font = NULL, apply_number_format = NULL, apply_protection = NULL, border_id = NULL, ext_lst = NULL, fill_id = NULL, font_id = NULL, hidden = NULL, horizontal = NULL, indent = NULL, justify_last_line = NULL, locked = NULL, num_fmt_id = NULL, pivot_button = NULL, quote_prefix = NULL, reading_order = NULL, relative_indent = NULL, shrink_to_fit = NULL, text_rotation = NULL, vertical = NULL, wrap_text = NULL, xf_id = NULL, ... )
wb_add_cell_style( wb, sheet = current_sheet(), dims = "A1", apply_alignment = NULL, apply_border = NULL, apply_fill = NULL, apply_font = NULL, apply_number_format = NULL, apply_protection = NULL, border_id = NULL, ext_lst = NULL, fill_id = NULL, font_id = NULL, hidden = NULL, horizontal = NULL, indent = NULL, justify_last_line = NULL, locked = NULL, num_fmt_id = NULL, pivot_button = NULL, quote_prefix = NULL, reading_order = NULL, relative_indent = NULL, shrink_to_fit = NULL, text_rotation = NULL, vertical = NULL, wrap_text = NULL, xf_id = NULL, ... )
wb |
a workbook |
sheet |
the worksheet |
dims |
the cell range |
apply_alignment |
logical apply alignment |
apply_border |
logical apply border |
apply_fill |
logical apply fill |
apply_font |
logical apply font |
apply_number_format |
logical apply number format |
apply_protection |
logical apply protection |
border_id |
border ID to apply |
ext_lst |
extension list something like |
fill_id |
fill ID to apply |
font_id |
font ID to apply |
logical cell is hidden |
|
horizontal |
align content horizontal ('general', 'left', 'center', 'right', 'fill', 'justify', 'centerContinuous', 'distributed') |
indent |
logical indent content |
justify_last_line |
logical justify last line |
locked |
logical cell is locked |
num_fmt_id |
number format ID to apply |
pivot_button |
unknown |
quote_prefix |
unknown |
reading_order |
reading order left to right |
relative_indent |
relative indentation |
shrink_to_fit |
logical shrink to fit |
text_rotation |
degrees of text rotation |
vertical |
vertical alignment of content ('top', 'center', 'bottom', 'justify', 'distributed') |
wrap_text |
wrap text in cell |
xf_id |
xf ID to apply |
... |
additional arguments |
The wbWorkbook
object, invisibly
Other styles:
wb_add_border()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", x = mtcars) wb %>% wb_add_cell_style( dims = "A1:K1", text_rotation = "45", horizontal = "center", vertical = "center", wrap_text = "1" ) # Chaining wb <- wb_workbook()$add_worksheet("S1")$add_data(x = mtcars) wb$add_cell_style(dims = "A1:K1", text_rotation = "45", horizontal = "center", vertical = "center", wrap_text = "1")
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", x = mtcars) wb %>% wb_add_cell_style( dims = "A1:K1", text_rotation = "45", horizontal = "center", vertical = "center", wrap_text = "1" ) # Chaining wb <- wb_workbook()$add_worksheet("S1")$add_data(x = mtcars) wb$add_cell_style(dims = "A1:K1", text_rotation = "45", horizontal = "center", vertical = "center", wrap_text = "1")
Add a chart XML to a worksheet
wb_add_chart_xml( wb, sheet = current_sheet(), dims = NULL, xml, col_offset = 0, row_offset = 0, ... )
wb_add_chart_xml( wb, sheet = current_sheet(), dims = NULL, xml, col_offset = 0, row_offset = 0, ... )
wb |
a workbook |
sheet |
the sheet on which the graph will appear |
dims |
the dimensions where the sheet will appear |
xml |
chart xml |
col_offset , row_offset
|
positioning |
... |
additional arguments |
wb_add_drawing()
wb_add_image()
wb_add_mschart()
wb_add_plot()
A chartsheet is a special type of sheet that handles charts output. You must add a chart to the sheet. Otherwise, this will break the workbook.
wb_add_chartsheet( wb, sheet = next_sheet(), tab_color = NULL, zoom = 100, visible = c("true", "false", "hidden", "visible", "veryhidden"), ... )
wb_add_chartsheet( wb, sheet = next_sheet(), tab_color = NULL, zoom = 100, visible = c("true", "false", "hidden", "visible", "veryhidden"), ... )
wb |
A Workbook object to attach the new chartsheet |
sheet |
A name for the new chartsheet |
tab_color |
Color of the sheet tab. A |
zoom |
The sheet zoom level, a numeric between 10 and 400 as a percentage. (A zoom value smaller than 10 will default to 10.) |
visible |
If |
... |
Additional arguments |
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Add comment to worksheet
wb_add_comment(wb, sheet = current_sheet(), dims = "A1", comment, ...) wb_get_comment(wb, sheet = current_sheet(), dims = NULL) wb_remove_comment(wb, sheet = current_sheet(), dims = "A1", ...)
wb_add_comment(wb, sheet = current_sheet(), dims = "A1", comment, ...) wb_get_comment(wb, sheet = current_sheet(), dims = NULL) wb_remove_comment(wb, sheet = current_sheet(), dims = "A1", ...)
wb |
A workbook object |
sheet |
A worksheet of the workbook |
dims |
Optional row and column as spreadsheet dimension, e.g. "A1" |
comment |
A comment to apply to |
... |
additional arguments |
If applying a comment
with a string, it will use wb_comment()
default values. If additional background colors are applied, RGB colors should be provided, either as hex code or with builtin R colors. The alpha channel is ignored.
The Workbook object, invisibly.
wb <- wb_workbook() wb$add_worksheet("Sheet 1") # add a comment without author c1 <- wb_comment(text = "this is a comment", author = "") wb$add_comment(dims = "B10", comment = c1) #' # Remove comment wb$remove_comment(sheet = "Sheet 1", dims = "B10") # Write another comment with author information c2 <- wb_comment(text = "this is another comment", author = "Marco Polo", visible = TRUE) wb$add_comment(sheet = 1, dims = "C10", comment = c2) # Works with formatted text also. formatted_text <- fmt_txt("bar", underline = TRUE) wb$add_comment(dims = "B5", comment = formatted_text) # With background color wb$add_comment(dims = "B7", comment = formatted_text, color = wb_color("green")) # With background image. File extension must be png or jpeg, not jpg? tmp <- tempfile(fileext = ".png") png(file = tmp, bg = "transparent") plot(1:10) rect(1, 5, 3, 7, col = "white") dev.off() c1 <- wb_comment(text = "this is a comment", author = "", visible = TRUE) wb$add_comment(dims = "B12", comment = c1, file = tmp)
wb <- wb_workbook() wb$add_worksheet("Sheet 1") # add a comment without author c1 <- wb_comment(text = "this is a comment", author = "") wb$add_comment(dims = "B10", comment = c1) #' # Remove comment wb$remove_comment(sheet = "Sheet 1", dims = "B10") # Write another comment with author information c2 <- wb_comment(text = "this is another comment", author = "Marco Polo", visible = TRUE) wb$add_comment(sheet = 1, dims = "C10", comment = c2) # Works with formatted text also. formatted_text <- fmt_txt("bar", underline = TRUE) wb$add_comment(dims = "B5", comment = formatted_text) # With background color wb$add_comment(dims = "B7", comment = formatted_text, color = wb_color("green")) # With background image. File extension must be png or jpeg, not jpg? tmp <- tempfile(fileext = ".png") png(file = tmp, bg = "transparent") plot(1:10) rect(1, 5, 3, 7, col = "white") dev.off() c1 <- wb_comment(text = "this is a comment", author = "", visible = TRUE) wb$add_comment(dims = "B12", comment = c1, file = tmp)
Add conditional formatting to cells.
You can find more details in vignette("conditional-formatting")
.
wb_add_conditional_formatting( wb, sheet = current_sheet(), dims = NULL, rule = NULL, style = NULL, type = c("expression", "colorScale", "dataBar", "iconSet", "duplicatedValues", "uniqueValues", "containsErrors", "notContainsErrors", "containsBlanks", "notContainsBlanks", "containsText", "notContainsText", "beginsWith", "endsWith", "between", "topN", "bottomN"), params = list(showValue = TRUE, gradient = TRUE, border = TRUE, percent = FALSE, rank = 5L), ... ) wb_remove_conditional_formatting( wb, sheet = current_sheet(), dims = NULL, first = FALSE, last = FALSE )
wb_add_conditional_formatting( wb, sheet = current_sheet(), dims = NULL, rule = NULL, style = NULL, type = c("expression", "colorScale", "dataBar", "iconSet", "duplicatedValues", "uniqueValues", "containsErrors", "notContainsErrors", "containsBlanks", "notContainsBlanks", "containsText", "notContainsText", "beginsWith", "endsWith", "between", "topN", "bottomN"), params = list(showValue = TRUE, gradient = TRUE, border = TRUE, percent = FALSE, rank = 5L), ... ) wb_remove_conditional_formatting( wb, sheet = current_sheet(), dims = NULL, first = FALSE, last = FALSE )
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
dims |
A cell or cell range like "A1" or "A1:B2" |
rule |
The condition under which to apply the formatting. See Examples. |
style |
A name of a style to apply to those cells that satisfy the rule. See |
type |
The type of conditional formatting rule to apply. One of |
params |
A list of additional parameters passed. See Details for more. |
... |
additional arguments |
first |
remove the first conditional formatting |
last |
remove the last conditional formatting |
openxml uses the alpha channel first then RGB, whereas the usual default is RGBA.
Conditional formatting type
accept different parameters. Unless noted,
unlisted parameters are ignored.
expression
[style]
A Style
object[rule]
An Excel expression (as a character). Valid operators are: <
, <=
, >
, >=
, ==
, !=
colorScale
[style]
A character
vector of valid colors with length 2
or 3
[rule]
NULL
or a character
vector of valid colors of equal length to styles
dataBar
[style]
A character
vector of valid colors with length 2
or 3
[rule]
A numeric
vector specifying the range of the databar colors. Must be equal length to style
[params$showValue]
If FALSE
the cell value is hidden. Default TRUE
[params$gradient]
If FALSE
color gradient is removed. Default TRUE
[params$border]
If FALSE
the border around the database is hidden. Default TRUE
duplicatedValues
/ uniqueValues
/ containsErrors
[style]
A Style
object
contains
[style]
A Style
object[rule]
The text to look for within cells
between
[style]
A Style
object.[rule]
A numeric
vector of length 2
specifying lower and upper bound (Inclusive)
topN
[style]
A Style
object[params$rank]
A numeric
vector of length 1
indicating number of highest values. Default 5L
[params$percent]
If TRUE
, uses percentage
bottomN
[style]
A Style
object[params$rank]
A numeric
vector of length 1
indicating number of lowest values. Default 5L
[params$percent]
If TRUE
, uses percentage
iconSet
[params$showValue]
If FALSE
, the cell value is hidden. Default TRUE
[params$reverse]
If TRUE
, the order is reversed. Default FALSE
[params$percent]
If TRUE
, uses percentage[params$iconSet]
Uses one of the implemented icon sets. Values must match the length of the icons
in the set 3Arrows, 3ArrowsGray, 3Flags, 3Signs, 3Stars, 3Symbols, 3Symbols2, 3TrafficLights1, 3TrafficLights2,
3Triangles, 4Arrows, 4ArrowsGray, 4Rating, 4RedToBlack, 4TrafficLights, 5Arrows, 5ArrowsGray, 5Boxes, 5Quarters, 5Rating.
The default is 3TrafficLights1.
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
wb <- wb_workbook() wb$add_worksheet("a") wb$add_data(x = 1:4, col_names = FALSE) wb$add_conditional_formatting(dims = wb_dims(cols = "A", rows = 1:4), rule = ">2")
wb <- wb_workbook() wb$add_worksheet("a") wb$add_data(x = 1:4, col_names = FALSE) wb$add_conditional_formatting(dims = wb_dims(cols = "A", rows = 1:4), rule = ">2")
Add data to worksheet with optional styling.
wb_add_data( wb, sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, array = FALSE, col_names = TRUE, row_names = FALSE, with_filter = FALSE, name = NULL, sep = ", ", apply_cell_style = TRUE, remove_cell_style = FALSE, na.strings = na_strings(), inline_strings = TRUE, enforce = FALSE, ... )
wb_add_data( wb, sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, array = FALSE, col_names = TRUE, row_names = FALSE, with_filter = FALSE, name = NULL, sep = ", ", apply_cell_style = TRUE, remove_cell_style = FALSE, na.strings = na_strings(), inline_strings = TRUE, enforce = FALSE, ... )
wb |
A Workbook object containing a worksheet. |
sheet |
The worksheet to write to. Can be the worksheet index or name. |
x |
Object to be written. For classes supported look at the examples. |
dims |
Spreadsheet cell range that will determine |
start_col |
A vector specifying the starting column to write |
start_row |
A vector specifying the starting row to write |
array |
A bool if the function written is of type array |
col_names |
If |
row_names |
If |
with_filter |
If |
name |
The name of a named region if specified. |
sep |
Only applies to list columns. The separator used to collapse list
columns to a character vector e.g. |
apply_cell_style |
Should we write cell styles to the workbook |
remove_cell_style |
keep the cell style? |
na.strings |
Value used for replacing |
inline_strings |
write characters as inline strings |
enforce |
enforce that selected dims is filled. For this to work, |
... |
additional arguments |
Formulae written using wb_add_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.
Supported classes are data frames, matrices and vectors of various types and
everything that can be converted into a data frame with as.data.frame()
.
Everything else that the user wants to write should either be converted into
a vector or data frame or written in vector or data frame segments. This
includes base classes such as table
, which were coerced internally in the
predecessor of this package.
Even vectors and data frames can consist of different classes. Many base
classes are covered, though not all and far from all third-party classes.
When data of an unknown class is written, it is handled with as.character()
.
It is not possible to write character nodes beginning with <r>
or <r/>
. Both
are reserved for internal functions. If you need these. You have to wrap
the input string in fmt_txt()
.
The columns of x
with class Date/POSIXt, currency, accounting, hyperlink,
percentage are automatically styled as dates, currency, accounting,
hyperlinks, percentages respectively.
Functions wb_add_data()
and wb_add_data_table()
behave quite similar. The
distinction is that the latter creates a table in the worksheet that can be
used for different kind of formulas and can be sorted independently, though
is less flexible than basic cell regions.
A wbWorkbook
, invisibly.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
## See formatting vignette for further examples. ## Options for default styling (These are the defaults) options("openxlsx2.dateFormat" = "mm/dd/yyyy") options("openxlsx2.datetimeFormat" = "yyyy-mm-dd hh:mm:ss") options("openxlsx2.numFmt" = NULL) ############################################################################# ## Create Workbook object and add worksheets wb <- wb_workbook() ## Add worksheets wb$add_worksheet("Cars") wb$add_worksheet("Formula") x <- mtcars[1:6, ] wb$add_data("Cars", x, start_col = 2, start_row = 3, row_names = TRUE) ############################################################################# ## Hyperlinks ## - vectors/columns with class 'hyperlink' are written as hyperlinks' v <- rep("https://CRAN.R-project.org/", 4) names(v) <- paste0("Hyperlink", 1:4) # Optional: names will be used as display text class(v) <- "hyperlink" wb$add_data("Cars", x = v, dims = "B32") ############################################################################# ## Formulas ## - vectors/columns with class 'formula' are written as formulas' df <- data.frame( x = 1:3, y = 1:3, z = paste(paste0("A", 1:3 + 1L), paste0("B", 1:3 + 1L), sep = "+"), stringsAsFactors = FALSE ) class(df$z) <- c(class(df$z), "formula") wb$add_data(sheet = "Formula", x = df) ############################################################################# # update cell range and add mtcars xlsxFile <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb2 <- wb_load(xlsxFile) # read dataset with inlinestr wb_to_df(wb2) wb2 <- wb2 %>% wb_add_data(sheet = 1, mtcars, dims = wb_dims(4, 4)) wb_to_df(wb2)
## See formatting vignette for further examples. ## Options for default styling (These are the defaults) options("openxlsx2.dateFormat" = "mm/dd/yyyy") options("openxlsx2.datetimeFormat" = "yyyy-mm-dd hh:mm:ss") options("openxlsx2.numFmt" = NULL) ############################################################################# ## Create Workbook object and add worksheets wb <- wb_workbook() ## Add worksheets wb$add_worksheet("Cars") wb$add_worksheet("Formula") x <- mtcars[1:6, ] wb$add_data("Cars", x, start_col = 2, start_row = 3, row_names = TRUE) ############################################################################# ## Hyperlinks ## - vectors/columns with class 'hyperlink' are written as hyperlinks' v <- rep("https://CRAN.R-project.org/", 4) names(v) <- paste0("Hyperlink", 1:4) # Optional: names will be used as display text class(v) <- "hyperlink" wb$add_data("Cars", x = v, dims = "B32") ############################################################################# ## Formulas ## - vectors/columns with class 'formula' are written as formulas' df <- data.frame( x = 1:3, y = 1:3, z = paste(paste0("A", 1:3 + 1L), paste0("B", 1:3 + 1L), sep = "+"), stringsAsFactors = FALSE ) class(df$z) <- c(class(df$z), "formula") wb$add_data(sheet = "Formula", x = df) ############################################################################# # update cell range and add mtcars xlsxFile <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb2 <- wb_load(xlsxFile) # read dataset with inlinestr wb_to_df(wb2) wb2 <- wb2 %>% wb_add_data(sheet = 1, mtcars, dims = wb_dims(4, 4)) wb_to_df(wb2)
Add data to a worksheet and format as an Excel table.
wb_add_data_table( wb, sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, col_names = TRUE, row_names = FALSE, table_style = "TableStyleLight9", table_name = NULL, with_filter = TRUE, sep = ", ", first_column = FALSE, last_column = FALSE, banded_rows = TRUE, banded_cols = FALSE, apply_cell_style = TRUE, remove_cell_style = FALSE, na.strings = na_strings(), inline_strings = TRUE, total_row = FALSE, ... )
wb_add_data_table( wb, sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, col_names = TRUE, row_names = FALSE, table_style = "TableStyleLight9", table_name = NULL, with_filter = TRUE, sep = ", ", first_column = FALSE, last_column = FALSE, banded_rows = TRUE, banded_cols = FALSE, apply_cell_style = TRUE, remove_cell_style = FALSE, na.strings = na_strings(), inline_strings = TRUE, total_row = FALSE, ... )
wb |
A Workbook object containing a worksheet. |
sheet |
The worksheet to write to. Can be the worksheet index or name. |
x |
A data frame |
dims |
Spreadsheet cell range that will determine |
start_col |
A vector specifying the starting column to write |
start_row |
A vector specifying the starting row to write |
col_names |
If |
row_names |
If |
table_style |
Any table style name or "none" (see |
table_name |
Name of table in workbook. The table name must be unique. |
with_filter |
If |
sep |
Only applies to list columns. The separator used to collapse list
columns to a character vector e.g.
|
first_column |
logical. If |
last_column |
logical. If |
banded_rows |
logical. If |
banded_cols |
logical. If |
apply_cell_style |
Should we write cell styles to the workbook |
remove_cell_style |
keep the cell style? |
na.strings |
Value used for replacing |
inline_strings |
write characters as inline strings |
total_row |
logical. With the default |
... |
additional arguments |
Formulae written using wb_add_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.
Supported classes are data frames, matrices and vectors of various types and
everything that can be converted into a data frame with as.data.frame()
.
Everything else that the user wants to write should either be converted into
a vector or data frame or written in vector or data frame segments. This
includes base classes such as table
, which were coerced internally in the
predecessor of this package.
Even vectors and data frames can consist of different classes. Many base
classes are covered, though not all and far from all third-party classes.
When data of an unknown class is written, it is handled with as.character()
.
It is not possible to write character nodes beginning with <r>
or <r/>
. Both
are reserved for internal functions. If you need these. You have to wrap
the input string in fmt_txt()
.
The columns of x
with class Date/POSIXt, currency, accounting, hyperlink,
percentage are automatically styled as dates, currency, accounting,
hyperlinks, percentages respectively.
Functions wb_add_data()
and wb_add_data_table()
behave quite similar. The
distinction is that the latter creates a table in the worksheet that can be
used for different kind of formulas and can be sorted independently, though
is less flexible than basic cell regions.
It is possible to further tweak the total row. In addition to the default
FALSE
possible values are TRUE
(the xlsx file will create column sums
each variable).
In addition it is possible to tweak this further using a character string
with one of the following functions for each variable: "average"
,
"count"
, "countNums"
, "max"
, "min"
, "stdDev"
, "sum"
, "var"
.
It is possible to leave the cell empty "none"
or to create a text input
using a named character with name text
like: c(text = "Total")
.
It's also possible to pass other spreadsheet software functions if they
return a single value and hence "SUM"
would work too.
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
wb <- wb_workbook()$add_worksheet()$ add_data_table( x = as.data.frame(USPersonalExpenditure), row_names = TRUE, total_row = c(text = "Total", "none", "sum", "sum", "sum", "SUM") )
wb <- wb_workbook()$add_worksheet()$ add_data_table( x = as.data.frame(USPersonalExpenditure), row_names = TRUE, total_row = c(text = "Total", "none", "sum", "sum", "sum", "SUM") )
Add Excel data validation to cells
wb_add_data_validation( wb, sheet = current_sheet(), dims = "A1", type, operator, value, allow_blank = TRUE, show_input_msg = TRUE, show_error_msg = TRUE, error_style = NULL, error_title = NULL, error = NULL, prompt_title = NULL, prompt = NULL, ... )
wb_add_data_validation( wb, sheet = current_sheet(), dims = "A1", type, operator, value, allow_blank = TRUE, show_input_msg = TRUE, show_error_msg = TRUE, error_style = NULL, error_title = NULL, error = NULL, prompt_title = NULL, prompt = NULL, ... )
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
dims |
A cell dimension ("A1" or "A1:B2") |
type |
One of 'whole', 'decimal', 'date', 'time', 'textLength', 'list' (see examples) |
operator |
One of 'between', 'notBetween', 'equal', 'notEqual', 'greaterThan', 'lessThan', 'greaterThanOrEqual', 'lessThanOrEqual' |
value |
a vector of length 1 or 2 depending on operator (see examples) |
allow_blank |
logical |
show_input_msg |
logical |
show_error_msg |
logical |
error_style |
The icon shown and the options how to deal with such inputs. Default "stop" (cancel), else "information" (prompt popup) or "warning" (prompt accept or change input) |
error_title |
The error title |
error |
The error text |
prompt_title |
The prompt title |
prompt |
The prompt text |
... |
additional arguments |
wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_data_table(1, x = iris[1:30, ]) wb$add_data_validation(1, dims = "A2:C31", type = "whole", operator = "between", value = c(1, 9) ) wb$add_data_validation(1, dims = "E2:E31", type = "textLength", operator = "between", value = c(4, 6) ) ## Date and Time cell validation df <- data.frame( "d" = as.Date("2016-01-01") + -5:5, "t" = as.POSIXct("2016-01-01") + -5:5 * 10000 ) wb$add_data_table(2, x = df) wb$add_data_validation(2, dims = "A2:A12", type = "date", operator = "greaterThanOrEqual", value = as.Date("2016-01-01") ) wb$add_data_validation(2, dims = "B2:B12", type = "time", operator = "between", value = df$t[c(4, 8)] ) ###################################################################### ## If type == 'list' # operator argument is ignored. wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_data_table(sheet = 1, x = iris[1:30, ]) wb$add_data(sheet = 2, x = sample(iris$Sepal.Length, 10)) wb$add_data_validation(1, dims = "A2:A31", type = "list", value = "'Sheet 2'!$A$1:$A$10")
wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_data_table(1, x = iris[1:30, ]) wb$add_data_validation(1, dims = "A2:C31", type = "whole", operator = "between", value = c(1, 9) ) wb$add_data_validation(1, dims = "E2:E31", type = "textLength", operator = "between", value = c(4, 6) ) ## Date and Time cell validation df <- data.frame( "d" = as.Date("2016-01-01") + -5:5, "t" = as.POSIXct("2016-01-01") + -5:5 * 10000 ) wb$add_data_table(2, x = df) wb$add_data_validation(2, dims = "A2:A12", type = "date", operator = "greaterThanOrEqual", value = as.Date("2016-01-01") ) wb$add_data_validation(2, dims = "B2:B12", type = "time", operator = "between", value = df$t[c(4, 8)] ) ###################################################################### ## If type == 'list' # operator argument is ignored. wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_worksheet("Sheet 2") wb$add_data_table(sheet = 1, x = iris[1:30, ]) wb$add_data(sheet = 2, x = sample(iris$Sepal.Length, 10)) wb$add_data_validation(1, dims = "A2:A31", type = "list", value = "'Sheet 2'!$A$1:$A$10")
Add drawings to a worksheet. This requires the rvg
package.
wb_add_drawing( wb, sheet = current_sheet(), dims = "A1", xml, col_offset = 0, row_offset = 0, ... )
wb_add_drawing( wb, sheet = current_sheet(), dims = "A1", xml, col_offset = 0, row_offset = 0, ... )
wb |
A |
sheet |
A sheet in the workbook |
dims |
The dimension where the drawing is added. |
xml |
the drawing xml as character or file |
col_offset , row_offset
|
offsets for column and row |
... |
additional arguments |
wb_add_chart_xml()
wb_add_image()
wb_add_mschart()
wb_add_plot()
if (requireNamespace("rvg") && interactive()) { ## rvg example require(rvg) tmp <- tempfile(fileext = ".xml") dml_xlsx(file = tmp) plot(1,1) dev.off() wb <- wb_workbook()$ add_worksheet()$ add_drawing(xml = tmp)$ add_drawing(xml = tmp, dims = NULL) }
if (requireNamespace("rvg") && interactive()) { ## rvg example require(rvg) tmp <- tempfile(fileext = ".xml") dml_xlsx(file = tmp) plot(1,1) dev.off() wb <- wb_workbook()$ add_worksheet()$ add_drawing(xml = tmp)$ add_drawing(xml = tmp, dims = NULL) }
These styles are used with conditional formatting and custom table styles.
wb_add_dxfs_style( wb, name, font_name = NULL, font_size = NULL, font_color = NULL, num_fmt = NULL, border = NULL, border_color = wb_color(getOption("openxlsx2.borderColor", "black")), border_style = getOption("openxlsx2.borderStyle", "thin"), bg_fill = NULL, gradient_fill = NULL, text_bold = NULL, text_italic = NULL, text_underline = NULL, ... )
wb_add_dxfs_style( wb, name, font_name = NULL, font_size = NULL, font_color = NULL, num_fmt = NULL, border = NULL, border_color = wb_color(getOption("openxlsx2.borderColor", "black")), border_style = getOption("openxlsx2.borderStyle", "thin"), bg_fill = NULL, gradient_fill = NULL, text_bold = NULL, text_italic = NULL, text_underline = NULL, ... )
wb |
A Workbook object. |
name |
the style name |
font_name |
the font name |
font_size |
the font size |
font_color |
the font color (a |
num_fmt |
the number format |
border |
logical if borders are applied |
border_color |
the border color |
border_style |
the border style |
bg_fill |
any background fill |
gradient_fill |
any gradient fill |
text_bold |
logical if text is bold |
text_italic |
logical if text is italic |
text_underline |
logical if text is underlined |
... |
additional arguments passed to |
The Workbook object, invisibly
Other workbook styling functions:
base_font-wb
,
wb_add_style()
,
wb_base_colors
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_dxfs_style( name = "nay", font_color = wb_color(hex = "FF9C0006"), bg_fill = wb_color(hex = "FFFFC7CE") )
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_dxfs_style( name = "nay", font_color = wb_color(hex = "FF9C0006"), bg_fill = wb_color(hex = "FFFFC7CE") )
Add fill to a cell region.
wb_add_fill( wb, sheet = current_sheet(), dims = "A1", color = wb_color(hex = "FFFFFF00"), pattern = "solid", gradient_fill = "", every_nth_col = 1, every_nth_row = 1, ... )
wb_add_fill( wb, sheet = current_sheet(), dims = "A1", color = wb_color(hex = "FFFFFF00"), pattern = "solid", gradient_fill = "", every_nth_col = 1, every_nth_row = 1, ... )
wb |
a workbook |
sheet |
the worksheet |
dims |
the cell range |
color |
the colors to apply, e.g. yellow: wb_color(hex = "FFFFFF00") |
pattern |
various default "none" but others are possible: "solid", "mediumGray", "darkGray", "lightGray", "darkHorizontal", "darkVertical", "darkDown", "darkUp", "darkGrid", "darkTrellis", "lightHorizontal", "lightVertical", "lightDown", "lightUp", "lightGrid", "lightTrellis", "gray125", "gray0625" |
gradient_fill |
a gradient fill xml pattern. |
every_nth_col |
which col should be filled |
every_nth_row |
which row should be filled |
... |
... |
The wbWorkbook
object, invisibly
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb <- wb %>% wb_add_fill("S1", dims = "D5:J23", color = wb_color(hex = "FFFFFF00")) wb <- wb %>% wb_add_fill("S1", dims = "B22:D27", color = wb_color(hex = "FF00FF00")) wb <- wb %>% wb_add_worksheet("S2") %>% wb_add_data("S2", mtcars) gradient_fill1 <- '<gradientFill degree="90"> <stop position="0"><color rgb="FF92D050"/></stop> <stop position="1"><color rgb="FF0070C0"/></stop> </gradientFill>' wb <- wb %>% wb_add_fill("S2", dims = "A2:K5", gradient_fill = gradient_fill1) gradient_fill2 <- '<gradientFill type="path" left="0.2" right="0.8" top="0.2" bottom="0.8"> <stop position="0"><color theme="0"/></stop> <stop position="1"><color theme="4"/></stop> </gradientFill>' wb <- wb %>% wb_add_fill("S2", dims = "A7:K10", gradient_fill = gradient_fill2)
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb <- wb %>% wb_add_fill("S1", dims = "D5:J23", color = wb_color(hex = "FFFFFF00")) wb <- wb %>% wb_add_fill("S1", dims = "B22:D27", color = wb_color(hex = "FF00FF00")) wb <- wb %>% wb_add_worksheet("S2") %>% wb_add_data("S2", mtcars) gradient_fill1 <- '<gradientFill degree="90"> <stop position="0"><color rgb="FF92D050"/></stop> <stop position="1"><color rgb="FF0070C0"/></stop> </gradientFill>' wb <- wb %>% wb_add_fill("S2", dims = "A2:K5", gradient_fill = gradient_fill1) gradient_fill2 <- '<gradientFill type="path" left="0.2" right="0.8" top="0.2" bottom="0.8"> <stop position="0"><color theme="0"/></stop> <stop position="1"><color theme="4"/></stop> </gradientFill>' wb <- wb %>% wb_add_fill("S2", dims = "A7:K10", gradient_fill = gradient_fill2)
Modify the font in a cell region with more precision
You can specify the font in a cell with other cell styling functions,
but wb_add_font()
gives you more control.
wb_add_font( wb, sheet = current_sheet(), dims = "A1", name = "Aptos Narrow", color = wb_color(hex = "FF000000"), size = "11", bold = "", italic = "", outline = "", strike = "", underline = "", charset = "", condense = "", extend = "", family = "", scheme = "", shadow = "", vert_align = "", ... )
wb_add_font( wb, sheet = current_sheet(), dims = "A1", name = "Aptos Narrow", color = wb_color(hex = "FF000000"), size = "11", bold = "", italic = "", outline = "", strike = "", underline = "", charset = "", condense = "", extend = "", family = "", scheme = "", shadow = "", vert_align = "", ... )
wb |
A Workbook object |
sheet |
the worksheet |
dims |
the cell range |
name |
Font name: default "Aptos Narrow" |
color |
An object created by |
size |
Font size: default "11", |
bold |
bold, "single" or "double", default: "" |
italic |
italic |
outline |
outline |
strike |
strike |
underline |
underline |
charset |
charset |
condense |
condense |
extend |
extend |
family |
font family |
scheme |
font scheme |
shadow |
shadow |
vert_align |
vertical alignment |
... |
... |
wb_add_font()
provides all the options openxml accepts for a font node,
not all have to be set. Usually name
, size
and color
should be what the user wants.
A wbWorkbook
, invisibly
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb %>% wb_add_font("S1", "A1:K1", name = "Arial", color = wb_color(theme = "4")) # With chaining wb <- wb_workbook()$add_worksheet("S1")$add_data("S1", mtcars) wb$add_font("S1", "A1:K1", name = "Arial", color = wb_color(theme = "4"))
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb %>% wb_add_font("S1", "A1:K1", name = "Arial", color = wb_color(theme = "4")) # With chaining wb <- wb_workbook()$add_worksheet("S1")$add_data("S1", mtcars) wb$add_font("S1", "A1:K1", name = "Arial", color = wb_color(theme = "4"))
You can add Form Control to a cell. The three supported types are a Checkbox, a Radio button, or a Drop menu.
wb_add_form_control( wb, sheet = current_sheet(), dims = "A1", type = c("Checkbox", "Radio", "Drop"), text = NULL, link = NULL, range = NULL, checked = FALSE )
wb_add_form_control( wb, sheet = current_sheet(), dims = "A1", type = c("Checkbox", "Radio", "Drop"), text = NULL, link = NULL, range = NULL, checked = FALSE )
wb |
A Workbook object |
sheet |
A worksheet of the workbook |
dims |
A single cell as spreadsheet dimension, e.g. "A1". |
type |
A type "Checkbox" (the default), "Radio" a radio button or "Drop" a drop down menu |
text |
A text to be shown next to the Checkbox or radio button (optional) |
link |
A cell range to link to |
range |
A cell range used as input |
checked |
A logical indicating if the Checkbox or Radio button is checked |
The wbWorkbook
object, invisibly.
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_form_control() # Add wb$add_form_control(dims = "C5", type = "Radio", checked = TRUE)
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_form_control() # Add wb$add_form_control(dims = "C5", type = "Radio", checked = TRUE)
This function can be used to add a formula to a worksheet.
In wb_add_formula()
, you can provide the formula as a character vector.
wb_add_formula( wb, sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, array = FALSE, cm = FALSE, apply_cell_style = TRUE, remove_cell_style = FALSE, enforce = FALSE, shared = FALSE, name = NULL, ... )
wb_add_formula( wb, sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, array = FALSE, cm = FALSE, apply_cell_style = TRUE, remove_cell_style = FALSE, enforce = FALSE, shared = FALSE, name = NULL, ... )
wb |
A Workbook object containing a worksheet. |
sheet |
The worksheet to write to. (either as index or name) |
x |
A formula as character vector. |
dims |
Spreadsheet dimensions that will determine where |
start_col |
A vector specifying the starting column to write to. |
start_row |
A vector specifying the starting row to write to. |
array |
A bool if the function written is of type array |
cm |
A special kind of array function that hides the curly braces in the cell. Add this, if you see "@" inserted into your formulas. |
apply_cell_style |
Should we write cell styles to the workbook? |
remove_cell_style |
Should we keep the cell style? |
enforce |
enforce dims |
shared |
shared formula |
name |
The name of a named region if specified. |
... |
additional arguments |
Currently, the local translations of formulas are not supported. Only the English functions work.
The examples below show a small list of possible formulas:
SUM(B2:B4)
AVERAGE(B2:B4)
MIN(B2:B4)
MAX(B2:B4)
...
It is possible to pass vectors to x
. If x
is an array formula, it will
take dims
as a reference. For some formulas, the result will span multiple
cells (see the MMULT()
example below). For this type of formula, the
output range must be known a priori and passed to dims
, otherwise only the
value of the first cell will be returned. This type of formula, whose result
extends over several cells, is only possible with single strings. If a vector
is passed, it is only possible to return individual cells.
Custom functions can be registered as lambda functions in the workbook. For
this you take the function you want to add "LAMBDA(x, y, x + y)"
and escape
it as follows. LAMBDA()
is a future function and needs a prefix _xlfn
. The
arguments need a prefix _xlpm.
. So the full function looks like this:
"_xlfn.LAMBDA(_xlpm.x, _xlpm.y, _xlpm.x + _xlpm.y)"
. These custom formulas
are accessible via the named region manager and can be removed with
wb_remove_named_region()
. Contrary to other formulas, custom formulas must
be registered with the workbook before they can be used (see the example
below).
The workbook, invisibly.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
wb <- wb_workbook()$add_worksheet() wb$add_data(dims = wb_dims(rows = 1, cols = 1:3), x = c(4, 5, 8)) # calculate the sum of elements. wb$add_formula(dims = "D1", x = "SUM(A1:C1)") # array formula with result spanning over multiple cells mm <- matrix(1:4, 2, 2) wb$add_worksheet()$ add_data(x = mm, dims = "A1:B2", col_names = FALSE)$ add_data(x = mm, dims = "A4:B5", col_names = FALSE)$ add_formula(x = "MMULT(A1:B2, A4:B5)", dims = "A7:B8", array = TRUE) # add shared formula wb$add_worksheet()$ add_data(x = matrix(rnorm(5*5), ncol = 5, nrow = 5))$ add_formula(x = "SUM($A2:A2)", dims = "A8:E12", shared = TRUE) # add a custom formula, first define it, then use it wb$add_formula(x = c(YESTERDAY = "_xlfn.LAMBDA(TODAY() - 1)")) wb$add_formula(x = "=YESTERDAY()", dims = "A1", cm = TRUE)
wb <- wb_workbook()$add_worksheet() wb$add_data(dims = wb_dims(rows = 1, cols = 1:3), x = c(4, 5, 8)) # calculate the sum of elements. wb$add_formula(dims = "D1", x = "SUM(A1:C1)") # array formula with result spanning over multiple cells mm <- matrix(1:4, 2, 2) wb$add_worksheet()$ add_data(x = mm, dims = "A1:B2", col_names = FALSE)$ add_data(x = mm, dims = "A4:B5", col_names = FALSE)$ add_formula(x = "MMULT(A1:B2, A4:B5)", dims = "A7:B8", array = TRUE) # add shared formula wb$add_worksheet()$ add_data(x = matrix(rnorm(5*5), ncol = 5, nrow = 5))$ add_formula(x = "SUM($A2:A2)", dims = "A8:E12", shared = TRUE) # add a custom formula, first define it, then use it wb$add_formula(x = c(YESTERDAY = "_xlfn.LAMBDA(TODAY() - 1)")) wb$add_formula(x = "=YESTERDAY()", dims = "A1", cm = TRUE)
Helper to add shared hyperlinks into a worksheet or remove shared hyperlinks from a worksheet
wb_add_hyperlink( wb, sheet = current_sheet(), dims = "A1", target = NULL, tooltip = NULL, is_external = TRUE, col_names = FALSE ) wb_remove_hyperlink(wb, sheet = current_sheet(), dims = NULL)
wb_add_hyperlink( wb, sheet = current_sheet(), dims = "A1", target = NULL, tooltip = NULL, is_external = TRUE, col_names = FALSE ) wb_remove_hyperlink(wb, sheet = current_sheet(), dims = NULL)
wb |
A Workbook object containing a worksheet. |
sheet |
The worksheet to write to. (either as index or name) |
dims |
Spreadsheet dimensions that will determine where the hyperlink reference spans: "A1", "A1:B2", "A:B" |
target |
An optional target, if no target is specified, it is assumed that the cell already contains a reference (the cell could be a url or a filename) |
tooltip |
An optional description for a variable that will be visible when hovering over the link text in the spreadsheet |
is_external |
A logical indicating if the hyperlink is external (a url, a mail address, a file) or internal (a reference to worksheet cells) |
col_names |
Whether or not the object contains column names. If yes the first column of the dimension will be ignored |
There are multiple ways to add hyperlinks into a worksheet. One way is to construct a formula with create_hyperlink()
another is to assign a class hyperlink
to a column of a data frame.
Contrary to the previous method, shared hyperlinks are not cell formulas in the worksheet, but references in the worksheet relationship and hyperlinks in the worksheet xml structure.
These shared hyperlinks can be reused and they are not visible to spreadsheet users as HYPERLINK()
formulas.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
wb <- wb_workbook()$add_worksheet()$ add_data(x = "openxlsx2 on CRAN")$ add_hyperlink(target = "https://cran.r-project.org/package=openxlsx2", tooltip = "The canonical form to link to our CRAN page.") wb$remove_hyperlink()
wb <- wb_workbook()$add_worksheet()$ add_data(x = "openxlsx2 on CRAN")$ add_hyperlink(target = "https://cran.r-project.org/package=openxlsx2", tooltip = "The canonical form to link to our CRAN page.") wb$remove_hyperlink()
This function allows to hide / ignore certain types of errors shown in a worksheet.
wb_add_ignore_error( wb, sheet = current_sheet(), dims = "A1", calculated_column = FALSE, empty_cell_reference = FALSE, eval_error = FALSE, formula = FALSE, formula_range = FALSE, list_data_validation = FALSE, number_stored_as_text = FALSE, two_digit_text_year = FALSE, unlocked_formula = FALSE, ... )
wb_add_ignore_error( wb, sheet = current_sheet(), dims = "A1", calculated_column = FALSE, empty_cell_reference = FALSE, eval_error = FALSE, formula = FALSE, formula_range = FALSE, list_data_validation = FALSE, number_stored_as_text = FALSE, two_digit_text_year = FALSE, unlocked_formula = FALSE, ... )
wb |
A workbook |
sheet |
A sheet name or index. |
dims |
Cell range to ignore the error |
calculated_column |
calculatedColumn |
empty_cell_reference |
emptyCellReference |
eval_error |
evalError |
formula |
formula |
formula_range |
formulaRange |
list_data_validation |
listDataValidation |
number_stored_as_text |
If |
two_digit_text_year |
twoDigitTextYear |
unlocked_formula |
unlockedFormula |
... |
additional arguments |
The wbWorkbook
object, invisibly.
Insert an image into a worksheet
wb_add_image( wb, sheet = current_sheet(), dims = "A1", file, width = 6, height = 3, row_offset = 0, col_offset = 0, units = "in", dpi = 300, address = NULL, ... )
wb_add_image( wb, sheet = current_sheet(), dims = "A1", file, width = 6, height = 3, row_offset = 0, col_offset = 0, units = "in", dpi = 300, address = NULL, ... )
wb |
A workbook object |
sheet |
A name or index of a worksheet |
dims |
Dimensions where to plot. Default absolute anchor, single cell (eg. "A1") oneCellAnchor, cell range (eg. "A1:D4") twoCellAnchor |
file |
An image file. Valid file types are: |
width |
Width of figure. |
height |
Height of figure. |
row_offset |
offset vector for one or two cell anchor within cell (row) |
col_offset |
offset vector for one or two cell anchor within cell (column) |
units |
Units of width and height. Can be |
dpi |
Image resolution used for conversion between units. |
address |
An optional character string specifying an external URL, relative or absolute path to a file, or "mailto:" string (e.g. "mailto:[email protected]") that will be opened when the image is clicked. |
... |
additional arguments |
wb_add_chart_xml()
wb_add_drawing()
wb_add_mschart()
wb_add_plot()
img <- system.file("extdata", "einstein.jpg", package = "openxlsx2") wb <- wb_workbook()$ add_worksheet()$ add_image("Sheet 1", dims = "C5", file = img, width = 6, height = 5)$ add_worksheet()$ add_image(dims = "B2", file = img)$ add_worksheet()$ add_image(dims = "G3", file = img, width = 15, height = 12, units = "cm")
img <- system.file("extdata", "einstein.jpg", package = "openxlsx2") wb <- wb_workbook()$ add_worksheet()$ add_image("Sheet 1", dims = "C5", file = img, width = 6, height = 5)$ add_worksheet()$ add_image(dims = "B2", file = img)$ add_worksheet()$ add_image(dims = "G3", file = img, width = 15, height = 12, units = "cm")
Read sensitivity labels from files and apply them to workbooks
wb_add_mips(wb, xml = NULL) wb_get_mips(wb, single_xml = TRUE, quiet = TRUE)
wb_add_mips(wb, xml = NULL) wb_get_mips(wb, single_xml = TRUE, quiet = TRUE)
wb |
a workbook |
xml |
a mips string obtained from |
single_xml |
option to define if the string should be exported as single string. helpful if storing as option is desired. |
quiet |
option to print a MIP section name. This is not always a human readable string. |
The MIP section is a special user-defined XML section that is used to create
sensitivity labels in workbooks. It consists of a series of XML property
nodes that define the sensitivity label. This XML string cannot be created
and it is necessary to first load a workbook with a suitable sensitivity
label. Once the workbook is loaded, the string fmips <- wb_get_mips(wb)
can be extracted. This xml string can later be assigned to an
options("openxlsx2.mips_xml_string" = fmips)
option.
The sensitivity label can then be assigned with wb_add_mips(wb)
. If no xml
string is passed, the MIP section is taken from the option. This should make
it easier for users to read the section from a specific workbook, save it to
a file or string and copy it to an option via the .Rprofile.
the workbook invisible (wb_add_mips()
) or the xml string (wb_get_mips()
)
Add mschart object to a worksheet
wb_add_mschart( wb, sheet = current_sheet(), dims = NULL, graph, col_offset = 0, row_offset = 0, ... )
wb_add_mschart( wb, sheet = current_sheet(), dims = NULL, graph, col_offset = 0, row_offset = 0, ... )
wb |
a workbook |
sheet |
the sheet on which the graph will appear |
dims |
the dimensions where the sheet will appear |
graph |
mschart object |
col_offset , row_offset
|
offsets for column and row |
... |
additional arguments |
wb_data()
wb_add_chart_xml()
wb_add_image wb_add_mschart()
wb_add_plot
if (requireNamespace("mschart")) { require(mschart) ## Add mschart to worksheet (adds data and chart) scatter <- ms_scatterchart(data = iris, x = "Sepal.Length", y = "Sepal.Width", group = "Species") scatter <- chart_settings(scatter, scatterstyle = "marker") wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_mschart(dims = "F4:L20", graph = scatter) ## Add mschart to worksheet and use available data wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars, dims = "B2") # create wb_data object dat <- wb_data(wb, 1, dims = "B2:E6") # call ms_scatterplot data_plot <- ms_scatterchart( data = dat, x = "mpg", y = c("disp", "hp"), labels = c("disp", "hp") ) # add the scatterplot to the data wb <- wb %>% wb_add_mschart(dims = "F4:L20", graph = data_plot) }
if (requireNamespace("mschart")) { require(mschart) ## Add mschart to worksheet (adds data and chart) scatter <- ms_scatterchart(data = iris, x = "Sepal.Length", y = "Sepal.Width", group = "Species") scatter <- chart_settings(scatter, scatterstyle = "marker") wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_mschart(dims = "F4:L20", graph = scatter) ## Add mschart to worksheet and use available data wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars, dims = "B2") # create wb_data object dat <- wb_data(wb, 1, dims = "B2:E6") # call ms_scatterplot data_plot <- ms_scatterchart( data = dat, x = "mpg", y = c("disp", "hp"), labels = c("disp", "hp") ) # add the scatterplot to the data wb <- wb %>% wb_add_mschart(dims = "F4:L20", graph = data_plot) }
Set the styling to a named style for a cell region. Use wb_add_cell_style()
to style a cell region with custom parameters.
A named style is the one in spreadsheet software, like "Normal", "Warning".
wb_add_named_style( wb, sheet = current_sheet(), dims = "A1", name = "Normal", font_name = NULL, font_size = NULL )
wb_add_named_style( wb, sheet = current_sheet(), dims = "A1", name = "Normal", font_name = NULL, font_size = NULL )
wb |
A |
sheet |
A worksheet |
dims |
A cell range |
name |
The named style name. |
font_name , font_size
|
optional else the default of the theme |
The wbWorkbook
, invisibly
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_numfmt()
,
wb_cell_style
Add number formatting to a cell region. You can use a number format created
by create_numfmt()
.
wb_add_numfmt(wb, sheet = current_sheet(), dims = "A1", numfmt)
wb_add_numfmt(wb, sheet = current_sheet(), dims = "A1", numfmt)
wb |
A Workbook |
sheet |
the worksheet |
dims |
the cell range |
numfmt |
either an integer id for a builtin numeric font or a character string as described in the Details |
The list of number formats ID is located in the Details section of create_cell_style()
.
"0"
: Displays numbers as integers without decimal places.
"0.00"
: Displays numbers with two decimal places (e.g., 123.45
).
"#,##0"
: Displays thousands separators without decimals (e.g., 1,000
).
"#,##0.00"
: Displays thousands separators with two decimal places (e.g., 1,000.00
).
"$#,##0.00"
: Formats numbers as currency with two decimal places (e.g., $1,000.00
).
"[$$-409]#,##0.00"
: Localized currency format in U.S. dollars.
"¥#,##0"
: Custom currency format (e.g., for Japanese yen) without decimals.
"£#,##0.00"
: GBP currency format with two decimal places.
"0%"
: Displays numbers as percentages with no decimal places (e.g., 50%
).
"0.00%"
: Displays numbers as percentages with two decimal places (e.g., 50.00%
).
"0.00E+00"
: Scientific notation with two decimal places (e.g., 1.23E+03
for 1230
).
"yyyy-mm-dd"
: Year-month-day format (e.g., 2023-10-31
).
"dd/mm/yyyy"
: Day/month/year format (e.g., 31/10/2023
).
"mmm d, yyyy"
: Month abbreviation with day and year (e.g., Oct 31, 2023
).
"h:mm AM/PM"
: Time with AM/PM format (e.g., 1:30 PM
).
"h:mm:ss"
: Time with seconds (e.g., 13:30:15
for 1:30:15 PM
).
"yyyy-mm-dd h:mm:ss"
: Full date and time format.
"# ?/?"
: Displays numbers as a fraction with a single digit denominator (e.g., 1/2
).
"# ??/??"
: Displays numbers as a fraction with a two-digit denominator (e.g., 1 12/25
).
"_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
:
Custom currency format with parentheses for negative values and dashes for zero values.
"[Red]0.00;[Blue](0.00);0"
: Displays positive numbers in red, negatives in blue, and zeroes as plain.
"@"
: Text placeholder format (e.g., for cells with mixed text and numeric values).
0
: Digit placeholder, displays a digit or zero.
#
: Digit placeholder, does not display extra zeroes.
.
: Decimal point.
,
: Thousands separator.
E+
, E-
: Scientific notation.
_
(underscore): Adds a space equal to the width of the next character.
"text"
: Displays literal text within quotes.
*
: Repeat character to fill the cell width.
The wbWorkbook
object, invisibly.
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_cell_style
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb %>% wb_add_numfmt("S1", dims = "F1:F33", numfmt = "#.0") # Chaining wb <- wb_workbook()$add_worksheet("S1")$add_data("S1", mtcars) wb$add_numfmt("S1", "A1:A33", numfmt = 1)
wb <- wb_workbook() %>% wb_add_worksheet("S1") %>% wb_add_data("S1", mtcars) wb %>% wb_add_numfmt("S1", dims = "F1:F33", numfmt = "#.0") # Chaining wb <- wb_workbook()$add_worksheet("S1")$add_data("S1", mtcars) wb$add_numfmt("S1", "A1:A33", numfmt = 1)
Insert page breaks into a worksheet
wb_add_page_break(wb, sheet = current_sheet(), row = NULL, col = NULL)
wb_add_page_break(wb, sheet = current_sheet(), row = NULL, col = NULL)
wb |
A workbook object |
sheet |
A name or index of a worksheet |
row , col
|
Either a row number of column number. One must be |
wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_data(sheet = 1, x = iris) wb$add_page_break(sheet = 1, row = 10) wb$add_page_break(sheet = 1, row = 20) wb$add_page_break(sheet = 1, col = 2) ## In Excel: View tab -> Page Break Preview
wb <- wb_workbook() wb$add_worksheet("Sheet 1") wb$add_data(sheet = 1, x = iris) wb$add_page_break(sheet = 1, row = 10) wb$add_page_break(sheet = 1, row = 20) wb$add_page_break(sheet = 1, col = 2) ## In Excel: View tab -> Page Break Preview
The data must be specified using wb_data()
to ensure the function works.
The sheet will be empty unless it is opened in spreadsheet software. Find
more details in the section about pivot tables
in the openxlsx2 book.
wb_add_pivot_table( wb, x, sheet = next_sheet(), dims = "A3", filter, rows, cols, data, fun, params, pivot_table, slicer, timeline )
wb_add_pivot_table( wb, x, sheet = next_sheet(), dims = "A3", filter, rows, cols, data, fun, params, pivot_table, slicer, timeline )
wb |
A Workbook object containing a #' worksheet. |
x |
A |
sheet |
A worksheet containing a #' |
dims |
The worksheet cell where the pivot table is placed |
filter |
The column name(s) of |
rows |
The column name(s) of |
cols |
The column names(s) of |
data |
The column name(s) of |
fun |
A vector of functions to be used with |
params |
A list of parameters to modify pivot table creation. See Details for available options. |
pivot_table |
An optional name for the pivot table |
slicer , timeline
|
Any additional column name(s) of |
The pivot table is not actually written to the worksheet, therefore the cell region has to remain empty. What is written to the workbook is something like a recipe how the spreadsheet software has to construct the pivot table when opening the file.
It is possible to add slicers to the pivot table. For this the pivot
table has to be named and the variable used as slicer, must be part
of the selected pivot table names (cols
, rows
, filter
, or
slicer
). If these criteria are matched, a slicer can be added
using wb_add_slicer()
.
Be aware that you should always test on a copy if a param
argument works
with a pivot table. Not only to check if the desired effect appears, but
first and foremost if the file loads. Wildly mixing params might brick the
output file and cause spreadsheet software to crash.
fun
can be any of AVERAGE
, COUNT
, COUNTA
, MAX
, MIN
,
PRODUCT
, STDEV
, STDEVP
, SUM
, VAR
, VARP
.
show_data_as
can be any of normal
, difference
, percent
, percentDiff
,
runTotal
, percentOfRow
, percentOfCol
, percentOfTotal
, index
.
It is possible to calculate data fields if the formula is assigned as a
variable name for the field to calculate. This would look like this:
data = c("am", "disp/cyl" = "New")
Possible params
arguments are listed below. Pivot tables accepts more
parameters, but they were either not tested or misbehaved (probably because
we misunderstood how the parameter should be used).
Boolean arguments:
apply_alignment_formats
apply_number_formats
apply_border_formats
apply_font_formats
apply_pattern_formats
apply_width_height_formats
no_style
compact
outline
compact_data
row_grand_totals
col_grand_totals
Table styles accepting character strings:
auto_format_id: style id as character in the range of 4096 to 4117
table_style: a predefined (pivot) table style "TableStyleMedium23"
show_data_as: accepts character strings as listed above
Miscellaneous:
numfmt: accepts vectors of the form c(formatCode = "0.0%")
choose: select variables in the form of a named logical vector like
c(agegp = 'x > "25-34"')
for the esoph
dataset.
sort_item: named list of index or character vectors
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars) df <- wb_data(wb, sheet = 1) wb <- wb %>% # default pivot table wb_add_pivot_table(df, dims = "A3", filter = "am", rows = "cyl", cols = "gear", data = "disp" ) %>% # with parameters wb_add_pivot_table(df, filter = "am", rows = "cyl", cols = "gear", data = "disp", params = list(no_style = TRUE, numfmt = c(formatCode = "##0.0")) )
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars) df <- wb_data(wb, sheet = 1) wb <- wb %>% # default pivot table wb_add_pivot_table(df, dims = "A3", filter = "am", rows = "cyl", cols = "gear", data = "disp" ) %>% # with parameters wb_add_pivot_table(df, filter = "am", rows = "cyl", cols = "gear", data = "disp", params = list(no_style = TRUE, numfmt = c(formatCode = "##0.0")) )
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()
.
wb_add_plot( wb, sheet = current_sheet(), dims = "A1", width = 6, height = 4, row_offset = 0, col_offset = 0, file_type = "png", units = "in", dpi = 300, ... )
wb_add_plot( wb, sheet = current_sheet(), dims = "A1", width = 6, height = 4, row_offset = 0, col_offset = 0, file_type = "png", units = "in", dpi = 300, ... )
wb |
A workbook object |
sheet |
A name or index of a worksheet |
dims |
Worksheet dimension, single cell ("A1") or cell range ("A1:D4") |
width |
Width of figure. Defaults to |
height |
Height of figure . Defaults to |
row_offset , col_offset
|
Offset for column and row |
file_type |
File type of image |
units |
Units of width and height. Can be |
dpi |
Image resolution |
... |
additional arguments |
wb_add_chart_xml()
wb_add_drawing()
wb_add_image()
wb_add_mschart()
if (requireNamespace("ggplot2") && interactive()) { ## Create a new workbook wb <- wb_workbook() ## Add a worksheet wb$add_worksheet("Sheet 1", grid_lines = FALSE) ## create plot objects require(ggplot2) p1 <- ggplot(mtcars, aes(x = mpg, fill = as.factor(gear))) + ggtitle("Distribution of Gas Mileage") + geom_density(alpha = 0.5) p2 <- ggplot(Orange, aes(x = age, y = circumference, color = Tree)) + geom_point() + geom_line() ## 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, file_type = "png", units = "in") ## Insert plot 2 print(p2) wb$add_plot(1, dims = "J2", width = 16, height = 10, file_type = "png", units = "cm") }
if (requireNamespace("ggplot2") && interactive()) { ## Create a new workbook wb <- wb_workbook() ## Add a worksheet wb$add_worksheet("Sheet 1", grid_lines = FALSE) ## create plot objects require(ggplot2) p1 <- ggplot(mtcars, aes(x = mpg, fill = as.factor(gear))) + ggtitle("Distribution of Gas Mileage") + geom_density(alpha = 0.5) p2 <- ggplot(Orange, aes(x = age, y = circumference, color = Tree)) + geom_point() + geom_line() ## 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, file_type = "png", units = "in") ## Insert plot 2 print(p2) wb$add_plot(1, dims = "J2", width = 16, height = 10, file_type = "png", units = "cm") }
Add a slicer/timeline to a previously created pivot table. This function is still experimental and might be changed/improved in upcoming releases.
wb_add_slicer( wb, x, dims = "A1", sheet = current_sheet(), pivot_table, slicer, params ) wb_remove_slicer(wb, sheet = current_sheet()) wb_add_timeline( wb, x, dims = "A1", sheet = current_sheet(), pivot_table, timeline, params ) wb_remove_timeline(wb, sheet = current_sheet())
wb_add_slicer( wb, x, dims = "A1", sheet = current_sheet(), pivot_table, slicer, params ) wb_remove_slicer(wb, sheet = current_sheet()) wb_add_timeline( wb, x, dims = "A1", sheet = current_sheet(), pivot_table, timeline, params ) wb_remove_timeline(wb, sheet = current_sheet())
wb |
A Workbook object containing a worksheet. |
x |
A |
dims |
The worksheet cell where the pivot table is placed |
sheet |
A worksheet |
pivot_table |
The name of a pivot table |
slicer , timeline
|
A variable used as slicer/timeline for the pivot table |
params |
A list of parameters to modify pivot table creation. See Details for available options. |
This assumes that the slicer/timeline variable initialization has happened before. Unfortunately, it is unlikely that we can guarantee this for loaded workbooks, and we strictly discourage users from attempting this. If the variable has not been initialized properly, this may cause the spreadsheet software to crash. Although it is documented that slicers should use "TimelineStyleLight[1-6]" and "TimelineStyleDark[1-6]" they use slicer styles.
Possible params
arguments for slicers are listed below.
edit_as: "twoCell" to place the slicer into the cells
column_count: integer used as column count
sort_order: "descending" / "ascending"
choose: select variables in the form of a named logical vector like
c(agegp = 'x > "25-34"')
for the esoph
dataset.
locked_position
start_item
hide_no_data_items
Possible params
arguments for timelines are listed below.
beg_date/end_date: dates when the timeline should begin or end
choose_beg/choose_end: dates when the selection should begin or end
scroll_position
show_selection_label
show_time_level
show_horizontal_scrollbar
Possible common params
:
caption: string used for a caption
style: "SlicerStyleLight[1-6]", "SlicerStyleDark[1-6]" only for slicer "SlicerStyleOther[1-2]"
level: the granularity of the slicer (for timeline 0 = year, 1 = quarter, 2 = month)
show_caption: logical if caption should be shown or not
Removing works on the spreadsheet level. Therefore all slicers/timelines are removed from a worksheet. At the moment the drawing reference remains on the spreadsheet. Therefore spreadsheet software that does not handle slicers/timelines will still show the drawing.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_thread()
,
wb_freeze_pane()
,
wb_merge_cells()
# prepare data df <- data.frame( AirPassengers = c(AirPassengers), time = seq(from = as.Date("1949-01-01"), to = as.Date("1960-12-01"), by = "month"), letters = letters[1:4] ) # create workbook wb <- wb_workbook()$ add_worksheet("pivot")$ add_worksheet("data")$ add_data(x = df) # get pivot table data source df <- wb_data(wb, sheet = "data") # create pivot table wb$add_pivot_table( df, sheet = "pivot", rows = "time", cols = "letters", data = "AirPassengers", pivot_table = "airpassengers", params = list( compact = FALSE, outline = FALSE, compact_data = FALSE, row_grand_totals = FALSE, col_grand_totals = FALSE) ) # add slicer wb$add_slicer( df, dims = "E1:I7", sheet = "pivot", slicer = "letters", pivot_table = "airpassengers", params = list(choose = c(letters = 'x %in% c("a", "b")')) ) # add timeline wb$add_timeline( df, dims = "E9:I14", sheet = "pivot", timeline = "time", pivot_table = "airpassengers", params = list( beg_date = as.Date("1954-01-01"), end_date = as.Date("1961-01-01"), choose_beg = as.Date("1957-01-01"), choose_end = as.Date("1958-01-01"), level = 0, style = "TimeSlicerStyleLight2" ) )
# prepare data df <- data.frame( AirPassengers = c(AirPassengers), time = seq(from = as.Date("1949-01-01"), to = as.Date("1960-12-01"), by = "month"), letters = letters[1:4] ) # create workbook wb <- wb_workbook()$ add_worksheet("pivot")$ add_worksheet("data")$ add_data(x = df) # get pivot table data source df <- wb_data(wb, sheet = "data") # create pivot table wb$add_pivot_table( df, sheet = "pivot", rows = "time", cols = "letters", data = "AirPassengers", pivot_table = "airpassengers", params = list( compact = FALSE, outline = FALSE, compact_data = FALSE, row_grand_totals = FALSE, col_grand_totals = FALSE) ) # add slicer wb$add_slicer( df, dims = "E1:I7", sheet = "pivot", slicer = "letters", pivot_table = "airpassengers", params = list(choose = c(letters = 'x %in% c("a", "b")')) ) # add timeline wb$add_timeline( df, dims = "E9:I14", sheet = "pivot", timeline = "time", pivot_table = "airpassengers", params = list( beg_date = as.Date("1954-01-01"), end_date = as.Date("1961-01-01"), choose_beg = as.Date("1957-01-01"), choose_end = as.Date("1958-01-01"), level = 0, style = "TimeSlicerStyleLight2" ) )
Add sparklines to a worksheet
wb_add_sparklines(wb, sheet = current_sheet(), sparklines)
wb_add_sparklines(wb, sheet = current_sheet(), sparklines)
wb |
A |
sheet |
sheet to add the sparklines to |
sparklines |
sparklines object created with |
sl <- create_sparklines("Sheet 1", dims = "A3:K3", sqref = "L3") wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars) %>% wb_add_sparklines(sparklines = sl)
sl <- create_sparklines("Sheet 1", dims = "A3:K3", sqref = "L3") wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars) %>% wb_add_sparklines(sparklines = sl)
wb wrapper to add style to workbook
wb_add_style(wb, style = NULL, style_name = NULL)
wb_add_style(wb, style = NULL, style_name = NULL)
wb |
A workbook |
style |
style xml character, created by a |
style_name |
style name used optional argument |
The wbWorkbook
object, invisibly.
Other workbook styling functions:
base_font-wb
,
wb_add_dxfs_style()
,
wb_base_colors
yellow_f <- wb_color(hex = "FF9C6500") yellow_b <- wb_color(hex = "FFFFEB9C") yellow <- create_dxfs_style(font_color = yellow_f, bg_fill = yellow_b) wb <- wb_workbook() %>% wb_add_style(yellow)
yellow_f <- wb_color(hex = "FF9C6500") yellow_b <- wb_color(hex = "FFFFEB9C") yellow <- create_dxfs_style(font_color = yellow_f, bg_fill = yellow_b) wb <- wb_workbook() %>% wb_add_style(yellow)
These functions allow adding thread comments to spreadsheets.
This is not yet supported by all spreadsheet software. A threaded comment must
be tied to a person created by wb_add_person()
.
wb_add_thread( wb, sheet = current_sheet(), dims = "A1", comment = NULL, person_id, reply = FALSE, resolve = FALSE ) wb_get_thread(wb, sheet = current_sheet(), dims = NULL)
wb_add_thread( wb, sheet = current_sheet(), dims = "A1", comment = NULL, person_id, reply = FALSE, resolve = FALSE ) wb_get_thread(wb, sheet = current_sheet(), dims = NULL)
wb |
A workbook |
sheet |
A worksheet |
dims |
A cell |
comment |
The text to add, a character vector. |
person_id |
the person Id this should be added. The default is
|
reply |
Is the comment a reply? (default |
resolve |
Should the comment be resolved? (default |
If a threaded comment is added, it needs a person attached to it.
The default is to create a person with provider id "None"
.
Other providers are possible with specific values for id
and user_id
.
If you require the following, create a workbook via spreadsheet software load
it and get the values with wb_get_person()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_freeze_pane()
,
wb_merge_cells()
wb <- wb_workbook()$add_worksheet() # Add a person to the workbook. wb$add_person(name = "someone who likes to edit workbooks") pid <- wb$get_person(name = "someone who likes to edit workbooks")$id # write a comment to a thread, reply to one and solve some wb <- wb %>% wb_add_thread(dims = "A1", comment = "wow it works!", person_id = pid) %>% wb_add_thread(dims = "A2", comment = "indeed", person_id = pid, resolve = TRUE) %>% wb_add_thread(dims = "A1", comment = "so cool", person_id = pid, reply = TRUE)
wb <- wb_workbook()$add_worksheet() # Add a person to the workbook. wb$add_person(name = "someone who likes to edit workbooks") pid <- wb$get_person(name = "someone who likes to edit workbooks")$id # write a comment to a thread, reply to one and solve some wb <- wb %>% wb_add_thread(dims = "A1", comment = "wow it works!", person_id = pid) %>% wb_add_thread(dims = "A2", comment = "indeed", person_id = pid, resolve = TRUE) %>% wb_add_thread(dims = "A1", comment = "so cool", person_id = pid, reply = TRUE)
Add a worksheet to a wbWorkbook is the first step to build a workbook.
With the function, you can also set the sheet view with zoom
, set headers
and footers as well as other features. See the function arguments.
wb_add_worksheet( wb, 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)), ... )
wb_add_worksheet( wb, 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)), ... )
wb |
A |
sheet |
A name for the new worksheet |
grid_lines |
A logical. If |
row_col_headers |
A logical. If |
tab_color |
Color of the sheet tab. A |
zoom |
The sheet zoom level, a numeric between 10 and 400 as a percentage. (A zoom value smaller than 10 will default to 10.) |
header , odd_header , even_header , first_header , footer , odd_footer , even_footer , first_footer
|
Character vector of length 3 corresponding to positions left, center,
right. |
visible |
If |
has_drawing |
If |
paper_size |
An integer corresponding to a paper size. See |
orientation |
One of "portrait" or "landscape" |
hdpi , vdpi
|
Horizontal and vertical DPI. Can be set with |
... |
Additional arguments |
Headers and footers can contain special tags
&[Page] Page number
&[Pages] Number of pages
&[Date] Current date
&[Time] Current time
&[Path] File path
&[File] File name
&[Tab] Worksheet name
The wbWorkbook
object, invisibly.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
## Create a new workbook wb <- wb_workbook() ## Add a worksheet wb$add_worksheet("Sheet 1") ## No grid lines wb$add_worksheet("Sheet 2", grid_lines = FALSE) ## A red tab color wb$add_worksheet("Sheet 3", tab_color = wb_color("red")) ## All options combined with a zoom of 40% wb$add_worksheet("Sheet 4", grid_lines = FALSE, tab_color = wb_color(hex = "#4F81BD"), zoom = 40) ## 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"), even_header = c("EVEN HEAD LEFT", "EVEN HEAD CENTER", "EVEN HEAD RIGHT"), even_footer = c("EVEN FOOT RIGHT", "EVEN FOOT CENTER", "EVEN FOOT RIGHT"), first_header = c("TOP", "OF FIRST", "PAGE"), first_footer = 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]"), first_header = c(NA, "Center Header of First Page", NA), first_footer = 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", first_header = c("FIRST ONLY L", NA, "FIRST ONLY R"), first_footer = 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)
## Create a new workbook wb <- wb_workbook() ## Add a worksheet wb$add_worksheet("Sheet 1") ## No grid lines wb$add_worksheet("Sheet 2", grid_lines = FALSE) ## A red tab color wb$add_worksheet("Sheet 3", tab_color = wb_color("red")) ## All options combined with a zoom of 40% wb$add_worksheet("Sheet 4", grid_lines = FALSE, tab_color = wb_color(hex = "#4F81BD"), zoom = 40) ## 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"), even_header = c("EVEN HEAD LEFT", "EVEN HEAD CENTER", "EVEN HEAD RIGHT"), even_footer = c("EVEN FOOT RIGHT", "EVEN FOOT CENTER", "EVEN FOOT RIGHT"), first_header = c("TOP", "OF FIRST", "PAGE"), first_footer = 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]"), first_header = c(NA, "Center Header of First Page", NA), first_footer = 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", first_header = c("FIRST ONLY L", NA, "FIRST ONLY R"), first_footer = 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)
Modify / get the default colors of the workbook.
wb_set_base_colors(wb, theme = "Office", ...) wb_get_base_colors(wb, xml = FALSE, plot = TRUE)
wb_set_base_colors(wb, theme = "Office", ...) wb_get_base_colors(wb, xml = FALSE, plot = TRUE)
wb |
A workbook object |
theme |
a predefined color theme |
... |
optional parameters |
xml |
Logical if xml string should be returned |
plot |
Logical if a barplot of the colors should be returned |
Theme must be any of the following: "Aspect", "Blue", "Blue II", "Blue Green", "Blue Warm", "Greyscale", "Green", "Green Yellow", "Marquee", "Median", "Office", "Office 2007 - 2010", "Office 2013 - 2022", "Orange", "Orange Red", "Paper", "Red", "Red Orange", "Red Violet", "Slipstream", "Violet", "Violet II", "Yellow", "Yellow Orange"
Other workbook styling functions:
base_font-wb
,
wb_add_dxfs_style()
,
wb_add_style()
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
wb <- wb_workbook() wb$get_base_colors() wb$set_base_colors(theme = 3) wb$set_base_colors(theme = "Violet II") wb$get_base_colours()
wb <- wb_workbook() wb$get_base_colors() wb$set_base_colors(theme = 3) wb$set_base_colors(theme = "Violet II") wb$get_base_colours()
Setting a style across only impacts cells that are not yet part of a workbook. The effect is similar to setting the cell style for all cells in a row independently, though much quicker and less memory consuming.
wb_get_cell_style(wb, sheet = current_sheet(), dims) wb_set_cell_style(wb, sheet = current_sheet(), dims, style) wb_set_cell_style_across( wb, sheet = current_sheet(), style, cols = NULL, rows = NULL )
wb_get_cell_style(wb, sheet = current_sheet(), dims) wb_set_cell_style(wb, sheet = current_sheet(), dims, style) wb_set_cell_style_across( wb, sheet = current_sheet(), style, cols = NULL, rows = NULL )
wb |
A |
sheet |
sheet |
dims |
A cell range in the worksheet |
style |
A style or a cell with a certain style |
cols |
The columns the style will be applied to, either "A:D" or 1:4 |
rows |
The rows the style will be applied to |
A Workbook object
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
# set a style in b1 wb <- wb_workbook()$add_worksheet()$ add_numfmt(dims = "B1", numfmt = "#,0") # get style from b1 to assign it to a1 numfmt <- wb$get_cell_style(dims = "B1") # assign style to a1 wb$set_cell_style(dims = "A1", style = numfmt) # set style across a workbook wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_fill(dims = "C3", color = wb_color("yellow")) %>% wb_set_cell_style_across(style = "C3", cols = "C:D", rows = 3:4)
# set a style in b1 wb <- wb_workbook()$add_worksheet()$ add_numfmt(dims = "B1", numfmt = "#,0") # get style from b1 to assign it to a1 numfmt <- wb$get_cell_style(dims = "B1") # assign style to a1 wb$set_cell_style(dims = "A1", style = numfmt) # set style across a workbook wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_fill(dims = "C3", color = wb_color("yellow")) %>% wb_set_cell_style_across(style = "C3", cols = "C:D", rows = 3:4)
Remove content of a worksheet completely, or a region if specifying dims
.
wb_clean_sheet( wb, sheet = current_sheet(), dims = NULL, numbers = TRUE, characters = TRUE, styles = TRUE, merged_cells = TRUE, hyperlinks = TRUE )
wb_clean_sheet( wb, sheet = current_sheet(), dims = NULL, numbers = TRUE, characters = TRUE, styles = TRUE, merged_cells = TRUE, hyperlinks = TRUE )
wb |
A Workbook object |
sheet |
sheet to clean |
dims |
spreadsheet dimensions (optional) |
numbers |
remove all numbers |
characters |
remove all characters |
styles |
remove all styles |
merged_cells |
remove all merged_cells |
hyperlinks |
remove all hyperlinks |
A Workbook object
This function can be used to apply styling from a cell range, and apply it to another cell range.
wb_clone_sheet_style(wb, from = current_sheet(), to)
wb_clone_sheet_style(wb, from = current_sheet(), to)
wb |
A workbook |
from |
sheet we select the style from |
to |
sheet to apply the style to |
Create a copy of a worksheet in the same wbWorkbook
object.
Cloning is possible only to a limited extent. References to sheet names in formulas, charts, pivot tables, etc. may not be updated. Some elements like named ranges and slicers cannot be cloned yet.
Cloning from another workbook is still an experimental feature and might not work reliably. Cloning data, media, charts and tables should work. Slicers and pivot tables as well as everything everything relying on dxfs styles (e.g. custom table styles and conditional formatting) is currently not implemented. Formula references are not updated to reflect interactions between workbooks.
wb_clone_worksheet(wb, old = current_sheet(), new = next_sheet(), from = NULL)
wb_clone_worksheet(wb, old = current_sheet(), new = next_sheet(), from = NULL)
wb |
A |
old |
Name of existing worksheet to copy |
new |
Name of the new worksheet to create |
from |
(optional) Workbook to clone old from |
The wbWorkbook
object, invisibly.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
# Create a new workbook wb <- wb_workbook() # Add worksheets wb$add_worksheet("Sheet 1") wb$clone_worksheet("Sheet 1", new = "Sheet 2") # Take advantage of waiver functions wb$clone_worksheet(old = "Sheet 1") ## cloning from another workbook # create a workbook wb <- wb_workbook()$ add_worksheet("NOT_SUM")$ add_data(x = head(iris))$ add_fill(dims = "A1:B2", color = wb_color("yellow"))$ add_border(dims = "B2:C3") # we will clone this styled chart into another workbook fl <- system.file("extdata", "oxlsx2_sheet.xlsx", package = "openxlsx2") wb_from <- wb_load(fl) # clone styles and shared strings wb$clone_worksheet(old = "SUM", new = "SUM", from = wb_from)
# Create a new workbook wb <- wb_workbook() # Add worksheets wb$add_worksheet("Sheet 1") wb$clone_worksheet("Sheet 1", new = "Sheet 2") # Take advantage of waiver functions wb$clone_worksheet(old = "Sheet 1") ## cloning from another workbook # create a workbook wb <- wb_workbook()$ add_worksheet("NOT_SUM")$ add_data(x = head(iris))$ add_fill(dims = "A1:B2", color = wb_color("yellow"))$ add_border(dims = "B2:C3") # we will clone this styled chart into another workbook fl <- system.file("extdata", "oxlsx2_sheet.xlsx", package = "openxlsx2") wb_from <- wb_load(fl) # clone styles and shared strings wb$clone_worksheet(old = "SUM", new = "SUM", from = wb_from)
Creates a wbColour
object.
wb_color( name = NULL, auto = NULL, indexed = NULL, hex = NULL, theme = NULL, tint = NULL )
wb_color( name = NULL, auto = NULL, indexed = NULL, hex = NULL, theme = NULL, tint = NULL )
name |
A name of a color known to R either as name or RGB/ARGB value. |
auto |
A boolean. |
indexed |
An indexed color value. This color has to be provided by the workbook. |
hex |
A rgb color either a ARGB hex value or RGB hex value With or without leading "#". |
theme |
A zero based index referencing a value in the theme. |
tint |
A tint value applied. Range from -1 (dark) to 1 (light). |
a wbColour
object
wb_get_base_colors()
grDevices::colors()
Creates a wbComment
object. Use with wb_add_comment()
to add to a worksheet location.
wb_comment( text = NULL, style = NULL, visible = FALSE, author = getOption("openxlsx2.creator"), width = 2, height = 4 )
wb_comment( text = NULL, style = NULL, visible = FALSE, author = getOption("openxlsx2.creator"), width = 2, height = 4 )
text |
Comment text. Character vector. or a |
style |
A Style object or list of style objects the same length as comment vector. |
visible |
Is comment visible? Default: |
author |
Author of comment. A string. By default, will look at |
width |
Textbox integer width in number of cells |
height |
Textbox integer height in number of cells |
A wbComment
object
wb <- wb_workbook() wb$add_worksheet("Sheet 1") # write comment without author c1 <- wb_comment(text = "this is a comment", author = "", visible = TRUE) wb$add_comment(dims = "B10", comment = c1) # Write another comment with author information c2 <- wb_comment(text = "this is another comment", author = "Marco Polo") wb$add_comment(sheet = 1, dims = "C10", comment = c2) # write a styled comment with system author s1 <- create_font(b = "true", color = wb_color(hex = "FFFF0000"), sz = "12") s2 <- create_font(color = wb_color(hex = "FF000000"), sz = "9") c3 <- wb_comment(text = c("This Part Bold red\n\n", "This part black"), style = c(s1, s2)) wb$add_comment(sheet = 1, dims = wb_dims(3, 6), comment = c3)
wb <- wb_workbook() wb$add_worksheet("Sheet 1") # write comment without author c1 <- wb_comment(text = "this is a comment", author = "", visible = TRUE) wb$add_comment(dims = "B10", comment = c1) # Write another comment with author information c2 <- wb_comment(text = "this is another comment", author = "Marco Polo") wb$add_comment(sheet = 1, dims = "C10", comment = c2) # write a styled comment with system author s1 <- create_font(b = "true", color = wb_color(hex = "FFFF0000"), sz = "12") s2 <- create_font(color = wb_color(hex = "FF000000"), sz = "9") c3 <- wb_comment(text = c("This Part Bold red\n\n", "This part black"), style = c(s1, s2)) wb$add_comment(sheet = 1, dims = wb_dims(3, 6), comment = c3)
Copy cells around within a worksheet
wb_copy_cells( wb, sheet = current_sheet(), dims = "A1", data, as_value = FALSE, as_ref = FALSE, transpose = FALSE, ... )
wb_copy_cells( wb, sheet = current_sheet(), dims = "A1", data, as_value = FALSE, as_ref = FALSE, transpose = FALSE, ... )
wb |
A workbook |
sheet |
a worksheet |
dims |
A cell where to place the copy |
data |
A |
as_value |
Should a copy of the value be written? |
as_ref |
Should references to the cell be written? |
transpose |
Should the data be written transposed? |
... |
additional arguments passed to add_data() if used with |
the wbWorkbook
invisibly
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
wb <- wb_workbook()$ add_worksheet()$ add_data(x = mtcars)$ add_fill(dims = "A1:F1", color = wb_color("yellow")) dat <- wb_data(wb, dims = "A1:D4", col_names = FALSE) # 1:1 copy to M2 wb$ clone_worksheet(old = 1, new = "Clone1")$ copy_cells(data = dat, dims = "M2")
wb <- wb_workbook()$ add_worksheet()$ add_data(x = mtcars)$ add_fill(dims = "A1:F1", color = wb_color("yellow")) dat <- wb_data(wb, dims = "A1:D4", col_names = FALSE) # 1:1 copy to M2 wb$ clone_worksheet(old = 1, new = "Clone1")$ copy_cells(data = dat, dims = "M2")
wb_data
attribute to a data frame in a worksheetprovide wb_data object as mschart input
wb_data(wb, sheet = current_sheet(), dims, ...) ## S3 method for class 'wb_data' x[ i, j, drop = ifelse((missing(j) && length(i) > 1) || (!missing(i) && length(j) > 1), FALSE, TRUE) ]
wb_data(wb, sheet = current_sheet(), dims, ...) ## S3 method for class 'wb_data' x[ i, j, drop = ifelse((missing(j) && length(i) > 1) || (!missing(i) && length(j) > 1), FALSE, TRUE) ]
wb |
a workbook |
sheet |
a sheet in the workbook either name or index |
dims |
the dimensions |
... |
additional arguments for |
x |
x |
i |
i |
j |
j |
drop |
drop |
A data frame of class wb_data
.
wb_to_df()
wb_add_mschart()
, wb_add_pivot_table()
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars, dims = "B2") wb_data(wb, 1, dims = "B2:E6")
wb <- wb_workbook() %>% wb_add_worksheet() %>% wb_add_data(x = mtcars, dims = "B2") wb_data(wb, 1, dims = "B2:E6")
dims
argumentwb_dims()
can be used to help provide the dims
argument, in the wb_add_*
functions.
It returns a A1 spreadsheet range ("A1:B1" or "A2").
It can be very useful as you can specify many parameters that interact together
In general, you must provide named arguments. wb_dims()
will only accept unnamed arguments
if they are rows
, cols
, for example wb_dims(1:4, 1:2)
, that will return "A1:B4".
wb_dims()
can also be used with an object (a data.frame
or a matrix
for example.)
All parameters are numeric unless stated otherwise.
wb_dims(..., select = NULL)
wb_dims(..., select = NULL)
... |
construct |
select |
A string, one of the followings.
it improves the selection of various parts of |
When using wb_dims()
with an object, the default behavior is
to select only the data / row or columns in x
If you need another behavior, use wb_dims()
without supplying x
.
x
An object (typically a matrix
or a data.frame
, but a vector is also accepted.)
from_row
/ from_col
/ from_dims
the starting position of x
(The dims
returned will assume that the top left corner of x
is at from_row / from_col
rows
Optional Which row span in x
should this apply to.
If rows
= 0, only column names will be affected.
cols
a range of columns id in x
, or one of the column names of x
(length 1 only accepted for column names of x
.)
row_names
A logical, this is to let wb_dims()
know that x
has row names or not.
If row_names = TRUE
, wb_dims()
will increment from_col
by 1.
col_names
wb_dims()
assumes that if x
has column names, then trying to find the dims
.
wb_dims()
tries to support most possible cases with row_names = TRUE
and col_names = FALSE
,
but it works best if x
has named dimensions (data.frame
, matrix
), and those parameters are not specified.
data with column names, and without row names. as the code is more clean.
In the add_data()
/ add_font()
example, if writing the data with row names
A dims
string
wb_dims()
without an x
objectrows
/ cols
(if you want to specify a single one, use from_row
/ from_col
)
from_row
/ from_col
the starting position of the dims
(similar to start_row
/ start_col
, but with a clearer name.)
wb_dims()
with an x
objectwb_dims()
with an object has 8 use-cases (they work with any position values of from_row
/ from_col
),
from_col/from_row
correspond to the coordinates at the top left of x
including column and row names if present.
These use cases are provided without from_row / from_col
, but they work also with from_row / from_col
.
provide the full grid with wb_dims(x = mtcars)
provide the data grid wb_dims(x = mtcars, select = "data")
provide the dims
of column names wb_dims(x = mtcars, select = "col_names)
provide the dims
of row names wb_dims(x = mtcars, row_names = TRUE, select = "row_names")
provide the dims
of a row span wb_dims(x = mtcars, rows = 1:10)
selects
the first 10 data rows of mtcars
(ignoring column names)
provide the dims
of the data in a column span wb_dims(x = mtcars, cols = 1:5)
select the data first 5 columns of mtcars
provide a column span (including column names) wb_dims(x = mtcars, cols = 4:7, select = "x")
select the data columns 4, 5, 6, 7 of mtcars
+ column names
provide the position of a single column by name wb_dims(x = mtcars, cols = "mpg")
.
provide a row span with a column. wb_dims(x = mtcars, cols = "mpg", rows = 5:22)
To reuse, a good trick is to create a wrapper function, so that styling can be performed seamlessly.
wb_dims_cars <- function(...) { wb_dims(x = mtcars, from_row = 2, from_col = "B", ...) } # using this function wb_dims_cars() # full grid (data + column names) wb_dims_cars(select = "data") # data only wb_dims_cars(select = "col_names") # select column names wb_dims_cars(cols = "vs") # select the `vs` column
It can be very useful to apply many rounds of styling sequentially.
# Provide coordinates wb_dims(1, 4) wb_dims(rows = 1, cols = 4) wb_dims(from_row = 4) wb_dims(from_col = 2) wb_dims(from_col = "B") wb_dims(1:4, 6:9, from_row = 5) # Provide vectors wb_dims(1:10, c("A", "B", "C")) wb_dims(rows = 1:10, cols = 1:10) # provide `from_col` / `from_row` wb_dims(rows = 1:10, cols = c("A", "B", "C"), from_row = 2) wb_dims(rows = 1:10, cols = 1:10, from_col = 2) wb_dims(rows = 1:10, cols = 1:10, from_dims = "B1") # or objects wb_dims(x = mtcars, col_names = TRUE) # select all data wb_dims(x = mtcars, select = "data") # column names of an object (with the special select = "col_names") wb_dims(x = mtcars, select = "col_names") # dims of the column names of an object wb_dims(x = mtcars, select = "col_names", col_names = TRUE) ## add formatting to `mtcars` using `wb_dims()`---- wb <- wb_workbook() wb$add_worksheet("test wb_dims() with an object") dims_mtcars_and_col_names <- wb_dims(x = mtcars) wb$add_data(x = mtcars, dims = dims_mtcars_and_col_names) # Put the font as Arial for the data dims_mtcars_data <- wb_dims(x = mtcars, select = "data") wb$add_font(dims = dims_mtcars_data, name = "Arial") # Style col names as bold using the special `select = "col_names"` with `x` provided. dims_column_names <- wb_dims(x = mtcars, select = "col_names") wb$add_font(dims = dims_column_names, bold = TRUE, size = 13) # Finally, to add styling to column "cyl" (the 4th column) (only the data) # there are many options, but here is the preferred one # if you know the column index, wb_dims(x = mtcars, cols = 4) also works. dims_cyl <- wb_dims(x = mtcars, cols = "cyl") wb$add_fill(dims = dims_cyl, color = wb_color("pink")) # Mark a full column as important(with the column name too) wb_dims_vs <- wb_dims(x = mtcars, cols = "vs", select = "x") wb$add_fill(dims = wb_dims_vs, fill = wb_color("yellow")) wb$add_conditional_formatting(dims = wb_dims(x = mtcars, cols = "mpg"), type = "dataBar") # wb_open(wb)
# Provide coordinates wb_dims(1, 4) wb_dims(rows = 1, cols = 4) wb_dims(from_row = 4) wb_dims(from_col = 2) wb_dims(from_col = "B") wb_dims(1:4, 6:9, from_row = 5) # Provide vectors wb_dims(1:10, c("A", "B", "C")) wb_dims(rows = 1:10, cols = 1:10) # provide `from_col` / `from_row` wb_dims(rows = 1:10, cols = c("A", "B", "C"), from_row = 2) wb_dims(rows = 1:10, cols = 1:10, from_col = 2) wb_dims(rows = 1:10, cols = 1:10, from_dims = "B1") # or objects wb_dims(x = mtcars, col_names = TRUE) # select all data wb_dims(x = mtcars, select = "data") # column names of an object (with the special select = "col_names") wb_dims(x = mtcars, select = "col_names") # dims of the column names of an object wb_dims(x = mtcars, select = "col_names", col_names = TRUE) ## add formatting to `mtcars` using `wb_dims()`---- wb <- wb_workbook() wb$add_worksheet("test wb_dims() with an object") dims_mtcars_and_col_names <- wb_dims(x = mtcars) wb$add_data(x = mtcars, dims = dims_mtcars_and_col_names) # Put the font as Arial for the data dims_mtcars_data <- wb_dims(x = mtcars, select = "data") wb$add_font(dims = dims_mtcars_data, name = "Arial") # Style col names as bold using the special `select = "col_names"` with `x` provided. dims_column_names <- wb_dims(x = mtcars, select = "col_names") wb$add_font(dims = dims_column_names, bold = TRUE, size = 13) # Finally, to add styling to column "cyl" (the 4th column) (only the data) # there are many options, but here is the preferred one # if you know the column index, wb_dims(x = mtcars, cols = 4) also works. dims_cyl <- wb_dims(x = mtcars, cols = "cyl") wb$add_fill(dims = dims_cyl, color = wb_color("pink")) # Mark a full column as important(with the column name too) wb_dims_vs <- wb_dims(x = mtcars, cols = "vs", select = "x") wb$add_fill(dims = wb_dims_vs, fill = wb_color("yellow")) wb$add_conditional_formatting(dims = wb_dims(x = mtcars, cols = "mpg"), type = "dataBar") # wb_open(wb)
Add a Freeze pane in a worksheet.
wb_freeze_pane( wb, sheet = current_sheet(), first_active_row = NULL, first_active_col = NULL, first_row = FALSE, first_col = FALSE, ... )
wb_freeze_pane( wb, sheet = current_sheet(), first_active_row = NULL, first_active_col = NULL, first_row = FALSE, first_col = FALSE, ... )
wb |
A workbook object |
sheet |
A name or index of a worksheet |
first_active_row |
Top row of active region |
first_active_col |
Furthest left column of active region |
first_row |
If |
first_col |
If |
... |
additional arguments |
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_merge_cells()
## 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", first_active_row = 5, first_active_col = 3) wb$freeze_pane("Sheet 2", first_col = TRUE) ## shortcut to first_active_col = 2 wb$freeze_pane(3, first_row = TRUE) ## shortcut to first_active_row = 2 wb$freeze_pane(4, first_active_row = 1, first_active_col = "D")
## 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", first_active_row = 5, first_active_col = 3) wb$freeze_pane("Sheet 2", first_col = TRUE) ## shortcut to first_active_col = 2 wb$freeze_pane(3, first_row = TRUE) ## shortcut to first_active_row = 2 wb$freeze_pane(4, first_active_row = 1, first_active_col = "D")
List Excel tables in a worksheet
wb_get_tables(wb, sheet = current_sheet())
wb_get_tables(wb, sheet = current_sheet())
wb |
A workbook object |
sheet |
A name or index of a worksheet |
A character vector of table names on the specified sheet
wb <- wb_workbook() wb$add_worksheet(sheet = "Sheet 1") wb$add_data_table(x = iris) wb$add_data_table(x = mtcars, table_name = "mtcars", start_col = 10) wb$get_tables(sheet = "Sheet 1")
wb <- wb_workbook() wb$add_worksheet(sheet = "Sheet 1") wb$add_data_table(x = iris) wb$add_data_table(x = mtcars, table_name = "mtcars", start_col = 10) wb$get_tables(sheet = "Sheet 1")
wb_load()
returns a wbWorkbook object conserving the content of the
original input file, including data, styles, media. This workbook can be
modified, read from, and be written back into a xlsx file.
wb_load(file, sheet, data_only = FALSE, ...)
wb_load(file, sheet, data_only = FALSE, ...)
file |
A path to an existing .xlsx, .xlsm or .xlsb file |
sheet |
optional sheet parameter. if this is applied, only the selected
sheet will be loaded. This can be a numeric, a string or |
data_only |
mode to import if only a data frame should be returned. This
strips the |
... |
additional arguments |
If a specific sheet
is selected, the workbook will still contain sheets
for all worksheets. The argument sheet
and data_only
are used internally
by wb_to_df()
to read from a file with minimal changes. They are not
specifically designed to create rudimentary but otherwise fully functional
workbooks. It is possible to import with
wb_load(data_only = TRUE, sheet = NULL)
. In this way, only a workbook
framework is loaded without worksheets or data. This can be useful if only
some workbook properties are of interest.
There are some internal arguments that can be passed to wb_load, which are
used for development. The debug
argument allows debugging of xlsb
files
in particular. With calc_chain
it is possible to maintain the calculation
chain. The calculation chain is used by spreadsheet software to determine
the order in which formulas are evaluated. Removing the calculation chain
has no known effect. The calculation chain is created the next time the
worksheet is loaded into the spreadsheet. Keeping the calculation chain
could only shorten the loading time in said software. Unfortunately, if a
cell is added to the worksheet, the calculation chain may block the
worksheet as the formulas will not be evaluated again until each individual
cell with a formula is selected in the spreadsheet software and the Enter
key is pressed manually. It is therefore strongly recommended not to
activate this function.
In rare cases, a warning is issued when loading an xlsx file that an xml
namespace has been removed from xml files. This refers to the internal
structure of the loaded xlsx file. Certain xlsx files created by third-party
applications contain a namespace (usually x). This namespace is not required
for the file to work in spreadsheet software and is not expected by
openxlsx2
. It is therefore removed when the file is loaded into a
workbook. Removal is generally considered safe, but the feature is still not
commonly observed, hence the warning.
Initial support for binary openxml files (xlsb
) has been added to the
package. We parse the binary file format into pseudo-openxml files that we
can import. Therefore, once imported, it is possible to interact with the
file as if it had been provided in xlsx file format in the first place. This
parsing into pseudo xml files is of course slower than reading directly from
the binary file. Our implementation is also still missing some functions:
some array formulas are not yet correct, conditional formatting and data
validation are not implemented, nor are pivot tables and slicers.
A Workbook object.
## load existing workbook fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb <- wb_load(file = fl)
## load existing workbook fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb <- wb_load(file = fl)
Worksheet cell merging
wb_merge_cells(wb, sheet = current_sheet(), dims = NULL, solve = FALSE, ...) wb_unmerge_cells(wb, sheet = current_sheet(), dims = NULL, ...)
wb_merge_cells(wb, sheet = current_sheet(), dims = NULL, solve = FALSE, ...) wb_unmerge_cells(wb, sheet = current_sheet(), dims = NULL, ...)
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
dims |
worksheet cells |
solve |
logical if intersecting merges should be solved |
... |
additional arguments |
If using the deprecated arguments rows
and cols
with a merged region must be rectangular,
only min and max of cols
and rows
are used.
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_save()
,
wb_set_last_modified_by()
,
wb_workbook()
Other worksheet content functions:
col_widths-wb
,
filter-wb
,
grouping-wb
,
named_region-wb
,
row_heights-wb
,
wb_add_conditional_formatting()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_thread()
,
wb_freeze_pane()
# Create a new workbook wb <- wb_workbook()$add_worksheet() # Merge cells: Row 2 column C to F (3:6) wb <- wb_merge_cells(wb, dims = "C3:F6") # Merge cells:Rows 10 to 20 columns A to J (1:10) wb <- wb_merge_cells(wb, dims = wb_dims(rows = 10:20, cols = 1:10)) wb$add_worksheet() ## Intersecting merges wb <- wb_merge_cells(wb, dims = wb_dims(cols = 1:10, rows = 1)) wb <- wb_merge_cells(wb, dims = wb_dims(cols = 5:10, rows = 2)) wb <- wb_merge_cells(wb, dims = wb_dims(cols = 1:10, rows = 12)) try(wb_merge_cells(wb, dims = "A1:A10")) ## remove merged cells # removes any intersecting merges wb <- wb_unmerge_cells(wb, dims = wb_dims(cols = 1, rows = 1)) wb <- wb_merge_cells(wb, dims = "A1:A10") # or let us decide how to solve this wb <- wb_merge_cells(wb, dims = "A1:A10", solve = TRUE)
# Create a new workbook wb <- wb_workbook()$add_worksheet() # Merge cells: Row 2 column C to F (3:6) wb <- wb_merge_cells(wb, dims = "C3:F6") # Merge cells:Rows 10 to 20 columns A to J (1:10) wb <- wb_merge_cells(wb, dims = wb_dims(rows = 10:20, cols = 1:10)) wb$add_worksheet() ## Intersecting merges wb <- wb_merge_cells(wb, dims = wb_dims(cols = 1:10, rows = 1)) wb <- wb_merge_cells(wb, dims = wb_dims(cols = 5:10, rows = 2)) wb <- wb_merge_cells(wb, dims = wb_dims(cols = 1:10, rows = 12)) try(wb_merge_cells(wb, dims = "A1:A10")) ## remove merged cells # removes any intersecting merges wb <- wb_unmerge_cells(wb, dims = wb_dims(cols = 1, rows = 1)) wb <- wb_merge_cells(wb, dims = "A1:A10") # or let us decide how to solve this wb <- wb_merge_cells(wb, dims = "A1:A10", solve = TRUE)
You can also use the shorter wb$open()
as a replacement.
To open xlsx files, see xl_open()
.
wb_open(wb)
wb_open(wb)
wb |
a wbWorkbook object |
Get/set order of worksheets in a Workbook object
wb_get_order(wb) wb_set_order(wb, sheets)
wb_get_order(wb) wb_set_order(wb, sheets)
wb |
A |
sheets |
Sheet order |
This function does not reorder the worksheets within the workbook object, it simply shuffles the order when writing to file.
## setup a workbook with 3 worksheets wb <- wb_workbook() wb$add_worksheet("Sheet 1", grid_lines = FALSE) wb$add_data_table(x = iris) wb$add_worksheet("mtcars (Sheet 2)", grid_lines = FALSE) wb$add_data(x = mtcars) wb$add_worksheet("Sheet 3", grid_lines = FALSE) wb$add_data(x = Formaldehyde) wb_get_order(wb) wb$get_sheet_na wb$set_order(c(1, 3, 2)) # switch position of sheets 2 & 3 wb$add_data(2, 'This is still the "mtcars" worksheet', start_col = 15) wb_get_order(wb) wb$get_sheet_names() ## ordering within workbook is not changed wb$set_order(3:1)
## setup a workbook with 3 worksheets wb <- wb_workbook() wb$add_worksheet("Sheet 1", grid_lines = FALSE) wb$add_data_table(x = iris) wb$add_worksheet("mtcars (Sheet 2)", grid_lines = FALSE) wb$add_data(x = mtcars) wb$add_worksheet("Sheet 3", grid_lines = FALSE) wb$add_data(x = Formaldehyde) wb_get_order(wb) wb$get_sheet_na wb$set_order(c(1, 3, 2)) # switch position of sheets 2 & 3 wb$add_data(2, 'This is still the "mtcars" worksheet', start_col = 15) wb_get_order(wb) wb$get_sheet_names() ## ordering within workbook is not changed wb$set_order(3:1)
Set page margins, orientation and print scaling.
wb_page_setup( wb, sheet = current_sheet(), orientation = NULL, scale = 100, left = 0.7, right = 0.7, top = 0.75, bottom = 0.75, header = 0.3, footer = 0.3, fit_to_width = FALSE, fit_to_height = FALSE, paper_size = NULL, print_title_rows = NULL, print_title_cols = NULL, summary_row = NULL, summary_col = NULL, ... )
wb_page_setup( wb, sheet = current_sheet(), orientation = NULL, scale = 100, left = 0.7, right = 0.7, top = 0.75, bottom = 0.75, header = 0.3, footer = 0.3, fit_to_width = FALSE, fit_to_height = FALSE, paper_size = NULL, print_title_rows = NULL, print_title_cols = NULL, summary_row = NULL, summary_col = NULL, ... )
wb |
A workbook object |
sheet |
A name or index of a worksheet |
orientation |
Page orientation. One of "portrait" or "landscape" |
scale |
Print scaling. Numeric value between 10 and 400 |
left , right , top , bottom
|
Page margin in inches |
header , footer
|
Margin in inches |
fit_to_width , fit_to_height
|
An integer that tells the spreadsheet software on how many pages the scaling should fit. This does not actually scale the sheet. |
paper_size |
See details. Default value is 9 (A4 paper). |
print_title_rows , print_title_cols
|
Rows / columns to repeat at top of page when printing. Integer vector. |
summary_row |
Location of summary rows in groupings. One of "Above" or "Below". |
summary_col |
Location of summary columns in groupings. One of "Right" or "Left". |
... |
additional arguments |
When adding fitting to width and height manual adjustment of the scaling factor is required. Setting fit_to_width
and fit_to_height
only tells spreadsheet software that the scaling was applied, but not which scaling was applied.
paper_size
is an integer corresponding to:
size | "paper type" |
1 | Letter paper (8.5 in. by 11 in.) |
2 | Letter small paper (8.5 in. by 11 in.) |
3 | Tabloid paper (11 in. by 17 in.) |
4 | Ledger paper (17 in. by 11 in.) |
5 | Legal paper (8.5 in. by 14 in.) |
6 | Statement paper (5.5 in. by 8.5 in.) |
7 | Executive paper (7.25 in. by 10.5 in.) |
8 | A3 paper (297 mm by 420 mm) |
9 | A4 paper (210 mm by 297 mm) |
10 | A4 small paper (210 mm by 297 mm) |
11 | A5 paper (148 mm by 210 mm) |
12 | B4 paper (250 mm by 353 mm) |
13 | B5 paper (176 mm by 250 mm) |
14 | Folio paper (8.5 in. by 13 in.) |
15 | Quarto paper (215 mm by 275 mm) |
16 | Standard paper (10 in. by 14 in.) |
17 | Standard paper (11 in. by 17 in.) |
18 | Note paper (8.5 in. by 11 in.) |
19 | #9 envelope (3.875 in. by 8.875 in.) |
20 | #10 envelope (4.125 in. by 9.5 in.) |
21 | #11 envelope (4.5 in. by 10.375 in.) |
22 | #12 envelope (4.75 in. by 11 in.) |
23 | #14 envelope (5 in. by 11.5 in.) |
24 | C paper (17 in. by 22 in.) |
25 | D paper (22 in. by 34 in.) |
26 | E paper (34 in. by 44 in.) |
27 | DL envelope (110 mm by 220 mm) |
28 | C5 envelope (162 mm by 229 mm) |
29 | C3 envelope (324 mm by 458 mm) |
30 | C4 envelope (229 mm by 324 mm) |
31 | C6 envelope (114 mm by 162 mm) |
32 | C65 envelope (114 mm by 229 mm) |
33 | B4 envelope (250 mm by 353 mm) |
34 | B5 envelope (176 mm by 250 mm) |
35 | B6 envelope (176 mm by 125 mm) |
36 | Italy envelope (110 mm by 230 mm) |
37 | Monarch envelope (3.875 in. by 7.5 in.) |
38 | 6 3/4 envelope (3.625 in. by 6.5 in.) |
39 | US standard fanfold (14.875 in. by 11 in.) |
40 | German standard fanfold (8.5 in. by 12 in.) |
41 | German legal fanfold (8.5 in. by 13 in.) |
42 | ISO B4 (250 mm by 353 mm) |
43 | Japanese double postcard (200 mm by 148 mm) |
44 | Standard paper (9 in. by 11 in.) |
45 | Standard paper (10 in. by 11 in.) |
46 | Standard paper (15 in. by 11 in.) |
47 | Invite envelope (220 mm by 220 mm) |
50 | Letter extra paper (9.275 in. by 12 in.) |
51 | Legal extra paper (9.275 in. by 15 in.) |
52 | Tabloid extra paper (11.69 in. by 18 in.) |
53 | A4 extra paper (236 mm by 322 mm) |
54 | Letter transverse paper (8.275 in. by 11 in.) |
55 | A4 transverse paper (210 mm by 297 mm) |
56 | Letter extra transverse paper (9.275 in. by 12 in.) |
57 | SuperA/SuperA/A4 paper (227 mm by 356 mm) |
58 | SuperB/SuperB/A3 paper (305 mm by 487 mm) |
59 | Letter plus paper (8.5 in. by 12.69 in.) |
60 | A4 plus paper (210 mm by 330 mm) |
61 | A5 transverse paper (148 mm by 210 mm) |
62 | JIS B5 transverse paper (182 mm by 257 mm) |
63 | A3 extra paper (322 mm by 445 mm) |
64 | A5 extra paper (174 mm by 235 mm) |
65 | ISO B5 extra paper (201 mm by 276 mm) |
66 | A2 paper (420 mm by 594 mm) |
67 | A3 transverse paper (297 mm by 420 mm) |
68 | A3 extra transverse paper (322 mm by 445 mm) |
69 | Japanese Double Postcard (200 mm x 148 mm) 70=A6(105mm x 148mm) |
71 | Japanese Envelope Kaku #2 |
72 | Japanese Envelope Kaku #3 |
73 | Japanese Envelope Chou #3 |
74 | Japanese Envelope Chou #4 |
75 | Letter Rotated (11in x 8 1/2 11 in) |
76 | A3 Rotated (420 mm x 297 mm) |
77 | A4 Rotated (297 mm x 210 mm) |
78 | A5 Rotated (210 mm x 148 mm) |
79 | B4 (JIS) Rotated (364 mm x 257 mm) |
80 | B5 (JIS) Rotated (257 mm x 182 mm) |
81 | Japanese Postcard Rotated (148 mm x 100 mm) |
82 | Double Japanese Postcard Rotated (148 mm x 200 mm) 83 = A6 Rotated (148 mm x 105 mm) |
84 | Japanese Envelope Kaku #2 Rotated |
85 | Japanese Envelope Kaku #3 Rotated |
86 | Japanese Envelope Chou #3 Rotated |
87 | Japanese Envelope Chou #4 Rotated 88=B6(JIS)(128mm x 182mm) |
89 | B6 (JIS) Rotated (182 mm x 128 mm) |
90 | (12 in x 11 in) |
91 | Japanese Envelope You #4 |
92 | Japanese Envelope You #4 Rotated 93=PRC16K(146mm x 215mm) 94=PRC32K(97mm x 151mm) |
95 | PRC 32K(Big) (97 mm x 151 mm) |
96 | PRC Envelope #1 (102 mm x 165 mm) |
97 | PRC Envelope #2 (102 mm x 176 mm) |
98 | PRC Envelope #3 (125 mm x 176 mm) |
99 | PRC Envelope #4 (110 mm x 208 mm) |
100 | PRC Envelope #5 (110 mm x 220 mm) |
101 | PRC Envelope #6 (120 mm x 230 mm) |
102 | PRC Envelope #7 (160 mm x 230 mm) |
103 | PRC Envelope #8 (120 mm x 309 mm) |
104 | PRC Envelope #9 (229 mm x 324 mm) |
105 | PRC Envelope #10 (324 mm x 458 mm) |
106 | PRC 16K Rotated |
107 | PRC 32K Rotated |
108 | PRC 32K(Big) Rotated |
109 | PRC Envelope #1 Rotated (165 mm x 102 mm) |
110 | PRC Envelope #2 Rotated (176 mm x 102 mm) |
111 | PRC Envelope #3 Rotated (176 mm x 125 mm) |
112 | PRC Envelope #4 Rotated (208 mm x 110 mm) |
113 | PRC Envelope #5 Rotated (220 mm x 110 mm) |
114 | PRC Envelope #6 Rotated (230 mm x 120 mm) |
115 | PRC Envelope #7 Rotated (230 mm x 160 mm) |
116 | PRC Envelope #8 Rotated (309 mm x 120 mm) |
117 | PRC Envelope #9 Rotated (324 mm x 229 mm) |
118 | PRC Envelope #10 Rotated (458 mm x 324 mm) |
wb <- wb_workbook() wb$add_worksheet("S1") wb$add_worksheet("S2") wb$add_data_table(1, x = iris[1:30, ]) wb$add_data_table(2, x = iris[1:30, ], dims = c("C5")) ## landscape page scaled to 50% wb$page_setup(sheet = 1, orientation = "landscape", scale = 50) ## portrait page scales to 300% with 0.5in left and right margins wb$page_setup(sheet = 2, orientation = "portrait", scale = 300, left = 0.5, right = 0.5) ## print titles wb$add_worksheet("print_title_rows") wb$add_worksheet("print_title_cols") wb$add_data("print_title_rows", rbind(iris, iris, iris, iris)) wb$add_data("print_title_cols", x = rbind(mtcars, mtcars, mtcars), row_names = TRUE) wb$page_setup(sheet = "print_title_rows", print_title_rows = 1) ## first row wb$page_setup(sheet = "print_title_cols", print_title_cols = 1, print_title_rows = 1)
wb <- wb_workbook() wb$add_worksheet("S1") wb$add_worksheet("S2") wb$add_data_table(1, x = iris[1:30, ]) wb$add_data_table(2, x = iris[1:30, ], dims = c("C5")) ## landscape page scaled to 50% wb$page_setup(sheet = 1, orientation = "landscape", scale = 50) ## portrait page scales to 300% with 0.5in left and right margins wb$page_setup(sheet = 2, orientation = "portrait", scale = 300, left = 0.5, right = 0.5) ## print titles wb$add_worksheet("print_title_rows") wb$add_worksheet("print_title_cols") wb$add_data("print_title_rows", rbind(iris, iris, iris, iris)) wb$add_data("print_title_cols", x = rbind(mtcars, mtcars, mtcars), row_names = TRUE) wb$page_setup(sheet = "print_title_rows", print_title_rows = 1) ## first row wb$page_setup(sheet = "print_title_cols", print_title_cols = 1, print_title_rows = 1)
Protect or unprotect a workbook from modifications by the user in the graphical user interface. Replaces an existing protection.
wb_protect( wb, protect = TRUE, password = NULL, lock_structure = FALSE, lock_windows = FALSE, type = 1, file_sharing = FALSE, username = unname(Sys.info()["user"]), read_only_recommended = FALSE, ... )
wb_protect( wb, protect = TRUE, password = NULL, lock_structure = FALSE, lock_windows = FALSE, type = 1, file_sharing = FALSE, username = unname(Sys.info()["user"]), read_only_recommended = FALSE, ... )
wb |
A Workbook object |
protect |
Whether to protect or unprotect the sheet (default |
password |
(optional) password required to unprotect the workbook |
lock_structure |
Whether the workbook structure should be locked |
lock_windows |
Whether the window position of the spreadsheet should be locked |
type |
Lock type (see Details) |
file_sharing |
Whether to enable a popup requesting the unlock password is prompted |
username |
The username for the |
read_only_recommended |
Whether or not a post unlock message appears stating that the workbook is recommended to be opened in read-only mode. |
... |
additional arguments |
Lock types:
1
xlsx with password (default)
2
xlsx recommends read-only
4
xlsx enforces read-only
8
xlsx is locked for annotation
wb <- wb_workbook() wb$add_worksheet("S1") wb_protect(wb, protect = TRUE, password = "Password", lock_structure = TRUE) # Remove the protection wb_protect(wb, protect = FALSE) wb <- wb_protect( wb, protect = TRUE, password = "Password", lock_structure = TRUE, type = 2L, file_sharing = TRUE, username = "Test", read_only_recommended = TRUE )
wb <- wb_workbook() wb$add_worksheet("S1") wb_protect(wb, protect = TRUE, password = "Password", lock_structure = TRUE) # Remove the protection wb_protect(wb, protect = FALSE) wb <- wb_protect( wb, protect = TRUE, password = "Password", lock_structure = TRUE, type = 2L, file_sharing = TRUE, username = "Test", read_only_recommended = TRUE )
Protect or unprotect a worksheet from modifications by the user in the graphical user interface. Replaces an existing protection. Certain features require applying unlocking of initialized cells in the worksheet and across columns and/or rows.
wb_protect_worksheet( wb, sheet = current_sheet(), protect = TRUE, password = NULL, properties = NULL )
wb_protect_worksheet( wb, sheet = current_sheet(), protect = TRUE, password = NULL, properties = NULL )
wb |
A workbook object |
sheet |
A name or index of a worksheet |
protect |
Whether to protect or unprotect the sheet (default=TRUE) |
password |
(optional) password required to unprotect the worksheet |
properties |
A character vector of properties to lock. Can be one or
more of the following: |
wb <- wb_workbook() wb$add_worksheet("S1") wb$add_data_table(1, x = iris[1:30, ]) wb$protect_worksheet( "S1", protect = TRUE, properties = c("formatCells", "formatColumns", "insertColumns", "deleteColumns") ) # Formatting cells / columns is allowed , but inserting / deleting columns is protected: wb$protect_worksheet( "S1", protect = TRUE, c(formatCells = FALSE, formatColumns = FALSE, insertColumns = TRUE, deleteColumns = TRUE) ) # Remove the protection wb$protect_worksheet("S1", protect = FALSE)
wb <- wb_workbook() wb$add_worksheet("S1") wb$add_data_table(1, x = iris[1:30, ]) wb$protect_worksheet( "S1", protect = TRUE, properties = c("formatCells", "formatColumns", "insertColumns", "deleteColumns") ) # Formatting cells / columns is allowed , but inserting / deleting columns is protected: wb$protect_worksheet( "S1", protect = TRUE, c(formatCells = FALSE, formatColumns = FALSE, insertColumns = TRUE, deleteColumns = TRUE) ) # Remove the protection wb$protect_worksheet("S1", protect = FALSE)
Remove Excel tables in a workbook using its name.
wb_remove_tables(wb, sheet = current_sheet(), table, remove_data = TRUE)
wb_remove_tables(wb, sheet = current_sheet(), table, remove_data = TRUE)
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
table |
Name of table to remove. Use |
remove_data |
Default |
The wbWorkbook
, invisibly
wb <- wb_workbook() wb$add_worksheet(sheet = "Sheet 1") wb$add_worksheet(sheet = "Sheet 2") wb$add_data_table(sheet = "Sheet 1", x = iris, table_name = "iris") wb$add_data_table(sheet = 1, x = mtcars, table_name = "mtcars", start_col = 10) ## delete worksheet removes table objects wb <- wb_remove_worksheet(wb, sheet = 1) wb$add_data_table(sheet = 1, x = iris, table_name = "iris") wb$add_data_table(sheet = 1, x = mtcars, table_name = "mtcars", start_col = 10) ## wb_remove_tables() deletes table object and all data wb_get_tables(wb, sheet = 1) wb$remove_tables(sheet = 1, table = "iris") wb$add_data_table(sheet = 1, x = iris, table_name = "iris") wb_get_tables(wb, sheet = 1) wb$remove_tables(sheet = 1, table = "iris")
wb <- wb_workbook() wb$add_worksheet(sheet = "Sheet 1") wb$add_worksheet(sheet = "Sheet 2") wb$add_data_table(sheet = "Sheet 1", x = iris, table_name = "iris") wb$add_data_table(sheet = 1, x = mtcars, table_name = "mtcars", start_col = 10) ## delete worksheet removes table objects wb <- wb_remove_worksheet(wb, sheet = 1) wb$add_data_table(sheet = 1, x = iris, table_name = "iris") wb$add_data_table(sheet = 1, x = mtcars, table_name = "mtcars", start_col = 10) ## wb_remove_tables() deletes table object and all data wb_get_tables(wb, sheet = 1) wb$remove_tables(sheet = 1, table = "iris") wb$add_data_table(sheet = 1, x = iris, table_name = "iris") wb_get_tables(wb, sheet = 1) wb$remove_tables(sheet = 1, table = "iris")
Remove a worksheet from a workbook
wb_remove_worksheet(wb, sheet = current_sheet())
wb_remove_worksheet(wb, sheet = current_sheet())
wb |
A wbWorkbook object |
sheet |
The sheet name or index to remove |
The wbWorkbook
object, invisibly.
## load a workbook wb <- wb_load(file = system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")) ## Remove sheet 2 wb <- wb_remove_worksheet(wb, 2)
## load a workbook wb <- wb_load(file = system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")) ## Remove sheet 2 wb <- wb_remove_worksheet(wb, 2)
Save a workbook to file
wb_save(wb, file = NULL, overwrite = TRUE, path = NULL)
wb_save(wb, file = NULL, overwrite = TRUE, path = NULL)
wb |
A |
file |
A path to save the workbook to |
overwrite |
If |
path |
Deprecated argument. Please use |
the wbWorkbook
object, invisibly
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_set_last_modified_by()
,
wb_workbook()
## 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 wb_save(wb, file = temp_xlsx(), overwrite = TRUE)
## 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 wb_save(wb, file = temp_xlsx(), overwrite = TRUE)
Set the workbook position, size and filter
wb_set_bookview( wb, active_tab = NULL, auto_filter_date_grouping = NULL, first_sheet = NULL, minimized = NULL, show_horizontal_scroll = NULL, show_sheet_tabs = NULL, show_vertical_scroll = NULL, tab_ratio = NULL, visibility = NULL, window_height = NULL, window_width = NULL, x_window = NULL, y_window = NULL, ... )
wb_set_bookview( wb, active_tab = NULL, auto_filter_date_grouping = NULL, first_sheet = NULL, minimized = NULL, show_horizontal_scroll = NULL, show_sheet_tabs = NULL, show_vertical_scroll = NULL, tab_ratio = NULL, visibility = NULL, window_height = NULL, window_width = NULL, x_window = NULL, y_window = NULL, ... )
wb |
A wbWorkbook object |
active_tab |
activeTab |
auto_filter_date_grouping |
autoFilterDateGrouping |
first_sheet |
The first sheet to be displayed |
minimized |
minimized |
show_horizontal_scroll |
showHorizontalScroll |
show_sheet_tabs |
showSheetTabs |
show_vertical_scroll |
showVerticalScroll |
tab_ratio |
tabRatio |
visibility |
visibility |
window_height |
windowHeight |
window_width |
windowWidth |
x_window |
xWindow |
y_window |
yWindow |
... |
additional arguments |
The Workbook object
Set worksheet grid lines to show or hide.
You can also add / remove grid lines when creating a worksheet with
wb_add_worksheet(grid_lines = FALSE)
wb_set_grid_lines(wb, sheet = current_sheet(), show = FALSE, print = show) wb_grid_lines(wb, sheet = current_sheet(), show = FALSE, print = show)
wb_set_grid_lines(wb, sheet = current_sheet(), show = FALSE, print = show) wb_grid_lines(wb, sheet = current_sheet(), show = FALSE, print = show)
wb |
A workbook object |
sheet |
A name or index of a worksheet |
show |
A logical. If |
print |
A logical. If |
wb <- wb_workbook()$add_worksheet()$add_worksheet() wb$get_sheet_names() ## list worksheets in workbook wb$set_grid_lines(1, show = FALSE) wb$set_grid_lines("Sheet 2", show = FALSE)
wb <- wb_workbook()$add_worksheet()$add_worksheet() wb$get_sheet_names() ## list worksheets in workbook wb$set_grid_lines(1, show = FALSE) wb$set_grid_lines("Sheet 2", show = FALSE)
Just a wrapper of wb$set_last_modified_by()
wb_set_last_modified_by(wb, name, ...)
wb_set_last_modified_by(wb, name, ...)
wb |
A workbook object |
name |
A string object with the name of the LastModifiedBy-User |
... |
additional arguments |
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_workbook()
wb <- wb_workbook() wb_set_last_modified_by(wb, "test")
wb <- wb_workbook() wb_set_last_modified_by(wb, "test")
This helps set a worksheet's appearance, such as the zoom, whether to show grid lines
wb_set_sheetview( wb, sheet = current_sheet(), color_id = NULL, default_grid_color = NULL, right_to_left = NULL, show_formulas = NULL, show_grid_lines = NULL, show_outline_symbols = NULL, show_row_col_headers = NULL, show_ruler = NULL, show_white_space = NULL, show_zeros = NULL, tab_selected = NULL, top_left_cell = NULL, view = NULL, window_protection = NULL, workbook_view_id = NULL, zoom_scale = NULL, zoom_scale_normal = NULL, zoom_scale_page_layout_view = NULL, zoom_scale_sheet_layout_view = NULL, ... )
wb_set_sheetview( wb, sheet = current_sheet(), color_id = NULL, default_grid_color = NULL, right_to_left = NULL, show_formulas = NULL, show_grid_lines = NULL, show_outline_symbols = NULL, show_row_col_headers = NULL, show_ruler = NULL, show_white_space = NULL, show_zeros = NULL, tab_selected = NULL, top_left_cell = NULL, view = NULL, window_protection = NULL, workbook_view_id = NULL, zoom_scale = NULL, zoom_scale_normal = NULL, zoom_scale_page_layout_view = NULL, zoom_scale_sheet_layout_view = NULL, ... )
wb |
A Workbook object |
sheet |
sheet |
color_id , default_grid_color
|
Integer: A color, default is 64 |
right_to_left |
Logical: if |
show_formulas |
Logical: if |
show_grid_lines |
Logical: if |
show_outline_symbols |
Logical: if |
show_row_col_headers |
Logical: if |
show_ruler |
Logical: if |
show_white_space |
Logical: if |
show_zeros |
Logical: if |
tab_selected |
Integer: zero vector indicating the selected tab |
top_left_cell |
Cell: the cell shown in the top left corner / or top right with rightToLeft |
view |
View: "normal", "pageBreakPreview" or "pageLayout" |
window_protection |
Logical: if |
workbook_view_id |
integer: Pointing to some other view inside the workbook |
zoom_scale , zoom_scale_normal , zoom_scale_page_layout_view , zoom_scale_sheet_layout_view
|
Integer: the zoom scale should be between 10 and 400. These are values for current, normal etc. |
... |
additional arguments |
The wbWorkbook
object, invisibly
wb <- wb_workbook()$add_worksheet() wb$set_sheetview( zoom_scale = 75, right_to_left = FALSE, show_formulas = TRUE, show_grid_lines = TRUE, show_outline_symbols = FALSE, show_row_col_headers = TRUE, show_ruler = TRUE, show_white_space = FALSE, tab_selected = 1, top_left_cell = "B1", view = "normal", window_protection = TRUE )
wb <- wb_workbook()$add_worksheet() wb$set_sheetview( zoom_scale = 75, right_to_left = FALSE, show_formulas = TRUE, show_grid_lines = TRUE, show_outline_symbols = FALSE, show_row_col_headers = TRUE, show_ruler = TRUE, show_white_space = FALSE, tab_selected = 1, top_left_cell = "B1", view = "normal", window_protection = TRUE )
Simple function to create a data.frame
from a sheet in workbook. Simple as
in it was simply written down. read_xlsx()
and wb_read()
are just
internal wrappers of wb_to_df()
intended for people coming from other
packages.
wb_to_df( file, sheet, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, skip_hidden_rows = FALSE, skip_hidden_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, na.strings = "#N/A", na.numbers = NA, fill_merged_cells = FALSE, dims, show_formula = FALSE, convert = TRUE, types, named_region, keep_attributes = FALSE, check_names = FALSE, show_hyperlinks = FALSE, ... ) read_xlsx( file, sheet, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, named_region, na.strings = "#N/A", na.numbers = NA, fill_merged_cells = FALSE, check_names = FALSE, show_hyperlinks = FALSE, ... ) wb_read( file, sheet = 1, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, named_region, na.strings = "NA", na.numbers = NA, check_names = FALSE, show_hyperlinks = FALSE, ... )
wb_to_df( file, sheet, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, skip_hidden_rows = FALSE, skip_hidden_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, na.strings = "#N/A", na.numbers = NA, fill_merged_cells = FALSE, dims, show_formula = FALSE, convert = TRUE, types, named_region, keep_attributes = FALSE, check_names = FALSE, show_hyperlinks = FALSE, ... ) read_xlsx( file, sheet, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, named_region, na.strings = "#N/A", na.numbers = NA, fill_merged_cells = FALSE, check_names = FALSE, show_hyperlinks = FALSE, ... ) wb_read( file, sheet = 1, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, named_region, na.strings = "NA", na.numbers = NA, check_names = FALSE, show_hyperlinks = FALSE, ... )
file |
An xlsx file, wbWorkbook object or URL to xlsx file. |
sheet |
Either sheet name or index. When missing the first sheet in the workbook is selected. |
start_row |
first row to begin looking for data. |
start_col |
first column to begin looking for data. |
row_names |
If |
col_names |
If |
skip_empty_rows |
If |
skip_empty_cols |
If |
If |
|
If |
|
rows |
A numeric vector specifying which rows in the xlsx file to read.
If |
cols |
A numeric vector specifying which columns in the xlsx file to read.
If |
detect_dates |
If |
na.strings |
A character vector of strings which are to be interpreted as |
na.numbers |
A numeric vector of digits which are to be interpreted as |
fill_merged_cells |
If |
dims |
Character string of type "A1:B2" as optional dimensions to be imported. |
show_formula |
If |
convert |
If |
types |
A named numeric indicating, the type of the data. Names must match the returned data. See Details for more. |
named_region |
Character string with a |
keep_attributes |
If |
check_names |
If |
show_hyperlinks |
If |
... |
additional arguments |
The returned data frame will have named rows matching the rows of the
worksheet. With col_names = FALSE
the returned data frame will have
column names matching the columns of the worksheet. Otherwise the first
row is selected as column name.
Depending if the R package hms
is loaded, wb_to_df()
returns
hms
variables or string variables in the hh:mm:ss
format.
The types
argument can be a named numeric or a character string of the
matching R variable type. Either c(foo = 1)
or c(foo = "numeric")
.
0: character
1: numeric
2: Date
3: POSIXct (datetime)
4: logical
If no type is specified, the column types are derived based on all cells
in a column within the selected data range, excluding potential column
names. If keep_attr
is TRUE
, the derived column types can be inspected
as an attribute of the data frame.
wb_to_df()
will not pick up formulas added to a workbook object
via wb_add_formula()
. This is because only the formula is written and left
to be evaluated when the file is opened in a spreadsheet software.
Opening, saving and closing the file in a spreadsheet software will resolve
this.
########################################################################### # numerics, dates, missings, bool and string example_file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb1 <- wb_load(example_file) # import workbook wb_to_df(wb1) # do not convert first row to column names wb_to_df(wb1, col_names = FALSE) # do not try to identify dates in the data wb_to_df(wb1, detect_dates = FALSE) # return the underlying Excel formula instead of their values wb_to_df(wb1, show_formula = TRUE) # read dimension without colNames wb_to_df(wb1, dims = "A2:C5", col_names = FALSE) # read selected cols wb_to_df(wb1, cols = c("A:B", "G")) # read selected rows wb_to_df(wb1, rows = c(2, 4, 6)) # convert characters to numerics and date (logical too?) wb_to_df(wb1, convert = FALSE) # erase empty rows from dataset wb_to_df(wb1, skip_empty_rows = TRUE) # erase empty columns from dataset wb_to_df(wb1, skip_empty_cols = TRUE) # convert first row to rownames wb_to_df(wb1, sheet = 2, dims = "C6:G9", row_names = TRUE) # define type of the data.frame wb_to_df(wb1, cols = c(2, 5), types = c("Var1" = 0, "Var3" = 1)) # start in row 5 wb_to_df(wb1, start_row = 5, col_names = FALSE) # na string wb_to_df(wb1, na.strings = "a") ########################################################################### # Named regions file_named_region <- system.file("extdata", "namedRegions3.xlsx", package = "openxlsx2") wb2 <- wb_load(file_named_region) # read dataset with named_region (returns global first) wb_to_df(wb2, named_region = "MyRange", col_names = FALSE) # read named_region from sheet wb_to_df(wb2, named_region = "MyRange", sheet = 4, col_names = FALSE) # read_xlsx() and wb_read() example_file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") read_xlsx(file = example_file) df1 <- wb_read(file = example_file, sheet = 1) df2 <- wb_read(file = example_file, sheet = 1, rows = c(1, 3, 5), cols = 1:3)
########################################################################### # numerics, dates, missings, bool and string example_file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") wb1 <- wb_load(example_file) # import workbook wb_to_df(wb1) # do not convert first row to column names wb_to_df(wb1, col_names = FALSE) # do not try to identify dates in the data wb_to_df(wb1, detect_dates = FALSE) # return the underlying Excel formula instead of their values wb_to_df(wb1, show_formula = TRUE) # read dimension without colNames wb_to_df(wb1, dims = "A2:C5", col_names = FALSE) # read selected cols wb_to_df(wb1, cols = c("A:B", "G")) # read selected rows wb_to_df(wb1, rows = c(2, 4, 6)) # convert characters to numerics and date (logical too?) wb_to_df(wb1, convert = FALSE) # erase empty rows from dataset wb_to_df(wb1, skip_empty_rows = TRUE) # erase empty columns from dataset wb_to_df(wb1, skip_empty_cols = TRUE) # convert first row to rownames wb_to_df(wb1, sheet = 2, dims = "C6:G9", row_names = TRUE) # define type of the data.frame wb_to_df(wb1, cols = c(2, 5), types = c("Var1" = 0, "Var3" = 1)) # start in row 5 wb_to_df(wb1, start_row = 5, col_names = FALSE) # na string wb_to_df(wb1, na.strings = "a") ########################################################################### # Named regions file_named_region <- system.file("extdata", "namedRegions3.xlsx", package = "openxlsx2") wb2 <- wb_load(file_named_region) # read dataset with named_region (returns global first) wb_to_df(wb2, named_region = "MyRange", col_names = FALSE) # read named_region from sheet wb_to_df(wb2, named_region = "MyRange", sheet = 4, col_names = FALSE) # read_xlsx() and wb_read() example_file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") read_xlsx(file = example_file) df1 <- wb_read(file = example_file, sheet = 1) df2 <- wb_read(file = example_file, sheet = 1, rows = c(1, 3, 5), cols = 1:3)
Update the position of a data table, possibly written using wb_add_data_table()
wb_update_table(wb, sheet = current_sheet(), dims = "A1", tabname)
wb_update_table(wb, sheet = current_sheet(), dims = "A1", tabname)
wb |
A workbook |
sheet |
A worksheet |
dims |
Cell range used for new data table. |
tabname |
A table name |
Be aware that this function does not alter any filter. Excluding or adding rows does not make rows appear nor will it hide them.
wb <- wb_workbook()$add_worksheet()$add_data_table(x = mtcars) wb$update_table(tabname = "Table1", dims = "A1:J4")
wb <- wb_workbook()$add_worksheet()$add_data_table(x = mtcars) wb$update_table(tabname = "Table1", dims = "A1:J4")
Initialize a wbWorkbook object. You can set workbook properties as well.
wb_workbook( creator = NULL, title = NULL, subject = NULL, category = NULL, datetime_created = Sys.time(), datetime_modified = NULL, theme = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, ... )
wb_workbook( creator = NULL, title = NULL, subject = NULL, category = NULL, datetime_created = Sys.time(), datetime_modified = NULL, theme = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, ... )
creator |
Creator of the workbook (your name). Defaults to login username or |
title , subject , category , keywords , comments , manager , company
|
Workbook property, a string. |
datetime_created |
The time of the workbook is created |
datetime_modified |
The time of the workbook was last modified |
theme |
Optional theme identified by string or number. See Details for options. |
... |
additional arguments |
theme
can be one of
"Atlas", "Badge", "Berlin", "Celestial", "Crop", "Depth", "Droplet",
"Facet", "Feathered", "Gallery", "Headlines", "Integral", "Ion",
"Ion Boardroom", "LibreOffice", "Madison", "Main Event", "Mesh",
"Office 2007 - 2010 Theme", "Office 2013 - 2022 Theme", "Office Theme",
"Old Office Theme", "Organic", "Parallax", "Parcel", "Retrospect",
"Savon", "Slice", "Vapor Trail", "View", "Wisp", "Wood Type"
A wbWorkbook
object
Other workbook wrappers:
base_font-wb
,
col_widths-wb
,
creators-wb
,
grouping-wb
,
row_heights-wb
,
wb_add_chartsheet()
,
wb_add_data()
,
wb_add_data_table()
,
wb_add_formula()
,
wb_add_hyperlink()
,
wb_add_pivot_table()
,
wb_add_slicer()
,
wb_add_worksheet()
,
wb_base_colors
,
wb_clone_worksheet()
,
wb_copy_cells()
,
wb_freeze_pane()
,
wb_merge_cells()
,
wb_save()
,
wb_set_last_modified_by()
## 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" )
## 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" )
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.
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.
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.
# 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_dims = "D4")) # 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
).
sheet_names
The names of the sheets
calcChain
calcChain
charts
charts
is_chartsheet
A logical vector identifying if a sheet is a chartsheet.
customXml
customXml
connections
connections
ctrlProps
ctrlProps
Content_Types
Content_Types
app
app
core
The XML core
custom
custom
drawings
drawings
drawings_rels
drawings_rels
docMetadata
doc_meta_data
embeddings
embeddings
externalLinks
externalLinks
externalLinksRels
externalLinksRels
headFoot
The header and footer
media
media
metadata
contains cell/value metadata imported on load from xl/metadata.xml
persons
Persons of the workbook. to be used with wb_add_thread()
pivotTables
pivotTables
pivotTables.xml.rels
pivotTables.xml.rels
pivotDefinitions
pivotDefinitions
pivotRecords
pivotRecords
pivotDefinitionsRels
pivotDefinitionsRels
queryTables
queryTables
richData
richData
slicers
slicers
slicerCaches
slicerCaches
sharedStrings
sharedStrings
styles_mgr
styles_mgr
tables
tables
tables.xml.rels
tables.xml.rels
theme
theme
vbaProject
vbaProject
vml
vml
vml_rels
vml_rels
comments
Comments (notes) present in the workbook.
threadComments
Threaded comments
timelines
timelines
timelineCaches
timelineCaches
workbook
workbook
workbook.xml.rels
workbook.xml.rels
worksheets
worksheets
worksheets_rels
worksheets_rels
sheetOrder
The sheet order. Controls ordering for worksheets and worksheet names.
path
path
new()
Creates a new wbWorkbook
object
wbWorkbook$new( creator = NULL, title = NULL, subject = NULL, category = NULL, datetime_created = Sys.time(), datetime_modified = NULL, theme = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, ... )
creator
character vector of creators. Duplicated are ignored.
title, subject, category, keywords, comments, manager, company
workbook properties
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.
datetime_modified
The datetime (as POSIXt
) that should be recorded
as last modification date. Defaults to the creation date.
theme
Optional theme identified by string or number
...
additional arguments
a wbWorkbook
object
append()
Append a field. This method is intended for internal use
wbWorkbook$append(field, value)
field
A valid field name
value
A value for the field
append_sheets()
Append to self$workbook$sheets
This method is intended for internal use
wbWorkbook$append_sheets(value)
value
A value for self$workbook$sheets
validate_sheet()
validate sheet
wbWorkbook$validate_sheet(sheet)
sheet
A character sheet name or integer location
The integer position of the sheet
add_chartsheet()
Add a chart sheet to the workbook
wbWorkbook$add_chartsheet( sheet = next_sheet(), tab_color = NULL, zoom = 100, visible = c("true", "false", "hidden", "visible", "veryhidden"), ... )
sheet
The name of the sheet
tab_color
tab_color
zoom
zoom
visible
visible
...
additional arguments
The wbWorkbook
object, invisibly
add_worksheet()
Add worksheet to the wbWorkbook
object
wbWorkbook$add_worksheet( 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)), ... )
sheet
The name of the sheet
grid_lines
gridLines
row_col_headers
rowColHeaders
tab_color
tabColor
zoom
zoom
header
header
footer
footer
odd_header
oddHeader
odd_footer
oddFooter
even_header
evenHeader
even_footer
evenFooter
first_header
firstHeader
first_footer
firstFooter
visible
visible
has_drawing
hasDrawing
paper_size
paperSize
orientation
orientation
hdpi
hdpi
vdpi
vdpi
...
additional arguments
The wbWorkbook
object, invisibly
clone_worksheet()
Clone a workbooksheet to another workbook
wbWorkbook$clone_worksheet( old = current_sheet(), new = next_sheet(), from = NULL )
old
name of worksheet to clone
new
name of new worksheet to add
from
name of new worksheet to add
add_data()
add data
wbWorkbook$add_data( sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, array = FALSE, col_names = TRUE, row_names = FALSE, with_filter = FALSE, name = NULL, sep = ", ", apply_cell_style = TRUE, remove_cell_style = FALSE, na.strings = na_strings(), inline_strings = TRUE, enforce = FALSE, ... )
sheet
The name of the sheet
x
x
dims
Cell range in a sheet
start_col
startCol
start_row
startRow
array
array
col_names
colNames
row_names
rowNames
with_filter
withFilter
name
name
sep
sep
apply_cell_style
applyCellStyle
remove_cell_style
if writing into existing cells, should the cell style be removed?
na.strings
Value used for replacing NA
values from x
. Default
na_strings()
uses the special #N/A
value within the workbook.
inline_strings
write characters as inline strings
enforce
enforce that selected dims is filled. For this to work, dims
must match x
...
additional arguments
return
The wbWorkbook
object
add_data_table()
add a data table
wbWorkbook$add_data_table( sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, col_names = TRUE, row_names = FALSE, table_style = "TableStyleLight9", table_name = NULL, with_filter = TRUE, sep = ", ", first_column = FALSE, last_column = FALSE, banded_rows = TRUE, banded_cols = FALSE, apply_cell_style = TRUE, remove_cell_style = FALSE, na.strings = na_strings(), inline_strings = TRUE, total_row = FALSE, ... )
sheet
The name of the sheet
x
x
dims
Cell range in a sheet
start_col
startCol
start_row
startRow
col_names
colNames
row_names
rowNames
table_style
tableStyle
table_name
tableName
with_filter
withFilter
sep
sep
first_column
firstColumn
last_column
lastColumn
banded_rows
bandedRows
banded_cols
bandedCols
apply_cell_style
applyCellStyle
remove_cell_style
if writing into existing cells, should the cell style be removed?
na.strings
Value used for replacing NA
values from x
. Default
na_strings()
uses the special #N/A
value within the workbook.
inline_strings
write characters as inline strings
total_row
write total rows to table
...
additional arguments
The wbWorkbook
object
add_pivot_table()
add pivot table
wbWorkbook$add_pivot_table( x, sheet = next_sheet(), dims = "A3", filter, rows, cols, data, fun, params, pivot_table, slicer, timeline )
x
a wb_data object
sheet
The name of the sheet
dims
the worksheet cell where the pivot table is placed
filter
a character object with names used to filter
rows
a character object with names used as rows
cols
a character object with names used as cols
data
a character object with names used as data
fun
a character object of functions to be used with the data
params
a list of parameters to modify pivot table creation
pivot_table
a character object with a name for the pivot table
slicer
a character object with names used as slicer
timeline
a character object with names used as timeline
fun
can be either of AVERAGE, COUNT, COUNTA, MAX, MIN, PRODUCT, STDEV,
STDEVP, SUM, VAR, VARP
The wbWorkbook
object
add_slicer()
add pivot table
wbWorkbook$add_slicer( x, dims = "A1", sheet = current_sheet(), pivot_table, slicer, params )
x
a wb_data object
dims
the worksheet cell where the pivot table is placed
sheet
The name of the sheet
pivot_table
the name of a pivot table on the selected sheet
slicer
a variable used as slicer for the pivot table
params
a list of parameters to modify pivot table creation
The wbWorkbook
object
remove_slicer()
add pivot table
wbWorkbook$remove_slicer(sheet = current_sheet())
sheet
The name of the sheet
The wbWorkbook
object
add_timeline()
add pivot table
wbWorkbook$add_timeline( x, dims = "A1", sheet = current_sheet(), pivot_table, timeline, params )
x
a wb_data object
dims
the worksheet cell where the pivot table is placed
sheet
The name of the sheet
pivot_table
the name of a pivot table on the selected sheet
timeline
a variable used as timeline for the pivot table
params
a list of parameters to modify pivot table creation
The wbWorkbook
object
remove_timeline()
add pivot table
wbWorkbook$remove_timeline(sheet = current_sheet())
sheet
The name of the sheet
The wbWorkbook
object
add_formula()
Add formula
wbWorkbook$add_formula( sheet = current_sheet(), x, dims = wb_dims(start_row, start_col), start_col = 1, start_row = 1, array = FALSE, cm = FALSE, apply_cell_style = TRUE, remove_cell_style = FALSE, enforce = FALSE, shared = FALSE, name = NULL, ... )
sheet
The name of the sheet
x
x
dims
Cell range in a sheet
start_col
startCol
start_row
startRow
array
array
cm
cm
apply_cell_style
applyCellStyle
remove_cell_style
if writing into existing cells, should the cell style be removed?
enforce
enforce dims
shared
shared formula
name
name
...
additional arguments
The wbWorkbook
object
add_hyperlink()
Add hyperlink
wbWorkbook$add_hyperlink( sheet = current_sheet(), dims = "A1", target = NULL, tooltip = NULL, is_external = TRUE, col_names = FALSE )
sheet
sheet
dims
dims
target
target
tooltip
tooltip
is_external
is_external
col_names
col_names
The wbWorkbook
object
remove_hyperlink()
remove hyperlink
wbWorkbook$remove_hyperlink(sheet = current_sheet(), dims = NULL)
sheet
sheet
dims
dims
The wbWorkbook
object
add_style()
add style
wbWorkbook$add_style(style = NULL, style_name = NULL)
style
style
style_name
style_name
The wbWorkbook
object
to_df()
to_df
wbWorkbook$to_df( sheet, start_row = 1, start_col = NULL, row_names = FALSE, col_names = TRUE, skip_empty_rows = FALSE, skip_empty_cols = FALSE, skip_hidden_rows = FALSE, skip_hidden_cols = FALSE, rows = NULL, cols = NULL, detect_dates = TRUE, na.strings = "#N/A", na.numbers = NA, fill_merged_cells = FALSE, dims, show_formula = FALSE, convert = TRUE, types, named_region, keep_attributes = FALSE, check_names = FALSE, show_hyperlinks = FALSE, ... )
sheet
Either sheet name or index. When missing the first sheet in the workbook is selected.
start_row
first row to begin looking for data.
start_col
first column to begin looking for data.
row_names
If TRUE, the first col of data will be used as row names.
col_names
If TRUE, the first row of data will be used as column names.
skip_empty_rows
If TRUE, empty rows are skipped.
skip_empty_cols
If TRUE, empty columns are skipped.
skip_hidden_rows
If TRUE, hidden rows are skipped.
skip_hidden_cols
If TRUE, hidden columns are skipped.
rows
A numeric vector specifying which rows in the Excel file to read. If NULL, all rows are read.
cols
A numeric vector specifying which columns in the Excel file to read. If NULL, all columns are read.
detect_dates
If TRUE, attempt to recognize dates and perform conversion.
na.strings
A character vector of strings which are to be interpreted as NA. Blank cells will be returned as NA.
na.numbers
A numeric vector of digits which are to be interpreted as NA. Blank cells will be returned as NA.
fill_merged_cells
If TRUE, the value in a merged cell is given to all cells within the merge.
dims
Character string of type "A1:B2" as optional dimensions to be imported.
show_formula
If TRUE, the underlying Excel formulas are shown.
convert
If TRUE, a conversion to dates and numerics is attempted.
types
A named numeric indicating, the type of the data. 0: character, 1: numeric, 2: date, 3: posixt, 4:logical. Names must match the returned data
named_region
Character string with a named_region (defined name or table). If no sheet is selected, the first appearance will be selected.
keep_attributes
If TRUE additional attributes are returned. (These are used internally to define a cell type.)
check_names
If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names.
show_hyperlinks
If TRUE
instead of the displayed text, hyperlink targets are shown.
...
additional arguments
a data frame
load()
load workbook
wbWorkbook$load(file, sheet, data_only = FALSE, ...)
file
file
sheet
The name of the sheet
data_only
data_only
...
additional arguments
The wbWorkbook
object invisibly
save()
Save the workbook
wbWorkbook$save(file = self$path, overwrite = TRUE, path = NULL)
file
The path to save the workbook to
overwrite
If FALSE
, will not overwrite when path
exists
path
Deprecated argument previously used for file. Please use file in new code.
The wbWorkbook
object invisibly
open()
open wbWorkbook in Excel.
wbWorkbook$open(interactive = NA)
interactive
If FALSE
will throw a warning and not open the path.
This can be manually set to TRUE
, otherwise when NA
(default) uses
the value returned from base::interactive()
minor helper wrapping xl_open which does the entire same thing
The wbWorkbook
, invisibly
buildTable()
Build table
wbWorkbook$buildTable( sheet = current_sheet(), colNames, ref, showColNames, tableStyle, tableName, withFilter = TRUE, totalsRowCount = 0, totalLabel = FALSE, showFirstColumn = 0, showLastColumn = 0, showRowStripes = 1, showColumnStripes = 0 )
sheet
The name of the sheet
colNames
colNames
ref
ref
showColNames
showColNames
tableStyle
tableStyle
tableName
tableName
withFilter
withFilter
totalsRowCount
totalsRowCount
totalLabel
totalLabel
showFirstColumn
showFirstColumn
showLastColumn
showLastColumn
showRowStripes
showRowStripes
showColumnStripes
showColumnStripes
The wbWorksheet
object, invisibly
update_table()
update a data_table
wbWorkbook$update_table(sheet = current_sheet(), dims = "A1", tabname)
sheet
The name of the sheet
dims
Cell range in a sheet
tabname
a tablename
The wbWorksheet
object, invisibly
copy_cells()
copy cells around in a workbook
wbWorkbook$copy_cells( sheet = current_sheet(), dims = "A1", data, as_value = FALSE, as_ref = FALSE, transpose = FALSE, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
data
a wb_data object
as_value
should a copy of the value be written
as_ref
should references to the cell be written
transpose
should the data be written transposed
...
additional arguments passed to add_data() if used with as_value
The wbWorksheet
object, invisibly
get_base_font()
Get the base font
wbWorkbook$get_base_font()
A list of of the font
set_base_font()
Set the base font
wbWorkbook$set_base_font( font_size = 11, font_color = wb_color(theme = "1"), font_name = "Aptos Narrow", ... )
font_size
fontSize
font_color
font_color
font_name
font_name
...
additional arguments
The wbWorkbook
object
get_base_colors()
Get the base color
wbWorkbook$get_base_colors(xml = FALSE, plot = TRUE)
xml
xml
plot
plot
get_base_colours()
Get the base colour
wbWorkbook$get_base_colours(xml = FALSE, plot = TRUE)
xml
xml
plot
plot
set_base_colors()
Set the base color
wbWorkbook$set_base_colors(theme = "Office", ...)
theme
theme
...
...
The wbWorkbook
object
set_base_colours()
Set the base colour
wbWorkbook$set_base_colours(theme = "Office", ...)
theme
theme
...
...
The wbWorkbook
object
set_bookview()
Set the book views
wbWorkbook$set_bookview( active_tab = NULL, auto_filter_date_grouping = NULL, first_sheet = NULL, minimized = NULL, show_horizontal_scroll = NULL, show_sheet_tabs = NULL, show_vertical_scroll = NULL, tab_ratio = NULL, visibility = NULL, window_height = NULL, window_width = NULL, x_window = NULL, y_window = NULL, ... )
active_tab
activeTab
auto_filter_date_grouping
autoFilterDateGrouping
first_sheet
firstSheet
minimized
minimized
show_horizontal_scroll
showHorizontalScroll
show_sheet_tabs
showSheetTabs
show_vertical_scroll
showVerticalScroll
tab_ratio
tabRatio
visibility
visibility
window_height
windowHeight
window_width
windowWidth
x_window
xWindow
y_window
yWindow
...
additional arguments
The wbWorkbook
object
get_sheet_names()
Get sheet names
wbWorkbook$get_sheet_names(escape = FALSE)
escape
Logical if the xml special characters are escaped
A named
character
vector of sheet names in their order. The
names represent the original value of the worksheet prior to any
character substitutions.
set_sheet_names()
Sets a sheet name
wbWorkbook$set_sheet_names(old = NULL, new)
old
Old sheet name
new
New sheet name
The wbWorkbook
object, invisibly
set_row_heights()
Sets a row height for a sheet
wbWorkbook$set_row_heights( sheet = current_sheet(), rows, heights = NULL, hidden = FALSE )
sheet
The name of the sheet
rows
rows
heights
heights
hidden
hidden
The wbWorkbook
object, invisibly
remove_row_heights()
Removes a row height for a sheet
wbWorkbook$remove_row_heights(sheet = current_sheet(), rows)
sheet
The name of the sheet
rows
rows
The wbWorkbook
object, invisibly
createCols()
creates column object for worksheet
wbWorkbook$createCols(sheet = current_sheet(), n, beg, end)
sheet
The name of the sheet
n
n
beg
beg
end
end
group_cols()
Group cols
wbWorkbook$group_cols( sheet = current_sheet(), cols, collapsed = FALSE, levels = NULL )
sheet
The name of the sheet
cols
cols
collapsed
collapsed
levels
levels
The wbWorkbook
object, invisibly
ungroup_cols()
ungroup cols
wbWorkbook$ungroup_cols(sheet = current_sheet(), cols)
sheet
The name of the sheet
cols
columns
The wbWorkbook
object
remove_col_widths()
Remove row heights from a worksheet
wbWorkbook$remove_col_widths(sheet = current_sheet(), cols)
sheet
A name or index of a worksheet
cols
Indices of columns to remove custom width (if any) from.
The wbWorkbook
object, invisibly
set_col_widths()
Set column widths
wbWorkbook$set_col_widths( sheet = current_sheet(), cols, widths = 8.43, hidden = FALSE )
sheet
The name of the sheet
cols
cols
widths
Width of columns
hidden
A logical vector to determine which cols are hidden; values
are repeated across length of cols
The wbWorkbook
object, invisibly
group_rows()
Group rows
wbWorkbook$group_rows( sheet = current_sheet(), rows, collapsed = FALSE, levels = NULL )
sheet
The name of the sheet
rows
rows
collapsed
collapsed
levels
levels
The wbWorkbook
object, invisibly
ungroup_rows()
ungroup rows
wbWorkbook$ungroup_rows(sheet = current_sheet(), rows)
sheet
The name of the sheet
rows
rows
The wbWorkbook
object
remove_worksheet()
Remove a worksheet
wbWorkbook$remove_worksheet(sheet = current_sheet())
sheet
The worksheet to delete
The wbWorkbook
object, invisibly
add_data_validation()
Adds data validation
wbWorkbook$add_data_validation( sheet = current_sheet(), dims = "A1", type, operator, value, allow_blank = TRUE, show_input_msg = TRUE, show_error_msg = TRUE, error_style = NULL, error_title = NULL, error = NULL, prompt_title = NULL, prompt = NULL, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
type
type
operator
operator
value
value
allow_blank
allowBlank
show_input_msg
showInputMsg
show_error_msg
showErrorMsg
error_style
The icon shown and the options how to deal with such inputs. Default "stop" (cancel), else "information" (prompt popup) or "warning" (prompt accept or change input)
error_title
The error title
error
The error text
prompt_title
The prompt title
prompt
The prompt text
...
additional arguments
The wbWorkbook
object
merge_cells()
Set cell merging for a sheet
wbWorkbook$merge_cells( sheet = current_sheet(), dims = NULL, solve = FALSE, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
solve
logical if intersecting cells should be solved
...
additional arguments
The wbWorkbook
object, invisibly
unmerge_cells()
Removes cell merging for a sheet
wbWorkbook$unmerge_cells(sheet = current_sheet(), dims = NULL, ...)
sheet
The name of the sheet
dims
Cell range in a sheet
...
additional arguments
The wbWorkbook
object, invisibly
freeze_pane()
Set freeze panes for a sheet
wbWorkbook$freeze_pane( sheet = current_sheet(), first_active_row = NULL, first_active_col = NULL, first_row = FALSE, first_col = FALSE, ... )
sheet
The name of the sheet
first_active_row
first_active_row
first_active_col
first_active_col
first_row
first_row
first_col
first_col
...
additional arguments
The wbWorkbook
object, invisibly
add_comment()
Add comment
wbWorkbook$add_comment(sheet = current_sheet(), dims = "A1", comment, ...)
sheet
The name of the sheet
dims
row and column as spreadsheet dimension, e.g. "A1"
comment
a comment to apply to the worksheet
...
additional arguments
The wbWorkbook
object
get_comment()
Get comments
wbWorkbook$get_comment(sheet = current_sheet(), dims = NULL)
sheet
sheet
dims
dims
A data frame containing comments
remove_comment()
Remove comment
wbWorkbook$remove_comment(sheet = current_sheet(), dims = "A1", ...)
sheet
The name of the sheet
dims
row and column as spreadsheet dimension, e.g. "A1"
...
additional arguments
The wbWorkbook
object
add_thread()
add threaded comment to worksheet
wbWorkbook$add_thread( sheet = current_sheet(), dims = "A1", comment = NULL, person_id, reply = FALSE, resolve = FALSE )
sheet
The name of the sheet
dims
Cell range in a sheet
comment
the comment to add
person_id
the person Id this should be added for
reply
logical if the comment is a reply
resolve
logical if the comment should be marked as resolved
get_thread()
Get threads
wbWorkbook$get_thread(sheet = current_sheet(), dims = NULL)
sheet
sheet
dims
dims
A data frame containing threads
add_conditional_formatting()
Add conditional formatting
wbWorkbook$add_conditional_formatting( sheet = current_sheet(), dims = NULL, rule = NULL, style = NULL, type = c("expression", "colorScale", "dataBar", "iconSet", "duplicatedValues", "uniqueValues", "containsErrors", "notContainsErrors", "containsBlanks", "notContainsBlanks", "containsText", "notContainsText", "beginsWith", "endsWith", "between", "topN", "bottomN"), params = list(showValue = TRUE, gradient = TRUE, border = TRUE, percent = FALSE, rank = 5L), ... )
sheet
The name of the sheet
dims
Cell range in a sheet
rule
rule
style
style
type
type
params
Additional parameters
...
additional arguments
The wbWorkbook
object
remove_conditional_formatting()
Remove conditional formatting
wbWorkbook$remove_conditional_formatting( sheet = current_sheet(), dims = NULL, first = FALSE, last = FALSE )
sheet
sheet
dims
dims
first
first
last
last
The wbWorkbook
object
add_image()
Insert an image into a sheet
wbWorkbook$add_image( sheet = current_sheet(), dims = "A1", file, width = 6, height = 3, row_offset = 0, col_offset = 0, units = "in", dpi = 300, address = NULL, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
file
file
width
width
height
height
row_offset, col_offset
offsets
units
units
dpi
dpi
address
address
...
additional arguments
The wbWorkbook
object, invisibly
add_plot()
Add plot. A wrapper for add_image()
wbWorkbook$add_plot( sheet = current_sheet(), dims = "A1", width = 6, height = 4, row_offset = 0, col_offset = 0, file_type = "png", units = "in", dpi = 300, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
width
width
height
height
row_offset, col_offset
offsets
file_type
fileType
units
units
dpi
dpi
...
additional arguments
The wbWorkbook
object
add_drawing()
Add xml drawing
wbWorkbook$add_drawing( sheet = current_sheet(), dims = "A1", xml, col_offset = 0, row_offset = 0, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
xml
xml
col_offset, row_offset
offsets for column and row
...
additional arguments
The wbWorkbook
object
add_chart_xml()
Add xml chart
wbWorkbook$add_chart_xml( sheet = current_sheet(), dims = NULL, xml, col_offset = 0, row_offset = 0, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
xml
xml
col_offset, row_offset
positioning parameters
...
additional arguments
The wbWorkbook
object
add_mschart()
Add mschart chart to the workbook
wbWorkbook$add_mschart( sheet = current_sheet(), dims = NULL, graph, col_offset = 0, row_offset = 0, ... )
sheet
The name of the sheet
dims
the dimensions where the sheet will appear
graph
mschart graph
col_offset, row_offset
offsets for column and row
...
additional arguments
The wbWorkbook
object
add_form_control()
Add form control to workbook
wbWorkbook$add_form_control( sheet = current_sheet(), dims = "A1", type = c("Checkbox", "Radio", "Drop"), text = NULL, link = NULL, range = NULL, checked = FALSE )
sheet
The name of the sheet
dims
Cell range in a sheet
type
type
text
text
link
link
range
range
checked
checked
The wbWorkbook
object, invisibly
print()
Prints the wbWorkbook
object
wbWorkbook$print()
The wbWorkbook
object, invisibly; called for its side-effects
protect()
Protect a workbook
wbWorkbook$protect( protect = TRUE, password = NULL, lock_structure = FALSE, lock_windows = FALSE, type = 1, file_sharing = FALSE, username = unname(Sys.info()["user"]), read_only_recommended = FALSE, ... )
protect
protect
password
password
lock_structure
lock_structure
lock_windows
lock_windows
type
type
file_sharing
file_sharing
username
username
read_only_recommended
read_only_recommended
...
additional arguments
The wbWorkbook
object, invisibly
protect_worksheet()
protect worksheet
wbWorkbook$protect_worksheet( sheet = current_sheet(), protect = TRUE, password = NULL, properties = NULL )
sheet
The name of the sheet
protect
protect
password
password
properties
A character vector of properties to lock. Can be one
or more of the following: "selectLockedCells"
,
"selectUnlockedCells"
, "formatCells"
, "formatColumns"
,
"formatRows"
, "insertColumns"
, "insertRows"
,
"insertHyperlinks"
, "deleteColumns"
, "deleteRows"
, "sort"
,
"autoFilter"
, "pivotTables"
, "objects"
, "scenarios"
The wbWorkbook
object
get_properties()
Get properties of a workbook
wbWorkbook$get_properties()
set_properties()
Set a property of a workbook
wbWorkbook$set_properties( creator = NULL, title = NULL, subject = NULL, category = NULL, datetime_created = NULL, datetime_modified = NULL, modifier = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, custom = NULL )
creator
character vector of creators. Duplicated are ignored.
title, subject, category, datetime_created, datetime_modified, modifier, keywords, comments, manager, company, custom
A workbook property to set
add_mips()
add mips string
wbWorkbook$add_mips(xml = NULL)
xml
A mips string added to self$custom
get_mips()
get mips string
wbWorkbook$get_mips(single_xml = TRUE, quiet = TRUE)
single_xml
single_xml
quiet
quiet
set_creators()
Set creator(s)
wbWorkbook$set_creators(creators)
creators
A character vector of creators to set. Duplicates are ignored.
add_creators()
Add creator(s)
wbWorkbook$add_creators(creators)
creators
A character vector of creators to add. Duplicates are ignored.
remove_creators()
Remove creator(s)
wbWorkbook$remove_creators(creators)
creators
A character vector of creators to remove. All duplicated are removed.
set_last_modified_by()
Change the last modified by
wbWorkbook$set_last_modified_by(name, ...)
name
A new value
...
additional arguments
The wbWorkbook
object, invisibly
set_page_setup()
set_page_setup() this function is intended to supersede page_setup(), but is not yet stable
wbWorkbook$set_page_setup( sheet = current_sheet(), black_and_white = NULL, cell_comments = NULL, copies = NULL, draft = NULL, errors = NULL, first_page_number = NULL, id = NULL, page_order = NULL, paper_height = NULL, paper_width = NULL, hdpi = NULL, vdpi = NULL, use_first_page_number = NULL, use_printer_defaults = NULL, orientation = NULL, scale = NULL, left = 0.7, right = 0.7, top = 0.75, bottom = 0.75, header = 0.3, footer = 0.3, fit_to_width = FALSE, fit_to_height = FALSE, paper_size = NULL, print_title_rows = NULL, print_title_cols = NULL, summary_row = NULL, summary_col = NULL, tab_color = NULL, ... )
sheet
The name of the sheet
black_and_white
black_and_white
cell_comments
cell_comment
copies
copies
draft
draft
errors
errors
first_page_number
first_page_number
id
id
page_order
page_order
paper_height, paper_width
paper size
hdpi, vdpi
horizontal and vertical dpi
use_first_page_number
use_first_page_number
use_printer_defaults
use_printer_defaults
orientation
orientation
scale
scale
left
left
right
right
top
top
bottom
bottom
header
header
footer
footer
fit_to_width
fitToWidth
fit_to_height
fitToHeight
paper_size
paperSize
print_title_rows
printTitleRows
print_title_cols
printTitleCols
summary_row
summaryRow
summary_col
summaryCol
tab_color
tabColor
...
additional arguments
The wbWorkbook
object, invisibly
page_setup()
page_setup()
wbWorkbook$page_setup( sheet = current_sheet(), orientation = NULL, scale = 100, left = 0.7, right = 0.7, top = 0.75, bottom = 0.75, header = 0.3, footer = 0.3, fit_to_width = FALSE, fit_to_height = FALSE, paper_size = NULL, print_title_rows = NULL, print_title_cols = NULL, summary_row = NULL, summary_col = NULL, ... )
sheet
The name of the sheet
orientation
orientation
scale
scale
left
left
right
right
top
top
bottom
bottom
header
header
footer
footer
fit_to_width
fitToWidth
fit_to_height
fitToHeight
paper_size
paperSize
print_title_rows
printTitleRows
print_title_cols
printTitleCols
summary_row
summaryRow
summary_col
summaryCol
...
additional arguments
The wbWorkbook
object, invisibly
set_header_footer()
Sets headers and footers
wbWorkbook$set_header_footer( sheet = current_sheet(), header = NULL, footer = NULL, even_header = NULL, even_footer = NULL, first_header = NULL, first_footer = NULL, align_with_margins = NULL, scale_with_doc = NULL, ... )
sheet
The name of the sheet
header
header
footer
footer
even_header
evenHeader
even_footer
evenFooter
first_header
firstHeader
first_footer
firstFooter
align_with_margins
align_with_margins
scale_with_doc
scale_with_doc
...
additional arguments
The wbWorkbook
object, invisibly
get_tables()
get tables
wbWorkbook$get_tables(sheet = current_sheet())
sheet
The name of the sheet
The sheet tables. character()
if empty
remove_tables()
remove tables
wbWorkbook$remove_tables(sheet = current_sheet(), table, remove_data = TRUE)
sheet
The name of the sheet
table
table
remove_data
removes the data as well
The wbWorkbook
object
add_filter()
add filters
wbWorkbook$add_filter(sheet = current_sheet(), rows, cols)
sheet
The name of the sheet
rows
rows
cols
cols
The wbWorkbook
object
remove_filter()
remove filters
wbWorkbook$remove_filter(sheet = current_sheet())
sheet
The name of the sheet
The wbWorkbook
object
set_grid_lines()
grid lines
wbWorkbook$set_grid_lines(sheet = current_sheet(), show = FALSE, print = show)
sheet
The name of the sheet
show
show
print
The wbWorkbook
object
grid_lines()
grid lines
wbWorkbook$grid_lines(sheet = current_sheet(), show = FALSE, print = show)
sheet
The name of the sheet
show
show
print
The wbWorkbook
object
add_named_region()
add a named region
wbWorkbook$add_named_region( sheet = current_sheet(), dims = "A1", name, local_sheet = FALSE, overwrite = FALSE, comment = NULL, hidden = NULL, custom_menu = NULL, description = NULL, is_function = NULL, function_group_id = NULL, help = NULL, local_name = NULL, publish_to_server = NULL, status_bar = NULL, vb_procedure = NULL, workbook_parameter = NULL, xml = NULL, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
name
name
local_sheet
local_sheet
overwrite
overwrite
comment
comment
hidden
hidden
custom_menu
custom_menu
description
description
is_function
function
function_group_id
function group id
help
help
local_name
localName
publish_to_server
publish to server
status_bar
status bar
vb_procedure
vb procedure
workbook_parameter
workbookParameter
xml
xml
...
additional arguments
The wbWorkbook
object
get_named_regions()
get named regions in a workbook
wbWorkbook$get_named_regions(tables = FALSE, x = NULL)
tables
Return tables as well?
x
Not used.
A data.frame
of named regions
remove_named_region()
remove a named region
wbWorkbook$remove_named_region(sheet = current_sheet(), name = NULL)
sheet
The name of the sheet
name
name
The wbWorkbook
object
set_order()
set worksheet order
wbWorkbook$set_order(sheets)
sheets
sheets
The wbWorkbook
object
get_sheet_visibility()
Get sheet visibility
wbWorkbook$get_sheet_visibility()
Returns sheet visibility
set_sheet_visibility()
Set sheet visibility
wbWorkbook$set_sheet_visibility(sheet = current_sheet(), value)
sheet
The name of the sheet
value
value
The wbWorkbook
object
add_page_break()
Add a page break
wbWorkbook$add_page_break(sheet = current_sheet(), row = NULL, col = NULL)
sheet
The name of the sheet
row
row
col
col
The wbWorkbook
object
clean_sheet()
clean sheet (remove all values)
wbWorkbook$clean_sheet( sheet = current_sheet(), dims = NULL, numbers = TRUE, characters = TRUE, styles = TRUE, merged_cells = TRUE, hyperlinks = TRUE )
sheet
The name of the sheet
dims
Cell range in a sheet
numbers
remove all numbers
characters
remove all characters
styles
remove all styles
merged_cells
remove all merged_cells
hyperlinks
remove all hyperlinks
The wbWorksheetObject
, invisibly
add_border()
create borders for cell region
wbWorkbook$add_border( sheet = current_sheet(), dims = "A1", bottom_color = wb_color(hex = "FF000000"), left_color = wb_color(hex = "FF000000"), right_color = wb_color(hex = "FF000000"), top_color = wb_color(hex = "FF000000"), bottom_border = "thin", left_border = "thin", right_border = "thin", top_border = "thin", inner_hgrid = NULL, inner_hcolor = NULL, inner_vgrid = NULL, inner_vcolor = NULL, ... )
sheet
The name of the sheet
dims
dimensions on the worksheet e.g. "A1", "A1:A5", "A1:H5"
bottom_color, left_color, right_color, top_color, inner_hcolor, inner_vcolor
a color, either something openxml knows or some RGB color
left_border, right_border, top_border, bottom_border, inner_hgrid, inner_vgrid
the border style, if NULL no border is drawn. See create_border for possible border styles
...
additional arguments
The wbWorkbook
, invisibly
add_fill()
provide simple fill function
wbWorkbook$add_fill( sheet = current_sheet(), dims = "A1", color = wb_color(hex = "FFFFFF00"), pattern = "solid", gradient_fill = "", every_nth_col = 1, every_nth_row = 1, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
color
the colors to apply, e.g. yellow: wb_color(hex = "FFFFFF00")
pattern
various default "none" but others are possible: "solid", "mediumGray", "darkGray", "lightGray", "darkHorizontal", "darkVertical", "darkDown", "darkUp", "darkGrid", "darkTrellis", "lightHorizontal", "lightVertical", "lightDown", "lightUp", "lightGrid", "lightTrellis", "gray125", "gray0625"
gradient_fill
a gradient fill xml pattern.
every_nth_col
which col should be filled
every_nth_row
which row should be filled
...
additional arguments
The wbWorksheetObject
, invisibly
add_font()
provide simple font function
wbWorkbook$add_font( sheet = current_sheet(), dims = "A1", name = "Aptos Narrow", color = wb_color(hex = "FF000000"), size = "11", bold = "", italic = "", outline = "", strike = "", underline = "", charset = "", condense = "", extend = "", family = "", scheme = "", shadow = "", vert_align = "", ... )
sheet
The name of the sheet
dims
Cell range in a sheet
name
font name: default "Aptos Narrow"
color
rgb color: default "FF000000"
size
font size: default "11",
bold
bold
italic
italic
outline
outline
strike
strike
underline
underline
charset
charset
condense
condense
extend
extend
family
font family
scheme
font scheme
shadow
shadow
vert_align
vertical alignment
...
additional arguments
The wbWorkbook
, invisibly
add_numfmt()
provide simple number format function
wbWorkbook$add_numfmt(sheet = current_sheet(), dims = "A1", numfmt)
sheet
The name of the sheet
dims
Cell range in a sheet
numfmt
number format id or a character of the format
The wbWorksheetObject
, invisibly
add_cell_style()
provide simple cell style format function
wbWorkbook$add_cell_style( sheet = current_sheet(), dims = "A1", apply_alignment = NULL, apply_border = NULL, apply_fill = NULL, apply_font = NULL, apply_number_format = NULL, apply_protection = NULL, border_id = NULL, ext_lst = NULL, fill_id = NULL, font_id = NULL, hidden = NULL, horizontal = NULL, indent = NULL, justify_last_line = NULL, locked = NULL, num_fmt_id = NULL, pivot_button = NULL, quote_prefix = NULL, reading_order = NULL, relative_indent = NULL, shrink_to_fit = NULL, text_rotation = NULL, vertical = NULL, wrap_text = NULL, xf_id = NULL, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
apply_alignment
logical apply alignment
apply_border
logical apply border
apply_fill
logical apply fill
apply_font
logical apply font
apply_number_format
logical apply number format
apply_protection
logical apply protection
border_id
border ID to apply
ext_lst
extension list something like <extLst>...</extLst>
fill_id
fill ID to apply
font_id
font ID to apply
hidden
logical cell is hidden
horizontal
align content horizontal ('left', 'center', 'right')
indent
logical indent content
justify_last_line
logical justify last line
locked
logical cell is locked
num_fmt_id
number format ID to apply
pivot_button
unknown
quote_prefix
unknown
reading_order
reading order left to right
relative_indent
relative indentation
shrink_to_fit
logical shrink to fit
text_rotation
degrees of text rotation
vertical
vertical alignment of content ('top', 'center', 'bottom')
wrap_text
wrap text in cell
xf_id
xf ID to apply
...
additional arguments
The wbWorkbook
object, invisibly
get_cell_style()
get sheet style
wbWorkbook$get_cell_style(sheet = current_sheet(), dims)
sheet
The name of the sheet
dims
Cell range in a sheet
a character vector of cell styles
set_cell_style()
set sheet style
wbWorkbook$set_cell_style(sheet = current_sheet(), dims, style)
sheet
The name of the sheet
dims
Cell range in a sheet
style
style
The wbWorksheetObject
, invisibly
set_cell_style_across()
set style across columns and/or rows
wbWorkbook$set_cell_style_across( sheet = current_sheet(), style, cols = NULL, rows = NULL )
sheet
sheet
style
style
cols
cols
rows
rows
The wbWorkbook
object
add_named_style()
set sheet style
wbWorkbook$add_named_style( sheet = current_sheet(), dims = "A1", name = "Normal", font_name = NULL, font_size = NULL )
sheet
The name of the sheet
dims
Cell range in a sheet
name
name
font_name, font_size
optional else the default of the theme
The wbWorkbook
, invisibly
add_dxfs_style()
create dxfs style These styles are used with conditional formatting and custom table styles
wbWorkbook$add_dxfs_style( name, font_name = NULL, font_size = NULL, font_color = NULL, num_fmt = NULL, border = NULL, border_color = wb_color(getOption("openxlsx2.borderColor", "black")), border_style = getOption("openxlsx2.borderStyle", "thin"), bg_fill = NULL, gradient_fill = NULL, text_bold = NULL, text_italic = NULL, text_underline = NULL, ... )
name
the style name
font_name
the font name
font_size
the font size
font_color
the font color (a wb_color()
object)
num_fmt
the number format
border
logical if borders are applied
border_color
the border color
border_style
the border style
bg_fill
any background fill
gradient_fill
any gradient fill
text_bold
logical if text is bold
text_italic
logical if text is italic
text_underline
logical if text is underlined
...
additional arguments passed to create_dxfs_style()
The wbWorksheetObject
, invisibly
clone_sheet_style()
clone style from one sheet to another
wbWorkbook$clone_sheet_style(from = current_sheet(), to)
from
the worksheet you are cloning
to
the worksheet the style is applied to
add_sparklines()
apply sparkline to worksheet
wbWorkbook$add_sparklines(sheet = current_sheet(), sparklines)
sheet
The name of the sheet
sparklines
sparkline created by create_sparkline()
add_ignore_error()
Ignore error on worksheet
wbWorkbook$add_ignore_error( sheet = current_sheet(), dims = "A1", calculated_column = FALSE, empty_cell_reference = FALSE, eval_error = FALSE, formula = FALSE, formula_range = FALSE, list_data_validation = FALSE, number_stored_as_text = FALSE, two_digit_text_year = FALSE, unlocked_formula = FALSE, ... )
sheet
The name of the sheet
dims
Cell range in a sheet
calculated_column
calculatedColumn
empty_cell_reference
emptyCellReference
eval_error
evalError
formula
formula
formula_range
formulaRange
list_data_validation
listDataValidation
number_stored_as_text
numberStoredAsText
two_digit_text_year
twoDigitTextYear
unlocked_formula
unlockedFormula
...
additional arguments
set_sheetview()
add sheetview
wbWorkbook$set_sheetview( sheet = current_sheet(), color_id = NULL, default_grid_color = NULL, right_to_left = NULL, show_formulas = NULL, show_grid_lines = NULL, show_outline_symbols = NULL, show_row_col_headers = NULL, show_ruler = NULL, show_white_space = NULL, show_zeros = NULL, tab_selected = NULL, top_left_cell = NULL, view = NULL, window_protection = NULL, workbook_view_id = NULL, zoom_scale = NULL, zoom_scale_normal = NULL, zoom_scale_page_layout_view = NULL, zoom_scale_sheet_layout_view = NULL, ... )
sheet
The name of the sheet
color_id, default_grid_color
Integer: A color, default is 64
right_to_left
Logical: if TRUE column ordering is right to left
show_formulas
Logical: if TRUE cell formulas are shown
show_grid_lines
Logical: if TRUE the worksheet grid is shown
show_outline_symbols
Logical: if TRUE outline symbols are shown
show_row_col_headers
Logical: if TRUE row and column headers are shown
show_ruler
Logical: if TRUE a ruler is shown in page layout view
show_white_space
Logical: if TRUE margins are shown in page layout view
show_zeros
Logical: if FALSE cells containing zero are shown blank if !showFormulas
tab_selected
Integer: zero vector indicating the selected tab
top_left_cell
Cell: the cell shown in the top left corner / or top right with rightToLeft
view
View: "normal", "pageBreakPreview" or "pageLayout"
window_protection
Logical: if TRUE the panes are protected
workbook_view_id
integer: Pointing to some other view inside the workbook
zoom_scale, zoom_scale_normal, zoom_scale_page_layout_view, zoom_scale_sheet_layout_view
Integer: the zoom scale should be between 10 and 400. These are values for current, normal etc.
...
additional arguments
The wbWorksheetObject
, invisibly
add_person()
add person to workbook
wbWorkbook$add_person( name = NULL, id = NULL, user_id = NULL, provider_id = "None" )
name
name
id
id
user_id
user_id
provider_id
provider_id
get_person()
description get person
wbWorkbook$get_person(name = NULL)
name
name
get_active_sheet()
description get active sheet
wbWorkbook$get_active_sheet()
set_active_sheet()
description set active sheet
wbWorkbook$set_active_sheet(sheet = current_sheet())
sheet
The name of the sheet
get_selected()
description get selected sheets
wbWorkbook$get_selected()
set_selected()
set selected sheet
wbWorkbook$set_selected(sheet = current_sheet())
sheet
The name of the sheet
clone()
The objects of this class are cloneable with this method.
wbWorkbook$clone(deep = FALSE)
deep
Whether to make a deep clone.
Write a data frame or list of data frames to an xlsx file.
write_xlsx(x, file, as_table = FALSE, ...)
write_xlsx(x, file, as_table = FALSE, ...)
x |
An object or a list of objects that can be handled by |
file |
An optional xlsx file name. If no file is passed, the object is not written to disk and only a workbook object is returned. |
as_table |
If |
... |
Arguments passed on to
|
columns of x
with class Date
or POSIXt
are automatically
styled as dates and datetimes respectively.
A workbook object
## write to working directory write_xlsx(iris, file = temp_xlsx(), col_names = TRUE) write_xlsx(iris, file = temp_xlsx(), col_names = TRUE ) ## Lists elements are written to individual worksheets, using list names as sheet names if available l <- list("IRIS" = iris, "MTCARS" = mtcars, matrix(runif(1000), ncol = 5)) write_xlsx(l, temp_xlsx(), col_widths = c(NA, "auto", "auto")) ## different sheets can be given different parameters write_xlsx(l, temp_xlsx(), start_col = c(1, 2, 3), start_row = 2, as_table = c(TRUE, TRUE, FALSE), with_filter = c(TRUE, FALSE, FALSE) ) # specify column widths for multiple sheets write_xlsx(l, temp_xlsx(), col_widths = 20) write_xlsx(l, temp_xlsx(), col_widths = list(100, 200, 300)) write_xlsx(l, temp_xlsx(), col_widths = list(rep(10, 5), rep(8, 11), rep(5, 5)))
## write to working directory write_xlsx(iris, file = temp_xlsx(), col_names = TRUE) write_xlsx(iris, file = temp_xlsx(), col_names = TRUE ) ## Lists elements are written to individual worksheets, using list names as sheet names if available l <- list("IRIS" = iris, "MTCARS" = mtcars, matrix(runif(1000), ncol = 5)) write_xlsx(l, temp_xlsx(), col_widths = c(NA, "auto", "auto")) ## different sheets can be given different parameters write_xlsx(l, temp_xlsx(), start_col = c(1, 2, 3), start_row = 2, as_table = c(TRUE, TRUE, FALSE), with_filter = c(TRUE, FALSE, FALSE) ) # specify column widths for multiple sheets write_xlsx(l, temp_xlsx(), col_widths = 20) write_xlsx(l, temp_xlsx(), col_widths = list(100, 200, 300)) write_xlsx(l, temp_xlsx(), col_widths = list(rep(10, 5), rep(8, 11), rep(5, 5)))
wbWorkbook
objectThis function tries to open a Microsoft Excel (xls/xlsx) file or, an wbWorkbook with the proper application, in a portable manner.
On Windows it uses base::shell.exec()
(Windows only function) to
determine the appropriate program.
On Mac, (c) it uses system default handlers, given the file type.
On Linux, it searches (via which
) for available xls/xlsx reader
applications (unless options('openxlsx2.excelApp')
is set to the app bin
path), and if it finds anything, sets options('openxlsx2.excelApp')
to the
program chosen by the user via a menu (if many are present, otherwise it
will set the only available). Currently searched for apps are
Libreoffice/Openoffice (soffice
bin), Gnumeric (gnumeric
) and Calligra
Sheets (calligrasheets
).
xl_open(x, interactive = NA) ## S3 method for class 'wbWorkbook' xl_open(x, interactive = NA) ## Default S3 method: xl_open(x, interactive = NA)
xl_open(x, interactive = NA) ## S3 method for class 'wbWorkbook' xl_open(x, interactive = NA) ## Default S3 method: xl_open(x, interactive = NA)
x |
A path to the Excel (xls/xlsx) file or wbWorkbook object. |
interactive |
If |
if (interactive()) { xlsx_file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") xl_open(xlsx_file) # (not yet saved) Workbook example wb <- wb_workbook() x <- mtcars[1:6, ] wb$add_worksheet("Cars") wb$add_data("Cars", x, start_col = 2, start_row = 3, row_names = TRUE) xl_open(wb) }
if (interactive()) { xlsx_file <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2") xl_open(xlsx_file) # (not yet saved) Workbook example wb <- wb_workbook() x <- mtcars[1:6, ] wb$add_worksheet("Cars") wb$add_data("Cars", x, start_col = 2, start_row = 3, row_names = TRUE) xl_open(wb) }
append xml child to node
xml_add_child(xml_node, xml_child, level, pointer = FALSE, ...)
xml_add_child(xml_node, xml_child, level, pointer = FALSE, ...)
xml_node |
xml_node |
xml_child |
xml_child |
level |
optional level, if missing the first child is picked |
pointer |
pointer |
... |
additional arguments passed to |
xml_node <- "<a><b/></a>" xml_child <- "<c/>" # add child to first level node xml_add_child(xml_node, xml_child) # add child to second level node as request xml_node <- xml_add_child(xml_node, xml_child, level = c("b")) # add child to third level node as request xml_node <- xml_add_child(xml_node, "<d/>", level = c("b", "c"))
xml_node <- "<a><b/></a>" xml_child <- "<c/>" # add child to first level node xml_add_child(xml_node, xml_child) # add child to second level node as request xml_node <- xml_add_child(xml_node, xml_child, level = c("b")) # add child to third level node as request xml_node <- xml_add_child(xml_node, "<d/>", level = c("b", "c"))
Needs xml node and named character vector as input. Modifies the arguments of each first child found in the xml node and adds or updates the attribute vector.
xml_attr_mod( xml_content, xml_attributes, escapes = FALSE, declaration = FALSE, remove_empty_attr = TRUE )
xml_attr_mod( xml_content, xml_attributes, escapes = FALSE, declaration = FALSE, remove_empty_attr = TRUE )
xml_content |
some valid xml_node |
xml_attributes |
R vector of named attributes |
escapes |
bool if escapes should be used |
declaration |
bool if declaration should be imported |
remove_empty_attr |
bool remove empty attributes or ignore them |
If a named attribute in xml_attributes
is "" remove the attribute
from the node.
If xml_attributes
contains a named entry found in the xml node, it is
updated else it is added as attribute.
# add single node xml_node <- "<a foo=\"bar\">openxlsx2</a><b />" xml_attr <- c(qux = "quux") # "<a foo=\"bar\" qux=\"quux\">openxlsx2</a><b qux=\"quux\"/>" xml_attr_mod(xml_node, xml_attr) # update node and add node xml_node <- "<a foo=\"bar\">openxlsx2</a><b />" xml_attr <- c(foo = "baz", qux = "quux") # "<a foo=\"baz\" qux=\"quux\">openxlsx2</a><b foo=\"baz\" qux=\"quux\"/>" xml_attr_mod(xml_node, xml_attr) # remove node and add node xml_node <- "<a foo=\"bar\">openxlsx2</a><b />" xml_attr <- c(foo = "", qux = "quux") # "<a qux=\"quux\">openxlsx2</a><b qux=\"quux\"/>" xml_attr_mod(xml_node, xml_attr)
# add single node xml_node <- "<a foo=\"bar\">openxlsx2</a><b />" xml_attr <- c(qux = "quux") # "<a foo=\"bar\" qux=\"quux\">openxlsx2</a><b qux=\"quux\"/>" xml_attr_mod(xml_node, xml_attr) # update node and add node xml_node <- "<a foo=\"bar\">openxlsx2</a><b />" xml_attr <- c(foo = "baz", qux = "quux") # "<a foo=\"baz\" qux=\"quux\">openxlsx2</a><b foo=\"baz\" qux=\"quux\"/>" xml_attr_mod(xml_node, xml_attr) # remove node and add node xml_node <- "<a foo=\"bar\">openxlsx2</a><b />" xml_attr <- c(foo = "", qux = "quux") # "<a qux=\"quux\">openxlsx2</a><b qux=\"quux\"/>" xml_attr_mod(xml_node, xml_attr)
takes xml_name, xml_children and xml_attributes to create a new xml_node.
xml_node_create( xml_name, xml_children = NULL, xml_attributes = NULL, escapes = FALSE, declaration = FALSE )
xml_node_create( xml_name, xml_children = NULL, xml_attributes = NULL, escapes = FALSE, declaration = FALSE )
xml_name |
the name of the new xml_node |
xml_children |
character vector children attached to the xml_node |
xml_attributes |
named character vector of attributes for the xml_node |
escapes |
bool if escapes should be used |
declaration |
bool if declaration should be imported |
if xml_children or xml_attributes should be empty, use NULL
xml_name <- "a" # "<a/>" xml_node_create(xml_name) xml_child <- "openxlsx" # "<a>openxlsx</a>" xml_node_create(xml_name, xml_children = xml_child) xml_attr <- c(foo = "baz", qux = "quux") # "<a foo=\"baz\" qux=\"quux\"/>" xml_node_create(xml_name, xml_attributes = xml_attr) # "<a foo=\"baz\" qux=\"quux\">openxlsx</a>" xml_node_create(xml_name, xml_children = xml_child, xml_attributes = xml_attr)
xml_name <- "a" # "<a/>" xml_node_create(xml_name) xml_child <- "openxlsx" # "<a>openxlsx</a>" xml_node_create(xml_name, xml_children = xml_child) xml_attr <- c(foo = "baz", qux = "quux") # "<a foo=\"baz\" qux=\"quux\"/>" xml_node_create(xml_name, xml_attributes = xml_attr) # "<a foo=\"baz\" qux=\"quux\">openxlsx</a>" xml_node_create(xml_name, xml_children = xml_child, xml_attributes = xml_attr)
remove xml child to node
xml_rm_child(xml_node, xml_child, level, which = 0, pointer = FALSE, ...)
xml_rm_child(xml_node, xml_child, level, which = 0, pointer = FALSE, ...)
xml_node |
xml_node |
xml_child |
xml_child |
level |
optional level, if missing the first child is picked |
which |
optional index which node to remove, if multiple are available. Default disabled all will be removed |
pointer |
pointer |
... |
additional arguments passed to |
xml_node <- "<a><b><c><d/></c></b><c/></a>" xml_child <- "c" xml_rm_child(xml_node, xml_child) xml_rm_child(xml_node, xml_child, level = c("b")) xml_rm_child(xml_node, "d", level = c("b", "c"))
xml_node <- "<a><b><c><d/></c></b><c/></a>" xml_child <- "c" xml_rm_child(xml_node, xml_child) xml_rm_child(xml_node, xml_child, level = c("b")) xml_rm_child(xml_node, "d", level = c("b", "c"))