Type: | Package |
Title: | Read, Write and Edit 'xlsx' Files |
Version: | 1.17 |
Language: | en-US |
Description: | Simplifies the creation of 'xlsx' files by providing a high level interface to writing, styling and editing worksheets. |
License: | MIT + file LICENSE |
URL: | https://janmarvin.github.io/openxlsx2/, https://github.com/JanMarvin/openxlsx2 |
BugReports: | https://github.com/JanMarvin/openxlsx2/issues |
Depends: | R (≥ 3.5.0) |
Imports: | R6, Rcpp, grDevices, magrittr, stringi, utils, zip |
LinkingTo: | Rcpp |
Suggests: | ggplot2, knitr, mschart (≥ 0.4), rmarkdown, rvg, testthat (≥ 3.0.0), waldo |
VignetteBuilder: | knitr |
Encoding: | UTF-8 |
RoxygenNote: | 7.3.2 |
Config/testthat/edition: | 3 |
Config/testthat/parallel: | true |
NeedsCompilation: | yes |
Packaged: | 2025-07-04 06:09:03 UTC; janmarvingarbuszus |
Author: | Jordan Mark Barbone
|
Maintainer: | Jan Marvin Garbuszus <jan.garbuszus@ruhr-uni-bochum.de> |
Repository: | CRAN |
Date/Publication: | 2025-07-04 07:00:01 UTC |
xlsx reading, writing and editing.
Description
This R package is a modern reinterpretation of the widely used popular
openxlsx
package. Similar to its predecessor, it simplifies the creation of xlsx
files by providing a clean interface for writing, designing and editing worksheets.
Based on a powerful XML library and focusing on modern programming flows in pipes
or chains, openxlsx2
allows to break many new ground.
Details
The openxlsx2
package provides comprehensive functionality for interacting
with Office Open XML spreadsheet files. Users can read data using read_xlsx()
and write data to spreadsheets via write_xlsx()
, with options to specify
sheet names and cell ranges for targeted operations. Beyond basic read/write
capabilities, openxlsx2
facilitates extensive workbook (wb_workbook()
)
manipulations, including:
Loading a workbook into R with
wb_load()
and saving it withwb_save()
Adding/removing and modifying worksheets and data with
wb_add_worksheet()
,wb_remove_worksheet()
, andwb_add_data()
.Enhancing spreadsheets with comments (
wb_add_comment()
), images (wb_add_image()
), plots (wb_add_plot()
), charts (wb_add_mschart()
), and pivot tables (wb_add_pivot_table()
). Customizing cell styles using fonts (wb_add_font()
), number formats (wb_add_numfmt()
), backgrounds (wb_add_fill()
), and alignments (wb_add_cell_style()
). Inserting custom text strings withfmt_txt()
and creating comprehensive table styles withcreate_tablestyle()
.
Interaction
Interaction with openxlsx2
objects can occur 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. To find information,
users should look up the wb function name e.g. ?wb_add_data_table
rather than
searching for ?wbWorkbook
.
Function arguments follow the snake_case convention, but for backward compatibility,
camelCase is also supported at the moment. The API aims to maintain consistency
in its arguments, with a special focus on sheet
(wb_get_sheet_names()
) and
dims
(wb_dims), which are of particular importance to users.
Locale
By default, openxlsx2
uses the American English word for color (written with
'o' instead of the British English 'ou'). However, both spellings are supported.
So where the documentation uses a 'color', the function should also accept a 'colour'.
However, this is not indicated by the autocompletion.
Numeric Precision
R typically uses IEEE 754 double-precision floating-point
numbers. When openxlsx2
writes these R numeric values to a spreadsheet,
it stores them using double precision (and shortens if possible) within
the file structure. However, spreadsheet software operates with, displays,
and performs calculations using only about 15 significant decimal digits.
If spreadsheet software encounters a number with higher precision (like one
written by openxlsx2
), it will typically round that number to 15
significant digits for its internal use and display. Conversely, when
reading numeric data from an xlsx/xlsm file, openxlsx2
reads the stored
double-precision value. However, potential discrepancies can still arise.
If the number was originally created or calculated within Excel and
exceeded 15 digits, Excel may have already rounded it before saving.
Additionally, subtle rounding differences can sometimes occur during the
XML-to-numeric conversion when reading the file into R. Expect minor
variations, especially in the least significant digits, and avoid direct
equality (==
) comparisons; check for differences within a small
tolerance instead.
Supported files
Supported input files include xlsx
, xlsm
, and xlsb
. The xlsx
and
xlsm
formats are fully supported. The key difference between these two
formats is that xlsm
files may contain a binary blob that stores VBA
code, while xlsx
files do not.
Support for the xlsb
format is more limited. A custom parser is used to
convert the binary format into a pseudo-XML structure that can be loaded
into a wbWorkbook
. This allows xlsb
files to be handled similarly to
other workbook formats. However, the parser does not fully implement the
entire xlsb
specification. It provides functionality to read worksheets
into data frames and to save the content as an xlsx
or xlsm
file for
comparison of values and formulas. Some components, such as pivot tables
and conditional formatting, are not currently parsed. Writing xlsb
files
is not supported, and big endian support is very limited. At present,
there are no plans to extend support for xlsb
files further, due to the
complexity of the format. It is recommended to use spreadsheet software to
convert files to or from the xlsb
format when necessary.
The XML-based formats (xlsx
and xlsm
) are fully supported. Loading,
modifying, and saving these files with minimal unintended changes is a
core project goal. Nevertheless, the XML format can be fragile. Modifying
cells that interact with formulas, named objects such as tables or
regions, slicers, or pivot tables can lead to unexpected behavior. It is
therefore strongly advised to keep backups of important files and to
regularly verify the output using appropriate spreadsheet software.
Authors and contributions
For a full list of all authors that have made this package possible and for whom we are grateful, please see:
system.file("AUTHORS", package = "openxlsx2")
If you feel like you should be included on this list, please let us know. If you have something to contribute, you are welcome. If something is not working as expected, open issues or if you have solved an issue, open a pull request. Please be respectful and be aware that we are volunteers doing this for fun in our unpaid free time. We will work on problems when we have time or need.
License
This package is licensed under the MIT license and
is based on openxlsx
(by Alexander Walker and Philipp Schauberger; COPYRIGHT 2014-2022)
and pugixml
(by Arseny Kapoulkine; COPYRIGHT 2006-2025). Both released under the MIT license.
Author(s)
Maintainer: Jan Marvin Garbuszus jan.garbuszus@ruhr-uni-bochum.de
Authors:
Jordan Mark Barbone jmbarbone@gmail.com (ORCID)
Other contributors:
Olivier Roy [contributor]
openxlsx authors (openxlsx package) [copyright holder]
Arseny Kapoulkine (Author of included pugixml code) [contributor, copyright holder]
See Also
-
browseVignettes("openxlsx2")
-
https://janmarvin.github.io/ox2-book/ for examples
Examples
# read xlsx or xlsm files
path <- system.file("extdata/openxlsx2_example.xlsx", package = "openxlsx2")
read_xlsx(path)
# or import workbooks
wb <- wb_load(path)
# read a data frame
wb_to_df(wb)
# and save
temp <- temp_xlsx()
if (interactive()) wb_save(wb, temp)
## or create one yourself
wb <- wb_workbook()
# add a worksheet
wb$add_worksheet("sheet")
# add some data
wb$add_data("sheet", cars)
# open it in your default spreadsheet software
if (interactive()) wb$open()
Pipe operator
Description
See magrittr::%>%
for details.
Usage
lhs %>% rhs
Arguments
lhs |
A value or the magrittr placeholder. |
rhs |
A function call using the magrittr semantics. |
Value
The result of calling rhs(lhs)
.
Modify the state of active and selected sheets in a workbook
Description
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.
Usage
wb_get_active_sheet(wb)
wb_set_active_sheet(wb, sheet)
wb_get_selected(wb)
wb_set_selected(wb, sheet)
Arguments
wb |
a workbook |
sheet |
a sheet name of the workbook |
Value
a data frame with tabSelected and names
Examples
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
Description
loads character string to pugixml and returns an externalptr
Usage
as_xml(x, ...)
Arguments
x |
input as xml |
... |
additional arguments passed to |
Details
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)
Examples
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)
Set the default font in a workbook
Description
Modify / get the default font for the workbook. This will alter the latin major and minor font in the workbooks theme.
Usage
wb_set_base_font(
wb,
font_size = 11,
font_color = wb_color(theme = "1"),
font_name = "Aptos Narrow",
...
)
wb_get_base_font(wb)
Arguments
wb |
A workbook object |
font_size |
Font size |
font_color |
Font color |
font_name |
Name of a font |
... |
Additional arguments |
Details
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.
See Also
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()
Examples
## 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)
Clean worksheet name
Description
Cleans a worksheet name by removing legal characters.
Usage
clean_worksheet_name(x, replacement = " ")
Arguments
x |
A vector, coerced to |
replacement |
A single value to replace illegal characters by. |
Details
Illegal characters are considered \
, /
, ?
, *
, :
, [
, and
]
. These must be intentionally removed from worksheet names prior to
creating a new worksheet.
Value
x with bad characters removed
Convert Excel column to integer
Description
Converts an Excel column label to an integer.
Usage
col2int(x)
Arguments
x |
A character vector |
Value
An integer column label (or NULL
if x
is NULL
)
Examples
col2int(LETTERS)
Modify column widths of a worksheet
Description
Remove / set worksheet column widths to specified width or "auto".
Usage
wb_set_col_widths(
wb,
sheet = current_sheet(),
cols,
widths = 8.43,
hidden = FALSE
)
wb_remove_col_widths(wb, sheet = current_sheet(), cols)
Arguments
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 |
Details
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)
See Also
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()
Examples
## 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)
Internal comment functions
Description
Users are advised to use wb_add_comment()
and wb_remove_comment()
.
write_comment()
and remove_comment()
are now deprecated. openxlsx2 will stop
exporting it at some point in the future. Use the replacement functions.
Usage
write_comment(
wb,
sheet,
col = NULL,
row = NULL,
comment,
dims = rowcol_to_dim(row, col),
color = NULL,
file = NULL
)
remove_comment(
wb,
sheet,
col = NULL,
row = NULL,
gridExpand = TRUE,
dims = NULL
)
Arguments
wb |
A workbook object |
sheet |
A worksheet of the workbook |
row , col |
Row and column of the cell |
comment |
An object created by |
dims |
Optional row and column as spreadsheet dimension, e.g. "A1" |
color |
optional background color |
file |
optional background image (file extension must be png or jpeg) |
gridExpand |
If |
Examples
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)
create consecutive dims from column and row vector
Description
create consecutive dims from column and row vector
Usage
con_dims(cols, rows)
Arguments
cols , rows |
integer vectors |
consecutive range in vector
Description
consecutive range in vector
Usage
con_rng(x)
Arguments
x |
integer vector |
Convert to Excel data
Description
Arguments
df |
dataframe |
date1904 |
take different origin |
Convert from Excel date, datetime or hms number to R Date type
Description
Convert from Excel date number to R Date type
Usage
convert_date(x, origin = "1900-01-01", ...)
convert_datetime(x, origin = "1900-01-01", ...)
convert_hms(x)
Arguments
x |
A vector of integers |
origin |
date. Default value is for Windows Excel 2010 |
... |
Arguments passed on to
|
Details
Excel stores dates as number of days from some origin day
Value
A date, datetime, or hms.
See Also
Examples
# 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
Description
convert back to an Excel Date
Usage
convert_to_excel_date(df, date1904 = FALSE)
Arguments
df |
dataframe |
date1904 |
take different origin |
Examples
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)
Create border format
Description
This function creates border styles for a cell in a spreadsheet. Border styles can be any of the following: "none", "thin", "medium", "dashed", "dotted", "thick", "double", "hair", "mediumDashed", "dashDot", "mediumDashDot", "dashDotDot", "mediumDashDotDot", "slantDashDot". Border colors can be created with wb_color()
.
Usage
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 = "",
start_color = NULL,
end_color = NULL,
horizontal_color = NULL,
vertical_color = NULL,
...
)
Arguments
diagonal_down , diagonal_up |
Logical, whether the diagonal border goes from the bottom left to the top right, or top left to bottom right. |
outline |
Logical, whether the border is. |
bottom , left , right , top , diagonal |
Character, the style of the border. |
bottom_color , left_color , right_color , top_color , diagonal_color , start_color , end_color , horizontal_color , vertical_color |
a |
horizontal , vertical |
Character, the style of the inner border (only for dxf objects). |
start , end |
leading and trailing edge of a border. |
... |
Additional arguments passed to other methods. |
Value
A formatted border object to be used in a spreadsheet.
See Also
Other style creating functions:
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Examples
# Create a border with a thick bottom and thin top
border <- create_border(
bottom = "thick",
bottom_color = wb_color("FF0000"),
top = "thin",
top_color = wb_color("00FF00")
)
Create cell style
Description
This function creates a cell style for a spreadsheet, including attributes such as borders, fills, fonts, and number formats.
Usage
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 = "",
...
)
Arguments
border_id , fill_id , font_id , num_fmt_id |
IDs for style elements. |
pivot_button |
Logical parameter for the pivot button. |
quote_prefix |
Logical parameter for the quote prefix. (This way a number in a character cell will not cause a warning). |
xf_id |
Dummy parameter for the xf ID. (Used only with named format styles). |
horizontal |
Character, alignment can be ”, 'general', 'left', 'center', 'right', 'fill', 'justify', 'centerContinuous', 'distributed'. |
indent |
Integer parameter for the indent. |
justify_last_line |
Logical for justifying the last line. |
reading_order |
Logical parameter for reading order. 0 (Left to right; default) or 1 (right to left). |
relative_indent |
Dummy parameter for relative indent. |
shrink_to_fit |
Logical parameter for shrink to fit. |
text_rotation |
Integer parameter for text rotation (-180 to 180). |
vertical |
Character, alignment can be ”, 'top', 'center', 'bottom', 'justify', 'distributed'. |
wrap_text |
Logical parameter for wrap text. (Required for linebreaks). |
ext_lst |
Dummy parameter for extension list. |
Logical parameter for hidden. | |
locked |
Logical parameter for locked. (Impacts the cell only). |
... |
Reserved for additional arguments. |
Details
A single cell style can make use of various other styles like border, fill, and font. These styles are independent of the cell style and must be registered with the style manager separately.
This allows multiple cell styles to share a common font type, for instance. The used style elements are passed to the cell style via their IDs. An example of this can be seen below.
The number format can be a custom one created by create_numfmt()
, or a built-in style from the formats table below.
"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" | "@" |
Value
A formatted cell style object to be used in a spreadsheet.
See Also
Other style creating functions:
create_border()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Examples
foo_fill <- create_fill(pattern_type = "lightHorizontal",
fg_color = wb_color("blue"),
bg_color = wb_color("orange"))
foo_font <- create_font(sz = 36, b = TRUE, color = wb_color("yellow"))
wb <- wb_workbook()
wb$styles_mgr$add(foo_fill, "foo")
wb$styles_mgr$add(foo_font, "foo")
foo_style <- create_cell_style(
fill_id = wb$styles_mgr$get_fill_id("foo"),
font_id = wb$styles_mgr$get_font_id("foo")
)
Create custom color xml schemes
Description
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.
Usage
create_colors_xml(name = "Base R", dark = NULL, accent = NULL, link = NULL)
Arguments
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 |
See Also
Other style creating functions:
create_border()
,
create_cell_style()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Examples
colors <- create_colors_xml()
wb <- wb_workbook()$add_worksheet()$set_base_colors(xml = colors)
Create a comment
Description
Use wb_comment()
in new code. See openxlsx2-deprecated
Usage
create_comment(
text,
author = Sys.info()[["user"]],
style = NULL,
visible = TRUE,
width = 2,
height = 4
)
Arguments
text |
Comment text. Character vector. or a |
author |
A string, by default, will use "user" |
style |
A Style object or list of style objects the same length as comment vector. |
visible |
Default: |
width |
Textbox integer width in number of cells |
height |
Textbox integer height in number of cells |
Value
a wbComment
object
Create a custom formatting style
Description
Create a new style to apply to worksheet cells. These styles are used in conditional formatting and in (pivot) table styles.
Usage
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,
...
)
Arguments
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 |
Details
It is possible to override border_color and border_style with {left, right, top, bottom}_color, {left, right, top, bottom}_style.
Value
A dxfs style node
See Also
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()
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"),
bg_fill = 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"),
bg_fill = wb_color(hex = "FFFFC7CE")
)
## See package vignettes for further examples
Create fill pattern
Description
This function creates fill patterns for a cell in a spreadsheet. Fill patterns can be simple solid colors or more complex gradient fills. For certain pattern types, two colors are needed.
Usage
create_fill(
gradient_fill = "",
pattern_type = "",
bg_color = NULL,
fg_color = NULL,
...
)
Arguments
gradient_fill |
Character, specifying complex gradient fills. |
pattern_type |
Character, specifying the fill pattern type. Valid values are "none" (default), "solid", "mediumGray", "darkGray", "lightGray", "darkHorizontal", "darkVertical", "darkDown", "darkUp", "darkGrid", "darkTrellis", "lightHorizontal", "lightVertical", "lightDown", "lightUp", "lightGrid", "lightTrellis", "gray125", "gray0625". |
bg_color |
Character, specifying the background color in hex8 format (alpha, red, green, blue) for pattern fills. |
fg_color |
Character, specifying the foreground color in hex8 format (alpha, red, green, blue) for pattern fills. |
... |
Additional arguments passed to other methods. |
Value
A formatted fill pattern object to be used in a spreadsheet.
See Also
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_font()
,
create_numfmt()
,
create_tablestyle()
Examples
# Create a solid fill pattern with foreground color
fill <- create_fill(
pattern_type = "solid",
fg_color = wb_color(hex = "FFFF0000")
)
Create font format
Description
This function creates font styles for a cell in a spreadsheet. It allows customization of various font properties including bold, italic, color, size, underline, and more.
Usage
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 = "",
...
)
Arguments
b |
Logical, whether the font should be bold. |
charset |
Character, the character set to be used. The list of valid IDs can be found in the Details section of |
color |
A |
condense |
Logical, whether the font should be condensed. |
extend |
Logical, whether the font should be extended. |
family |
Character, the font family. Default is "2" (modern). "0" (auto), "1" (roman), "2" (swiss), "3" (modern), "4" (script), "5" (decorative). # 6-14 unused |
i |
Logical, whether the font should be italic. |
name |
Character, the name of the font. Default is "Aptos Narrow". |
outline |
Logical, whether the font should have an outline. |
scheme |
Character, the font scheme. Valid values are "minor", "major", "none". Default is "minor". |
shadow |
Logical, whether the font should have a shadow. |
strike |
Logical, whether the font should have a strikethrough. |
sz |
Character, the size of the font. Default is "11". |
u |
Character, the underline style. Valid values are "single", "double", "singleAccounting", "doubleAccounting", "none". |
vert_align |
Character, the vertical alignment of the font. Valid values are "baseline", "superscript", "subscript". |
... |
Additional arguments passed to other methods. |
Value
A formatted font object to be used in a spreadsheet.
See Also
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_numfmt()
,
create_tablestyle()
Examples
# Create a font with bold and italic styles
font <- create_font(
b = TRUE,
i = TRUE,
color = wb_color(hex = "FF00FF00"),
name = "Arial",
sz = "12"
)
# 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"))
Create Excel hyperlink string
Description
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.
Usage
create_hyperlink(sheet, row = 1, col = 1, text = NULL, file = NULL)
Arguments
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 |
See Also
Examples
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
Description
This function creates a number format for a cell in a spreadsheet. Number formats define how numeric values are displayed, including dates, times, currencies, percentages, and more.
Usage
create_numfmt(numFmtId = 164, formatCode = "#,##0.00")
Arguments
numFmtId |
An ID representing the number format. The list of valid IDs can be found in the Details section of |
formatCode |
A format code that specifies the display format for numbers. This can include custom formats for dates, times, and other numeric values. |
Value
A formatted number format object to be used in a spreadsheet.
See Also
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_tablestyle()
Examples
# Create a number format for currency
numfmt <- create_numfmt(
numFmtId = 164,
formatCode = "$#,##0.00"
)
Helper to create a shape
Description
Helper to create a shape
Usage
create_shape(
shape = "rect",
name = "shape 1",
text = "",
fill_color = NULL,
fill_transparency = 0,
text_color = NULL,
text_transparency = 0,
line_color = fill_color,
line_transparency = 0,
text_align = "left",
rotation = 0,
id = 1,
...
)
Arguments
shape |
a shape (see details) |
name |
a name for the shape |
text |
a text written into the object. This can be a simple character or a |
fill_color , text_color , line_color |
a color for each, accepts only theme and rgb colors passed with |
fill_transparency , text_transparency , line_transparency |
sets the alpha value of the shape, an integer value in the range 0 to 100 |
text_align |
sets the alignment of the text. Can be 'left', 'center', 'right', 'justify', 'justifyLow', 'distributed', or 'thaiDistributed' |
rotation |
the rotation of the shape in degrees |
id |
an integer id (effect is unknown) |
... |
additional arguments |
Details
Possible shapes are (from ST_ShapeType - Preset Shape Types): "line", "lineInv", "triangle", "rtTriangle", "rect", "diamond", "parallelogram", "trapezoid", "nonIsoscelesTrapezoid", "pentagon", "hexagon", "heptagon", "octagon", "decagon", "dodecagon", "star4", "star5", "star6", "star7", "star8", "star10", "star12", "star16", "star24", "star32", "roundRect", "round1Rect", "round2SameRect", "round2DiagRect", "snipRoundRect", "snip1Rect", "snip2SameRect", "snip2DiagRect", "plaque", "ellipse", "teardrop", "homePlate", "chevron", "pieWedge", "pie", "blockArc", "donut", "noSmoking", "rightArrow", "leftArrow", "upArrow", "downArrow", "stripedRightArrow", "notchedRightArrow", "bentUpArrow", "leftRightArrow", "upDownArrow", "leftUpArrow", "leftRightUpArrow", "quadArrow", "leftArrowCallout", "rightArrowCallout", "upArrowCallout", "downArrowCallout", "leftRightArrowCallout", "upDownArrowCallout", "quadArrowCallout", "bentArrow", "uturnArrow", "circularArrow", "leftCircularArrow", "leftRightCircularArrow", "curvedRightArrow", "curvedLeftArrow", "curvedUpArrow", "curvedDownArrow", "swooshArrow", "cube", "can", "lightningBolt", "heart", "sun", "moon", "smileyFace", "irregularSeal1", "irregularSeal2", "foldedCorner", "bevel", "frame", "halfFrame", "corner", "diagStripe", "chord", "arc", "leftBracket", "rightBracket", "leftBrace", "rightBrace", "bracketPair", "bracePair", "straightConnector1", "bentConnector2", "bentConnector3", "bentConnector4", "bentConnector5", "curvedConnector2", "curvedConnector3", "curvedConnector4", "curvedConnector5", "callout1", "callout2", "callout3", "accentCallout1", "accentCallout2", "accentCallout3", "borderCallout1", "borderCallout2", "borderCallout3", "accentBorderCallout1", "accentBorderCallout2", "accentBorderCallout3", "wedgeRectCallout", "wedgeRoundRectCallout", "wedgeEllipseCallout", "cloudCallout", "cloud", "ribbon", "ribbon2", "ellipseRibbon", "ellipseRibbon2", "leftRightRibbon", "verticalScroll", "horizontalScroll", "wave", "doubleWave", "plus", "flowChartProcess", "flowChartDecision", "flowChartInputOutput", "flowChartPredefinedProcess", "flowChartInternalStorage", "flowChartDocument", "flowChartMultidocument", "flowChartTerminator", "flowChartPreparation", "flowChartManualInput", "flowChartManualOperation", "flowChartConnector", "flowChartPunchedCard", "flowChartPunchedTape", "flowChartSummingJunction", "flowChartOr", "flowChartCollate", "flowChartSort", "flowChartExtract", "flowChartMerge", "flowChartOfflineStorage", "flowChartOnlineStorage", "flowChartMagneticTape", "flowChartMagneticDisk", "flowChartMagneticDrum", "flowChartDisplay", "flowChartDelay", "flowChartAlternateProcess", "flowChartOffpageConnector", "actionButtonBlank", "actionButtonHome", "actionButtonHelp", "actionButtonInformation", "actionButtonForwardNext", "actionButtonBackPrevious", "actionButtonEnd", "actionButtonBeginning", "actionButtonReturn", "actionButtonDocument", "actionButtonSound", "actionButtonMovie", "gear6", "gear9", "funnel", "mathPlus", "mathMinus", "mathMultiply", "mathDivide", "mathEqual", "mathNotEqual", "cornerTabs", "squareTabs", "plaqueTabs", "chartX", "chartStar", "chartPlus"
Value
a character containing the XML
See Also
Examples
wb <- wb_workbook()$add_worksheet()$
add_drawing(xml = create_shape())
Create sparklines object
Description
Create a sparkline to be added a workbook with wb_add_sparklines()
Usage
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,
direction = NULL,
...
)
Arguments
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 |
direction |
Either |
... |
additional arguments |
Details
Colors are all predefined to be rgb. Maybe theme colors can be used too.
Value
A string containing XML code
Examples
# create multiple sparklines
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"),
create_sparklines("Sheet 1", "A5:L5;A7:L7", "M5;M7", markers = "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 sparkline groups
sparklines <- c(
create_sparklines("Sheet 2", "A2:L6;", "M2:M6", markers = "1"),
create_sparklines(
"Sheet 2", "A7:L7;A9:L9", "M7;M9", type = "stacked", negative = "1"
),
create_sparklines(
"Sheet 2", "A8:L8;A10:L13", "M8;M10:M13",
type = "column", first = "1"
),
create_sparklines(
"Sheet 2", "A2:L13", "A14:L14", type = "column", first = "1",
direction = "col"
)
)
wb <- wb$
add_worksheet("Sheet 2")$
add_data(x = t2)$
add_sparklines(sparklines = sparklines)
Create custom (pivot) table styles
Description
Create a custom (pivot) table style. These functions are for expert use only. Use other styling functions instead.
Usage
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,
...
)
Arguments
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 |
See Also
Other style creating functions:
create_border()
,
create_cell_style()
,
create_colors_xml()
,
create_dxfs_style()
,
create_fill()
,
create_font()
,
create_numfmt()
Modify creators of a workbook
Description
Modify and get workbook creators
Usage
wb_add_creators(wb, creators)
wb_set_creators(wb, creators)
wb_remove_creators(wb, creators)
wb_get_creators(wb)
Arguments
wb |
A |
creators |
A character vector of names |
Value
-
wb_set_creators()
,wb_add_creators()
, andwb_remove_creators()
return thewbWorkbook
object -
wb_get_creators()
returns acharacter
vector of creators
See Also
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()
Examples
# 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)
Create dimensions from dataframe
Description
Use wb_dims()
Usage
dataframe_to_dims(df, dim_break = FALSE)
Arguments
df |
dataframe with spreadsheet columns and rows |
dim_break |
split the dims? |
Examples
df <- dims_to_dataframe("A1:D5;F1:F6;D8", fill = TRUE)
dataframe_to_dims(df)
Delete data
Description
This function is deprecated. Use wb_clean_sheet()
.
Usage
delete_data(wb, sheet, cols, rows)
Arguments
wb |
workbook |
sheet |
sheet to clean |
cols |
numeric column vector |
rows |
numeric row vector |
Helper functions to work with dims
Description
Internal helpers to (de)construct a dims argument from/to a row and column vector. Exported for user convenience.
Usage
dims_to_rowcol(x, as_integer = FALSE)
rowcol_to_dims(row, col, single = TRUE)
Arguments
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 |
Value
A
dims
string for_to_dim
i.e "A1:A1"A named list of rows and columns for
to_rowcol
See Also
Examples
dims_to_rowcol("A1:J10")
wb_dims(1:10, 1:10)
Create dataframe from dimensions
Description
Non consecutive decreasing dims will return an increasing data frame.
Usage
dims_to_dataframe(dims, fill = FALSE, empty_rm = FALSE)
Arguments
dims |
Character vector of expected dimension. |
fill |
If |
empty_rm |
Logical if empty columns and rows should be included |
Examples
dims_to_dataframe("A1:B2")
Add/remove column filters in a worksheet
Description
Add or remove excel column filters to a worksheet
Usage
wb_add_filter(wb, sheet = current_sheet(), rows, cols)
wb_remove_filter(wb, sheet = current_sheet())
Arguments
wb |
A workbook object |
sheet |
A worksheet name or index.
In |
rows |
A row number. |
cols |
columns to add filter to. |
Details
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.
See Also
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()
Examples
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.
Description
format strings independent of the cell style.
Usage
fmt_txt(
x,
bold = FALSE,
italic = FALSE,
underline = FALSE,
strike = FALSE,
size = NULL,
color = NULL,
font = NULL,
charset = NULL,
outline = NULL,
vert_align = NULL,
family = NULL,
shadow = NULL,
condense = NULL,
extend = 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, ...)
Arguments
x , y |
an openxlsx2 fmt_txt string |
bold , italic , underline , strike |
logical defaulting to |
size |
the font size |
color |
a |
font |
the font name |
charset |
integer value from the table below |
outline , shadow , condense , extend |
logical defaulting to |
vert_align |
any of |
family |
a font family |
... |
additional arguments |
Details
The result is an xml string. It is possible to paste multiple fmt_txt()
strings together to create a string with differing styles. It is possible to
supply different underline styles to underline
.
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
.
See Also
Examples
fmt_txt("bar", underline = TRUE)
fmt_txt("foo ", bold = TRUE) + fmt_txt("bar")
as.character(fmt_txt(2))
Group rows and columns in a worksheet
Description
Group a selection of rows or cols
Usage
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)
Arguments
wb |
A |
sheet |
A name or index of a worksheet |
collapsed |
If |
levels |
levels |
rows , cols |
Indices or for columns also characters of rows and columns to group |
Details
If row was previously hidden, it will now be shown. Columns can be
added using A1 notion, so cols = 2:3
is similar to cols = "B:C"
. It is
possible to add nested groups, so cols = list("3" = list(1:2, 3:4)
is also
possible. Depending on the selected summary column either left or right will
be selected for grouping, this can be changed in wb_set_page_setup()
.
See Also
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()
Examples
# 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)
Convert integer to Excel column
Description
Converts an integer to an Excel column label.
Usage
int2col(x)
Arguments
x |
A numeric vector. |
Examples
int2col(1:10)
helper to check if a string looks like a cell
Description
helper to check if a string looks like a cell
Usage
is_dims(x)
Arguments
x |
a string |
Modify named regions in a worksheet
Description
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.
Usage
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)
Arguments
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 |
Details
You can use the wb_dims()
helper to specify the cell range of the named region
Value
A workbook, invisibly.
A data frame with the all named regions in wb
. Or NULL
, if none are found.
See Also
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()
Examples
## 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()
Deprecated functions in package openxlsx2
Description
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.
Internal functions
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
Deprecated functions
First of all, you can set an option that will add warnings when using deprecated functions.
options("openxlsx2.soon_deprecated" = TRUE)
Argument changes
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
Functions with a new name
These functions were renamed for consistency.
Deprecated usage
-
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()`
See Also
Options consulted by openxlsx2
Description
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 toTRUE
if you want a warning if using some functions deprecated recently in openxlsx2 -
options("openxlsx2.creator")
A default name for the creator of newwbWorkbook
object withwb_workbook()
or new comments withwb_add_comment()
-
options("openxlsx2.thread_id")
the default person id when adding a threaded comment to a cell withwb_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 as1
-
options("openxlsx2.na.strings" = "#N/A")
consulted bywrite_xlsx()
,wb_add_data()
andwb_add_data_table()
. -
options("openxlsx2.compression_level" = 6)
compression level for the output file. Increasing compression and time consumed from 1-9.
Helper for adding threaded comments
Description
Adds a person to a workbook, so that they can be the author of threaded
comments in a workbook with wb_add_thread()
Usage
wb_add_person(wb, name = NULL, id = NULL, user_id = NULL, provider_id = "None")
wb_get_person(wb, name = NULL)
Arguments
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 |
See Also
print pugi_xml
Description
print pugi_xml
Usage
## S3 method for class 'pugi_xml'
print(x, indent = " ", raw = FALSE, attr_indent = FALSE, ...)
Arguments
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 |
Examples
# a pointer
x <- read_xml("<a><b/></a>")
print(x)
print(x, raw = TRUE)
Modify workbook properties
Description
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.
Usage
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
)
Arguments
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 |
Details
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.
Value
A wbWorkbook object, invisibly.
See Also
Examples
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()
xml_node
Description
returns xml values as character
Usage
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, ...)
Arguments
xml |
something xml |
level1 |
to please check |
level2 |
to please check |
level3 |
to please check |
... |
additional arguments passed to |
Details
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
Examples
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
Description
read xml file
Usage
read_xml(
xml,
pointer = TRUE,
escapes = FALSE,
declaration = FALSE,
whitespace = TRUE,
empty_tags = FALSE,
skip_control = TRUE
)
Arguments
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 |
Details
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().
Examples
# 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)
Modify row heights of a worksheet
Description
Set / remove custom worksheet row heights
Usage
wb_set_row_heights(
wb,
sheet = current_sheet(),
rows,
heights = NULL,
hidden = FALSE
)
wb_remove_row_heights(wb, sheet = current_sheet(), rows)
Arguments
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 |
See Also
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()
Examples
## Create a new workbook
wb <- wb_workbook()
## Add a worksheet
wb$add_worksheet("Sheet 1")
## set row heights
wb <- wb_set_row_heights(
wb, 1,
rows = c(1, 4, 22, 2, 19),
heights = c(24, 28, 32, 42, 33)
)
## overwrite row 1 height
wb <- wb_set_row_heights(wb, 1, rows = 1, heights = 40)
## remove any custom row heights in row 1
wb$remove_row_heights(sheet = 1, rows = 1)
Get / Set worksheet names for a workbook
Description
Gets / Sets the worksheet names for a wbWorkbook object.
Usage
wb_set_sheet_names(wb, old = NULL, new)
wb_get_sheet_names(wb, escape = FALSE)
Arguments
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? |
Details
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.
Value
-
set_
: ThewbWorkbook
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/set worksheet visible state in a workbook
Description
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)
Usage
wb_get_sheet_visibility(wb)
wb_set_sheet_visibility(wb, sheet = current_sheet(), value)
Arguments
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" |
Value
-
wb_set_sheet_visibility
: The Workbook object, invisibly. -
wb_get_sheet_visibility()
: A character vector of the worksheet visibility value
Examples
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
Description
Get all styles on a sheet
Usage
styles_on_sheet(wb, sheet)
Arguments
wb |
workbook |
sheet |
worksheet |
helper function to create temporary directory for testing purpose
Description
helper function to create temporary directory for testing purpose
Usage
temp_xlsx(name = "temp_xlsx", macros = FALSE)
Arguments
name |
for the temp file |
macros |
logical if the file extension is xlsm or xlsx |
openxlsx2
waivers
Description
Waiver functions for openxlsx2
functions.
-
current_sheet()
useswb_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. It is defined as available sheets + 1L.
Usage
current_sheet()
next_sheet()
na_strings()
Value
An object of class openxlsx2_waiver
Workbook class
Description
This is the class used by openxlsx2
to modify workbooks from R.
You can load an existing workbook with wb_load()
and create a new one with
wb_workbook()
.
After that, you can modify the wbWorkbook
object through two primary methods:
Wrapper Function Method: Utilizes the wb
family of functions that support
piping to streamline operations.
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
).
Public fields
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
activeX
activeX
embeddings
embeddings
externalLinks
externalLinks
externalLinksRels
externalLinksRels
featurePropertyBag
featurePropertyBag
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
namedSheetViews
namedSheetViews
Methods
Public methods
Method new()
Creates a new wbWorkbook
object
Usage
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, ... )
Arguments
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 currentSys.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
Returns
a wbWorkbook
object
Method append()
Append a field. This method is intended for internal use
Usage
wbWorkbook$append(field, value)
Arguments
field
A valid field name
value
A value for the field
Method append_sheets()
Append to self$workbook$sheets
This method is intended for internal use
Usage
wbWorkbook$append_sheets(value)
Arguments
value
A value for
self$workbook$sheets
Method validate_sheet()
validate sheet
Usage
wbWorkbook$validate_sheet(sheet)
Arguments
sheet
A character sheet name or integer location
Returns
The integer position of the sheet
Method add_chartsheet()
Add a chart sheet to the workbook
Usage
wbWorkbook$add_chartsheet( sheet = next_sheet(), tab_color = NULL, zoom = 100, visible = c("true", "false", "hidden", "visible", "veryhidden"), ... )
Arguments
sheet
The name of the sheet
tab_color
tab_color
zoom
zoom
visible
visible
...
additional arguments
Returns
The wbWorkbook
object, invisibly
Method add_worksheet()
Add worksheet to the wbWorkbook
object
Usage
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)), ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method clone_worksheet()
Clone a workbooksheet to another workbook
Usage
wbWorkbook$clone_worksheet( old = current_sheet(), new = next_sheet(), from = NULL )
Arguments
old
name of worksheet to clone
new
name of new worksheet to add
from
name of new worksheet to add
Method add_data()
add data
Usage
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, ... )
Arguments
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 fromx
. Defaultna_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 matchx
...
additional arguments
return
The
wbWorkbook
object
Method add_data_table()
add a data table
Usage
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, ... )
Arguments
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 fromx
. Defaultna_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
Returns
The wbWorkbook
object
Method add_pivot_table()
add pivot table
Usage
wbWorkbook$add_pivot_table( x, sheet = next_sheet(), dims = "A3", filter, rows, cols, data, fun, params, pivot_table, slicer, timeline )
Arguments
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
Details
fun
can be either of AVERAGE, COUNT, COUNTA, MAX, MIN, PRODUCT, STDEV,
STDEVP, SUM, VAR, VARP
Returns
The wbWorkbook
object
Method add_slicer()
add pivot table
Usage
wbWorkbook$add_slicer( x, dims = "A1", sheet = current_sheet(), pivot_table, slicer, params )
Arguments
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
Returns
The wbWorkbook
object
Method remove_slicer()
add pivot table
Usage
wbWorkbook$remove_slicer(sheet = current_sheet())
Arguments
sheet
The name of the sheet
Returns
The wbWorkbook
object
Method add_timeline()
add pivot table
Usage
wbWorkbook$add_timeline( x, dims = "A1", sheet = current_sheet(), pivot_table, timeline, params )
Arguments
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
Returns
The wbWorkbook
object
Method remove_timeline()
add pivot table
Usage
wbWorkbook$remove_timeline(sheet = current_sheet())
Arguments
sheet
The name of the sheet
Returns
The wbWorkbook
object
Method add_formula()
Add formula
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object
Method add_hyperlink()
Add hyperlink
Usage
wbWorkbook$add_hyperlink( sheet = current_sheet(), dims = "A1", target = NULL, tooltip = NULL, is_external = TRUE, col_names = FALSE )
Arguments
sheet
sheet
dims
dims
target
target
tooltip
tooltip
is_external
is_external
col_names
col_names
Returns
The wbWorkbook
object
Method remove_hyperlink()
remove hyperlink
Usage
wbWorkbook$remove_hyperlink(sheet = current_sheet(), dims = NULL)
Arguments
sheet
sheet
dims
dims
Returns
The wbWorkbook
object
Method add_style()
add style
Usage
wbWorkbook$add_style(style = NULL, style_name = NULL)
Arguments
style
style
style_name
style_name
Returns
The wbWorkbook
object
Method to_df()
to_df
Usage
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, ... )
Arguments
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
Returns
a data frame
Method load()
load workbook
Usage
wbWorkbook$load(file, sheet, data_only = FALSE, ...)
Arguments
file
file
sheet
The name of the sheet
data_only
data_only
...
additional arguments
Returns
The wbWorkbook
object invisibly
Method save()
Save the workbook
Usage
wbWorkbook$save(file = self$path, overwrite = TRUE, path = NULL, flush = FALSE)
Arguments
file
The path to save the workbook to
overwrite
If
FALSE
, will not overwrite whenpath
existspath
Deprecated argument previously used for file. Please use file in new code.
flush
Experimental, streams the worksheet file to disk
Returns
The wbWorkbook
object invisibly
Method open()
open wbWorkbook in Excel.
Usage
wbWorkbook$open(interactive = NA, flush = FALSE)
Arguments
interactive
If
FALSE
will throw a warning and not open the path. This can be manually set toTRUE
, otherwise whenNA
(default) uses the value returned frombase::interactive()
flush
flush
Details
minor helper wrapping xl_open which does the entire same thing
Returns
The wbWorkbook
, invisibly
Method buildTable()
Build table
Usage
wbWorkbook$buildTable( sheet = current_sheet(), colNames, ref, showColNames, tableStyle, tableName, withFilter = TRUE, totalsRowCount = 0, totalLabel = FALSE, showFirstColumn = 0, showLastColumn = 0, showRowStripes = 1, showColumnStripes = 0 )
Arguments
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
Returns
The wbWorksheet
object, invisibly
Method update_table()
update a data_table
Usage
wbWorkbook$update_table(sheet = current_sheet(), dims = "A1", tabname)
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
tabname
a tablename
Returns
The wbWorksheet
object, invisibly
Method copy_cells()
copy cells around in a workbook
Usage
wbWorkbook$copy_cells( sheet = current_sheet(), dims = "A1", data, as_value = FALSE, as_ref = FALSE, transpose = FALSE, ... )
Arguments
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
Returns
The wbWorksheet
object, invisibly
Method get_base_font()
Get the base font
Usage
wbWorkbook$get_base_font()
Returns
A list of of the font
Method set_base_font()
Set the base font
Usage
wbWorkbook$set_base_font( font_size = 11, font_color = wb_color(theme = "1"), font_name = "Aptos Narrow", ... )
Arguments
font_size
fontSize
font_color
font_color
font_name
font_name
...
additional arguments
Returns
The wbWorkbook
object
Method get_base_colors()
Get the base color
Usage
wbWorkbook$get_base_colors(xml = FALSE, plot = TRUE)
Arguments
xml
xml
plot
plot
Method get_base_colours()
Get the base colour
Usage
wbWorkbook$get_base_colours(xml = FALSE, plot = TRUE)
Arguments
xml
xml
plot
plot
Method set_base_colors()
Set the base color
Usage
wbWorkbook$set_base_colors(theme = "Office", ...)
Arguments
theme
theme
...
...
Returns
The wbWorkbook
object
Method set_base_colours()
Set the base colour
Usage
wbWorkbook$set_base_colours(theme = "Office", ...)
Arguments
theme
theme
...
...
Returns
The wbWorkbook
object
Method get_bookview()
Get the book views
Usage
wbWorkbook$get_bookview()
Returns
A dataframe with the bookview properties
Method remove_bookview()
Get the book views
Usage
wbWorkbook$remove_bookview(view = NULL)
Arguments
view
view
Returns
The wbWorkbook
object
Method set_bookview()
Usage
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, view = 1L, ... )
Arguments
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
view
view
...
additional arguments
Returns
The wbWorkbook
object
Method get_sheet_names()
Get sheet names
Usage
wbWorkbook$get_sheet_names(escape = FALSE)
Arguments
escape
Logical if the xml special characters are escaped
Returns
A named
character
vector of sheet names in their order. The
names represent the original value of the worksheet prior to any
character substitutions.
Method set_sheet_names()
Sets a sheet name
Usage
wbWorkbook$set_sheet_names(old = NULL, new)
Arguments
old
Old sheet name
new
New sheet name
Returns
The wbWorkbook
object, invisibly
Method set_row_heights()
Sets a row height for a sheet
Usage
wbWorkbook$set_row_heights( sheet = current_sheet(), rows, heights = NULL, hidden = FALSE )
Arguments
sheet
The name of the sheet
rows
rows
heights
heights
hidden
hidden
Returns
The wbWorkbook
object, invisibly
Method remove_row_heights()
Removes a row height for a sheet
Usage
wbWorkbook$remove_row_heights(sheet = current_sheet(), rows)
Arguments
sheet
The name of the sheet
rows
rows
Returns
The wbWorkbook
object, invisibly
Method createCols()
creates column object for worksheet
Usage
wbWorkbook$createCols(sheet = current_sheet(), n, beg, end)
Arguments
sheet
The name of the sheet
n
n
beg
beg
end
end
Method group_cols()
Group cols
Usage
wbWorkbook$group_cols( sheet = current_sheet(), cols, collapsed = FALSE, levels = NULL )
Arguments
sheet
The name of the sheet
cols
cols
collapsed
collapsed
levels
levels
Returns
The wbWorkbook
object, invisibly
Method ungroup_cols()
ungroup cols
Usage
wbWorkbook$ungroup_cols(sheet = current_sheet(), cols)
Arguments
sheet
The name of the sheet
cols
columns
Returns
The wbWorkbook
object
Method remove_col_widths()
Remove row heights from a worksheet
Usage
wbWorkbook$remove_col_widths(sheet = current_sheet(), cols)
Arguments
sheet
A name or index of a worksheet
cols
Indices of columns to remove custom width (if any) from.
Returns
The wbWorkbook
object, invisibly
Method set_col_widths()
Set column widths
Usage
wbWorkbook$set_col_widths( sheet = current_sheet(), cols, widths = 8.43, hidden = FALSE )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method group_rows()
Group rows
Usage
wbWorkbook$group_rows( sheet = current_sheet(), rows, collapsed = FALSE, levels = NULL )
Arguments
sheet
The name of the sheet
rows
rows
collapsed
collapsed
levels
levels
Returns
The wbWorkbook
object, invisibly
Method ungroup_rows()
ungroup rows
Usage
wbWorkbook$ungroup_rows(sheet = current_sheet(), rows)
Arguments
sheet
The name of the sheet
rows
rows
Returns
The wbWorkbook
object
Method remove_worksheet()
Remove a worksheet
Usage
wbWorkbook$remove_worksheet(sheet = current_sheet())
Arguments
sheet
The worksheet to delete
Returns
The wbWorkbook
object, invisibly
Method add_data_validation()
Adds data validation
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object
Method merge_cells()
Set cell merging for a sheet
Usage
wbWorkbook$merge_cells( sheet = current_sheet(), dims = NULL, solve = FALSE, direction = NULL, ... )
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
solve
logical if intersecting cells should be solved
direction
direction in which to split the cell merging. Allows "row" or "col".
...
additional arguments
Returns
The wbWorkbook
object, invisibly
Method unmerge_cells()
Removes cell merging for a sheet
Usage
wbWorkbook$unmerge_cells(sheet = current_sheet(), dims = NULL, ...)
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
...
additional arguments
Returns
The wbWorkbook
object, invisibly
Method freeze_pane()
Set freeze panes for a sheet
Usage
wbWorkbook$freeze_pane( sheet = current_sheet(), first_active_row = NULL, first_active_col = NULL, first_row = FALSE, first_col = FALSE, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method add_comment()
Add comment
Usage
wbWorkbook$add_comment(sheet = current_sheet(), dims = "A1", comment, ...)
Arguments
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
Returns
The wbWorkbook
object
Method get_comment()
Get comments
Usage
wbWorkbook$get_comment(sheet = current_sheet(), dims = NULL)
Arguments
sheet
sheet
dims
dims
Returns
A data frame containing comments
Method remove_comment()
Remove comment
Usage
wbWorkbook$remove_comment(sheet = current_sheet(), dims = "A1", ...)
Arguments
sheet
The name of the sheet
dims
row and column as spreadsheet dimension, e.g. "A1"
...
additional arguments
Returns
The wbWorkbook
object
Method add_thread()
add threaded comment to worksheet
Usage
wbWorkbook$add_thread( sheet = current_sheet(), dims = "A1", comment = NULL, person_id, reply = FALSE, resolve = FALSE )
Arguments
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
Method get_thread()
Get threads
Usage
wbWorkbook$get_thread(sheet = current_sheet(), dims = NULL)
Arguments
sheet
sheet
dims
dims
Returns
A data frame containing threads
Method add_conditional_formatting()
Add conditional formatting
Usage
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), ... )
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
rule
rule
style
style
type
type
params
Additional parameters
...
additional arguments
Returns
The wbWorkbook
object
Method remove_conditional_formatting()
Remove conditional formatting
Usage
wbWorkbook$remove_conditional_formatting( sheet = current_sheet(), dims = NULL, first = FALSE, last = FALSE )
Arguments
sheet
sheet
dims
dims
first
first
last
last
Returns
The wbWorkbook
object
Method add_image()
Insert an image into a sheet
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method add_plot()
Add plot. A wrapper for add_image()
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object
Method add_drawing()
Add xml drawing
Usage
wbWorkbook$add_drawing( sheet = current_sheet(), dims = "A1", xml, col_offset = 0, row_offset = 0, ... )
Arguments
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
Returns
The wbWorkbook
object
Method add_chart_xml()
Add xml chart
Usage
wbWorkbook$add_chart_xml( sheet = current_sheet(), dims = NULL, xml, col_offset = 0, row_offset = 0, ... )
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
xml
xml
col_offset, row_offset
positioning parameters
...
additional arguments
Returns
The wbWorkbook
object
Method add_mschart()
Add mschart chart to the workbook
Usage
wbWorkbook$add_mschart( sheet = current_sheet(), dims = NULL, graph, col_offset = 0, row_offset = 0, ... )
Arguments
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
Returns
The wbWorkbook
object
Method add_form_control()
Add form control to workbook
Usage
wbWorkbook$add_form_control( sheet = current_sheet(), dims = "A1", type = c("Checkbox", "Radio", "Drop"), text = NULL, link = NULL, range = NULL, checked = FALSE )
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
type
type
text
text
link
link
range
range
checked
checked
Returns
The wbWorkbook
object, invisibly
Method print()
Prints the wbWorkbook
object
Usage
wbWorkbook$print()
Returns
The wbWorkbook
object, invisibly; called for its side-effects
Method protect()
Protect a workbook
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method protect_worksheet()
protect worksheet
Usage
wbWorkbook$protect_worksheet( sheet = current_sheet(), protect = TRUE, password = NULL, properties = NULL )
Arguments
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"
Returns
The wbWorkbook
object
Method get_properties()
Get properties of a workbook
Usage
wbWorkbook$get_properties()
Method set_properties()
Set a property of a workbook
Usage
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 )
Arguments
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
Method add_mips()
add mips string
Usage
wbWorkbook$add_mips(xml = NULL)
Arguments
xml
A mips string added to self$custom
Method get_mips()
get mips string
Usage
wbWorkbook$get_mips(single_xml = TRUE, quiet = TRUE)
Arguments
single_xml
single_xml
quiet
quiet
Method set_creators()
Set creator(s)
Usage
wbWorkbook$set_creators(creators)
Arguments
creators
A character vector of creators to set. Duplicates are ignored.
Method add_creators()
Add creator(s)
Usage
wbWorkbook$add_creators(creators)
Arguments
creators
A character vector of creators to add. Duplicates are ignored.
Method remove_creators()
Remove creator(s)
Usage
wbWorkbook$remove_creators(creators)
Arguments
creators
A character vector of creators to remove. All duplicated are removed.
Method set_last_modified_by()
Change the last modified by
Usage
wbWorkbook$set_last_modified_by(name, ...)
Arguments
name
A new value
...
additional arguments
Returns
The wbWorkbook
object, invisibly
Method set_page_setup()
set_page_setup() this function is intended to supersede page_setup(), but is not yet stable
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method page_setup()
page_setup()
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method set_header_footer()
Sets headers and footers
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method get_tables()
get tables
Usage
wbWorkbook$get_tables(sheet = current_sheet())
Arguments
sheet
The name of the sheet
Returns
The sheet tables. character()
if empty
Method remove_tables()
remove tables
Usage
wbWorkbook$remove_tables(sheet = current_sheet(), table, remove_data = TRUE)
Arguments
sheet
The name of the sheet
table
table
remove_data
removes the data as well
Returns
The wbWorkbook
object
Method add_filter()
add filters
Usage
wbWorkbook$add_filter(sheet = current_sheet(), rows, cols)
Arguments
sheet
The name of the sheet
rows
rows
cols
cols
Returns
The wbWorkbook
object
Method remove_filter()
remove filters
Usage
wbWorkbook$remove_filter(sheet = current_sheet())
Arguments
sheet
The name of the sheet
Returns
The wbWorkbook
object
Method set_grid_lines()
grid lines
Usage
wbWorkbook$set_grid_lines(sheet = current_sheet(), show = FALSE, print = show)
Arguments
sheet
The name of the sheet
show
show
print
print
Returns
The wbWorkbook
object
Method grid_lines()
grid lines
Usage
wbWorkbook$grid_lines(sheet = current_sheet(), show = FALSE, print = show)
Arguments
sheet
The name of the sheet
show
show
print
print
Returns
The wbWorkbook
object
Method add_named_region()
add a named region
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object
Method get_named_regions()
get named regions in a workbook
Usage
wbWorkbook$get_named_regions(tables = FALSE, x = NULL)
Arguments
tables
Return tables as well?
x
Not used.
Returns
A data.frame
of named regions
Method remove_named_region()
remove a named region
Usage
wbWorkbook$remove_named_region(sheet = current_sheet(), name = NULL)
Arguments
sheet
The name of the sheet
name
name
Returns
The wbWorkbook
object
Method set_order()
set worksheet order
Usage
wbWorkbook$set_order(sheets)
Arguments
sheets
sheets
Returns
The wbWorkbook
object
Method get_sheet_visibility()
Get sheet visibility
Usage
wbWorkbook$get_sheet_visibility()
Returns
Returns sheet visibility
Method set_sheet_visibility()
Set sheet visibility
Usage
wbWorkbook$set_sheet_visibility(sheet = current_sheet(), value)
Arguments
sheet
The name of the sheet
value
value
Returns
The wbWorkbook
object
Method add_page_break()
Add a page break
Usage
wbWorkbook$add_page_break(sheet = current_sheet(), row = NULL, col = NULL)
Arguments
sheet
The name of the sheet
row
row
col
col
Returns
The wbWorkbook
object
Method clean_sheet()
clean sheet (remove all values)
Usage
wbWorkbook$clean_sheet( sheet = current_sheet(), dims = NULL, numbers = TRUE, characters = TRUE, styles = TRUE, merged_cells = TRUE, hyperlinks = TRUE )
Arguments
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
Returns
The wbWorksheetObject
, invisibly
Method add_border()
create borders for cell region
Usage
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, update = FALSE, ... )
Arguments
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
update
update
...
additional arguments
Returns
The wbWorkbook
, invisibly
Method add_fill()
provide simple fill function
Usage
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, ... )
Arguments
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
Returns
The wbWorksheetObject
, invisibly
Method add_font()
provide simple font function
Usage
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 = "", update = FALSE, ... )
Arguments
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
update
update
...
additional arguments
Returns
The wbWorkbook
, invisibly
Method add_numfmt()
provide simple number format function
Usage
wbWorkbook$add_numfmt(sheet = current_sheet(), dims = "A1", numfmt)
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
numfmt
number format id or a character of the format
Returns
The wbWorksheetObject
, invisibly
Method add_cell_style()
provide simple cell style format function
Usage
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, ... )
Arguments
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
Returns
The wbWorkbook
object, invisibly
Method get_cell_style()
get sheet style
Usage
wbWorkbook$get_cell_style(sheet = current_sheet(), dims)
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
Returns
a character vector of cell styles
Method set_cell_style()
set sheet style
Usage
wbWorkbook$set_cell_style(sheet = current_sheet(), dims, style)
Arguments
sheet
The name of the sheet
dims
Cell range in a sheet
style
style
Returns
The wbWorksheetObject
, invisibly
Method set_cell_style_across()
set style across columns and/or rows
Usage
wbWorkbook$set_cell_style_across( sheet = current_sheet(), style, cols = NULL, rows = NULL )
Arguments
sheet
sheet
style
style
cols
cols
rows
rows
Returns
The wbWorkbook
object
Method add_named_style()
set sheet style
Usage
wbWorkbook$add_named_style( sheet = current_sheet(), dims = "A1", name = "Normal", font_name = NULL, font_size = NULL )
Arguments
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
Returns
The wbWorkbook
, invisibly
Method add_dxfs_style()
create dxfs style These styles are used with conditional formatting and custom table styles
Usage
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, ... )
Arguments
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()
Returns
The wbWorksheetObject
, invisibly
Method clone_sheet_style()
clone style from one sheet to another
Usage
wbWorkbook$clone_sheet_style(from = current_sheet(), to)
Arguments
from
the worksheet you are cloning
to
the worksheet the style is applied to
Method add_sparklines()
apply sparkline to worksheet
Usage
wbWorkbook$add_sparklines(sheet = current_sheet(), sparklines)
Arguments
sheet
The name of the sheet
sparklines
sparkline created by
create_sparkline()
Method add_ignore_error()
Ignore error on worksheet
Usage
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, ... )
Arguments
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
Method set_sheetview()
add sheetview
Usage
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, ... )
Arguments
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
Returns
The wbWorksheetObject
, invisibly
Method add_person()
add person to workbook
Usage
wbWorkbook$add_person( name = NULL, id = NULL, user_id = NULL, provider_id = "None" )
Arguments
name
name
id
id
user_id
user_id
provider_id
provider_id
Method get_person()
description get person
Usage
wbWorkbook$get_person(name = NULL)
Arguments
name
name
Method get_active_sheet()
description get active sheet
Usage
wbWorkbook$get_active_sheet()
Method set_active_sheet()
description set active sheet
Usage
wbWorkbook$set_active_sheet(sheet = current_sheet())
Arguments
sheet
The name of the sheet
Method get_selected()
description get selected sheets
Usage
wbWorkbook$get_selected()
Method set_selected()
set selected sheet
Usage
wbWorkbook$set_selected(sheet = current_sheet())
Arguments
sheet
The name of the sheet
Method clone()
The objects of this class are cloneable with this method.
Usage
wbWorkbook$clone(deep = FALSE)
Arguments
deep
Whether to make a deep clone.
Modify borders in a cell region of a worksheet
Description
wb wrapper to create borders for cell regions.
Usage
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,
update = FALSE,
...
)
Arguments
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 |
update |
Logical. Defaults to FALSE. If TRUE, and the border style includes NULL entries, existing borders may be updated with new ones. When overlapping cells (e.g., squares intersect), existing borders will be preserved where possible. |
... |
additional arguments |
See Also
Other styles:
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
Examples
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 = wb_color(hex = "FF808080"))
wb$add_worksheet()$
add_border(dims = "B2:D4", bottom_border = "thick", left_border = "thick",
right_border = "thick", top_border = "thick")$
add_border(dims = "C3:E5", update = TRUE)
Modify the style in a cell region
Description
Add cell style to a cell region
Usage
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,
...
)
Arguments
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 |
Value
The wbWorkbook
object, invisibly
See Also
Other styles:
wb_add_border()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
Examples
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
Description
Add a chart XML to a worksheet
Usage
wb_add_chart_xml(
wb,
sheet = current_sheet(),
dims = NULL,
xml,
col_offset = 0,
row_offset = 0,
...
)
Arguments
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 |
See Also
wb_add_drawing()
wb_add_image()
wb_add_mschart()
wb_add_plot()
Add a chartsheet to a workbook
Description
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.
Usage
wb_add_chartsheet(
wb,
sheet = next_sheet(),
tab_color = NULL,
zoom = 100,
visible = c("true", "false", "hidden", "visible", "veryhidden"),
...
)
Arguments
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 |
See Also
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
Description
Add comment to worksheet
Usage
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", ...)
Arguments
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 |
Details
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.
Value
The Workbook object, invisibly.
See Also
Examples
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 in a worksheet
Description
Add conditional formatting to cells.
You can find more details in vignette("conditional-formatting")
.
Usage
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
)
Arguments
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 |
Details
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.
If an expression is pointing to a cell "A1=1"
, this cell reference is fluid and not fixed like "$A$1=1"
. It will behave similar to a formula, when dims
is spanning multiple columns or rows (A1, A2, A3 ... in vertical direction, A1, B1, C1 ... in horizontal direction). If dims
is a non consecutive range ("A1:B2,D1:F2"), the expression is applied to each range. For the second dims
range it will be evaluated again as "A1=1"
.
expression
-
[style]
AStyle
object
[rule]
An Excel expression (as a character). Valid operators are:<
,<=
,>
,>=
,==
,!=
colorScale
-
[style]
Acharacter
vector of valid colors with length2
or3
[rule]
NULL
or acharacter
vector of valid colors of equal length tostyles
dataBar
-
[style]
Acharacter
vector of valid colors with length2
or3
[rule]
Anumeric
vector specifying the range of the databar colors. Must be equal length tostyle
[params$showValue]
IfFALSE
the cell value is hidden. DefaultTRUE
[params$gradient]
IfFALSE
color gradient is removed. DefaultTRUE
[params$border]
IfFALSE
the border around the database is hidden. DefaultTRUE
duplicatedValues
/uniqueValues
/containsErrors
-
[style]
AStyle
object contains
-
[style]
AStyle
object
[rule]
The text to look for within cells between
-
[style]
AStyle
object.
[rule]
Anumeric
vector of length2
specifying lower and upper bound (Inclusive) topN
-
[style]
AStyle
object
[params$rank]
Anumeric
vector of length1
indicating number of highest values. Default5L
[params$percent]
IfTRUE
, uses percentage bottomN
-
[style]
AStyle
object
[params$rank]
Anumeric
vector of length1
indicating number of lowest values. Default5L
[params$percent]
IfTRUE
, uses percentage iconSet
-
[params$showValue]
IfFALSE
, the cell value is hidden. DefaultTRUE
[params$reverse]
IfTRUE
, the order is reversed. DefaultFALSE
[params$percent]
IfTRUE
, 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.
See Also
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()
Examples
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 a worksheet
Description
Add data to worksheet with optional styling.
Usage
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,
...
)
Arguments
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 |
Details
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. Similar
factor labels "_openxlsx_Inf"
, "_openxlsx_nInf"
, and "_openxlsx_NaN"
are reserved.
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. When writing POSIXt, the users local
timezone should not matter. The openxml standard does not have a timezone
and the conversion from the local timezone should happen internally, so that
date and time are converted, but the timezone is dropped. This conversion
could cause a minor precision loss. The datetime in R and in spreadsheets
might differ by 1 second, caused by floating point precision. When read from
the worksheet, starting with openxlsx2
release 1.15
the datetime is
returned in "UTC"
.
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.
Value
A wbWorkbook
, invisibly.
See Also
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()
Examples
## 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 a data table to a worksheet
Description
Add data to a worksheet and format as an Excel table.
Usage
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,
...
)
Arguments
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 |
Details
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. Similar
factor labels "_openxlsx_Inf"
, "_openxlsx_nInf"
, and "_openxlsx_NaN"
are reserved.
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. When writing POSIXt, the users local
timezone should not matter. The openxml standard does not have a timezone
and the conversion from the local timezone should happen internally, so that
date and time are converted, but the timezone is dropped. This conversion
could cause a minor precision loss. The datetime in R and in spreadsheets
might differ by 1 second, caused by floating point precision. When read from
the worksheet, starting with openxlsx2
release 1.15
the datetime is
returned in "UTC"
.
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.
Modify total row argument
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.
See Also
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()
Examples
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"),
stringsAsFactors = FALSE
)
Add data validation to cells in a worksheet
Description
Add Excel data validation to cells
Usage
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,
...
)
Arguments
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 |
Examples
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
Description
Add drawings to a worksheet. This requires the rvg
package.
Usage
wb_add_drawing(
wb,
sheet = current_sheet(),
dims = "A1",
xml,
col_offset = 0,
row_offset = 0,
...
)
Arguments
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 |
See Also
wb_add_chart_xml()
wb_add_image()
wb_add_mschart()
wb_add_plot()
Examples
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)
}
Set a dxfs styling for the workbook
Description
These styles are used with conditional formatting and custom table styles.
Usage
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,
...
)
Arguments
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 |
Value
The Workbook object, invisibly
See Also
Other workbook styling functions:
base_font-wb
,
wb_add_style()
,
wb_base_colors
Examples
wb <- wb_workbook() %>%
wb_add_worksheet() %>%
wb_add_dxfs_style(
name = "nay",
font_color = wb_color(hex = "FF9C0006"),
bg_fill = wb_color(hex = "FFFFC7CE")
)
Modify the background fill color in a cell region
Description
Add fill to a cell region.
Usage
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,
...
)
Arguments
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 |
... |
... |
Value
The wbWorkbook
object, invisibly
See Also
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
Examples
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 font in a cell region
Description
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.
Usage
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 = "",
update = FALSE,
...
)
Arguments
wb |
A Workbook object |
sheet |
the worksheet |
dims |
the cell range |
name |
Font name: default |
color |
A |
size |
Font size: default is |
bold |
Logical, whether the font should be bold. |
italic |
Logical, whether the font should be italic. |
outline |
Logical, whether the font should have an outline. |
strike |
Logical, whether the font should have a strikethrough. |
underline |
underline, "single" or "double", default: "" |
charset |
Character, the character set to be used. The list of valid IDs can be found in the Details section of |
condense |
Logical, whether the font should be condensed. |
extend |
Logical, whether the font should be extended. |
family |
Character, the font family. Default is "2" (modern). "0" (auto), "1" (roman), "2" (swiss), "3" (modern), "4" (script), "5" (decorative). # 6-14 unused |
scheme |
Character, the font scheme. Valid values are "minor", "major", "none". Default is "minor". |
shadow |
Logical, whether the font should have a shadow. |
vert_align |
Character, the vertical alignment of the font. Valid values are "baseline", "superscript", "subscript". |
update |
Logical/Character if logical, all elements are assumed to be selected, whereas if character, only matching elements are updated. This will not alter strings styled with |
... |
... |
Details
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.
Value
A wbWorkbook
, invisibly
See Also
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_named_style()
,
wb_add_numfmt()
,
wb_cell_style
Examples
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"))
# Update the font color
wb$add_font("S1", "A1:K1", color = wb_color("orange"), update = c("color"))
Add a checkbox, radio button or drop menu to a cell in a worksheet
Description
You can add Form Control to a cell. The three supported types are a Checkbox, a Radio button, or a Drop menu.
Usage
wb_add_form_control(
wb,
sheet = current_sheet(),
dims = "A1",
type = c("Checkbox", "Radio", "Drop"),
text = NULL,
link = NULL,
range = NULL,
checked = FALSE
)
Arguments
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 |
Value
The wbWorkbook
object, invisibly.
Examples
wb <- wb_workbook() %>% wb_add_worksheet() %>%
wb_add_form_control()
# Add
wb$add_form_control(dims = "C5", type = "Radio", checked = TRUE)
Add a formula to a cell range in a worksheet
Description
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.
Usage
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,
...
)
Arguments
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 |
Details
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).
Value
The workbook, invisibly.
See Also
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()
Examples
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(1:25, 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_add_hyperlink
Description
Helper to add shared hyperlinks into a worksheet or remove shared hyperlinks from a worksheet
Usage
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)
Arguments
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 |
Details
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.
See Also
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()
Examples
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()
Ignore error types on worksheet
Description
This function allows to hide / ignore certain types of errors shown in a worksheet.
Usage
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,
...
)
Arguments
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 |
Value
The wbWorkbook
object, invisibly.
Insert an image into a worksheet
Description
Insert an image into a worksheet
Usage
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,
...
)
Arguments
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:example@example.com") that will be opened when the image is clicked. |
... |
additional arguments |
See Also
wb_add_chart_xml()
wb_add_drawing()
wb_add_mschart()
wb_add_plot()
Examples
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")
wb get and apply MIP section
Description
Read sensitivity labels from files and apply them to workbooks
Usage
wb_add_mips(wb, xml = NULL)
wb_get_mips(wb, single_xml = TRUE, quiet = TRUE)
Arguments
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. |
Details
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.
Value
the workbook invisible (wb_add_mips()
) or the xml string (wb_get_mips()
)
Add mschart object to a worksheet
Description
Add mschart object to a worksheet
Usage
wb_add_mschart(
wb,
sheet = current_sheet(),
dims = NULL,
graph,
col_offset = 0,
row_offset = 0,
...
)
Arguments
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 |
See Also
wb_data()
wb_add_chart_xml()
wb_add_image wb_add_mschart()
wb_add_plot
Examples
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)
}
Apply styling to a cell region with a named style
Description
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".
Usage
wb_add_named_style(
wb,
sheet = current_sheet(),
dims = "A1",
name = "Normal",
font_name = NULL,
font_size = NULL
)
Arguments
wb |
A |
sheet |
A worksheet |
dims |
A cell range |
name |
The named style name. Builtin styles are |
font_name , font_size |
optional else the default of the theme |
Value
The wbWorkbook
, invisibly
See Also
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_numfmt()
,
wb_cell_style
Examples
wb <- wb_workbook()$add_worksheet()
name <- "Normal"
dims <- "A1"
wb$add_data(dims = dims, x = name)
name <- "Bad"
dims <- "B1"
wb$add_named_style(dims = dims, name = name)
wb$add_data(dims = dims, x = name)
name <- "Good"
dims <- "C1"
wb$add_named_style(dims = dims, name = name)
wb$add_data(dims = dims, x = name)
Modify number formatting in a cell region
Description
Add number formatting to a cell region. You can use a number format created
by create_numfmt()
.
Usage
wb_add_numfmt(wb, sheet = current_sheet(), dims = "A1", numfmt)
Arguments
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 |
Details
The list of number formats ID is located in the Details section of create_cell_style()
.
General Number Formatting
-
"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
).
Currency Formatting
-
"$#,##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.
Percentage Formatting
-
"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%
).
Scientific Formatting
-
"0.00E+00"
: Scientific notation with two decimal places (e.g.,1.23E+03
for1230
).
Date and Time Formatting
-
"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
for1:30:15 PM
). -
"yyyy-mm-dd h:mm:ss"
: Full date and time format.
Fraction Formatting
-
"# ?/?"
: 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
).
Custom Formatting
-
"_($* #,##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).
Formatting Symbols Reference
-
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.
Value
The wbWorkbook
object, invisibly.
See Also
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_cell_style
Examples
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)
Add a page break to a worksheet
Description
Insert page breaks into a worksheet
Usage
wb_add_page_break(wb, sheet = current_sheet(), row = NULL, col = NULL)
Arguments
wb |
A workbook object |
sheet |
A name or index of a worksheet |
row , col |
Either a row number of column number. One must be |
See Also
Examples
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
Add a pivot table to a worksheet
Description
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.
Usage
wb_add_pivot_table(
wb,
x,
sheet = next_sheet(),
dims = "A3",
filter,
rows,
cols,
data,
fun,
params,
pivot_table,
slicer,
timeline
)
Arguments
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 |
Details
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 theesoph
dataset.sort_item: named list of index or character vectors
See Also
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()
Examples
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"))
)
Insert the current plot into a worksheet
Description
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()
.
Usage
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,
...
)
Arguments
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 |
See Also
wb_add_chart_xml()
wb_add_drawing()
wb_add_image()
wb_add_mschart()
Examples
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 pivot table
Description
Add a slicer/timeline to a previously created pivot table. This function is still experimental and might be changed/improved in upcoming releases.
Usage
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())
Arguments
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. |
Details
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 theesoph
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.
See Also
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()
Examples
# 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],
stringsAsFactors = FALSE
)
# 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
Description
Add sparklines to a worksheet
Usage
wb_add_sparklines(wb, sheet = current_sheet(), sparklines)
Arguments
wb |
A |
sheet |
sheet to add the sparklines to |
sparklines |
sparklines object created with |
See Also
Examples
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)
Set the default style in a workbook
Description
wb wrapper to add style to workbook
Usage
wb_add_style(wb, style = NULL, style_name = NULL)
Arguments
wb |
A workbook |
style |
style xml character, created by a |
style_name |
style name used optional argument |
Value
The wbWorkbook
object, invisibly.
See Also
Other workbook styling functions:
base_font-wb
,
wb_add_dxfs_style()
,
wb_base_colors
Examples
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)
Add threaded comments to a cell in a worksheet
Description
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()
.
Usage
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)
Arguments
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 |
Details
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()
See Also
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()
Examples
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 workbook
Description
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.
Usage
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)),
...
)
Arguments
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 |
Details
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
Value
The wbWorkbook
object, invisibly.
See Also
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()
Examples
## 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)
Set the default colors in a workbook
Description
Modify / get the default colors of the workbook.
Usage
wb_set_base_colors(wb, theme = "Office", ...)
wb_get_base_colors(wb, xml = FALSE, plot = TRUE)
Arguments
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 |
Details
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"
See Also
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()
Examples
wb <- wb_workbook()
wb$get_base_colors()
wb$set_base_colors(theme = 3)
wb$set_base_colors(theme = "Violet II")
wb$get_base_colours()
Apply styling to a cell region
Description
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.
Usage
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
)
Arguments
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 |
Value
A named vector with cell style index positions
See Also
Other styles:
wb_add_border()
,
wb_add_cell_style()
,
wb_add_fill()
,
wb_add_font()
,
wb_add_named_style()
,
wb_add_numfmt()
Examples
# 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 all values in a worksheet
Description
Remove content of a worksheet completely, or a region if specifying dims
.
Usage
wb_clean_sheet(
wb,
sheet = current_sheet(),
dims = NULL,
numbers = TRUE,
characters = TRUE,
styles = TRUE,
merged_cells = TRUE,
hyperlinks = TRUE
)
Arguments
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 |
Value
A Workbook object
Apply styling from a sheet to another within a workbook
Description
This function can be used to apply styling from a cell range, and apply it to another cell range.
Usage
wb_clone_sheet_style(wb, from = current_sheet(), to)
Arguments
wb |
A workbook |
from |
sheet we select the style from |
to |
sheet to apply the style to |
Create copies of a worksheet within a workbook
Description
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.
Usage
wb_clone_worksheet(wb, old = current_sheet(), new = next_sheet(), from = NULL)
Arguments
wb |
A |
old |
Name of existing worksheet to copy |
new |
Name of the new worksheet to create |
from |
(optional) Workbook to clone old from |
Value
The wbWorkbook
object, invisibly.
See Also
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()
Examples
# 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)
Helper to create a color
Description
Creates a wbColour
object.
Usage
wb_color(
name = NULL,
auto = NULL,
indexed = NULL,
hex = NULL,
theme = NULL,
tint = NULL,
format = c("ARGB", "RGBA")
)
Arguments
name |
A name of a color known to R either as name or RGB/ARGB/RGBA value. |
auto |
A boolean. |
indexed |
An indexed color value. This color has to be provided by the workbook. |
hex |
A rgb color a RGB/ARGB/RGBA 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). |
format |
A colour format, one of ARGB (default) or RGBA. |
Details
The format of the hex color representation can be either RGB, ARGB, or RGBA.
These hex formats differ only in a way how they encode the transparency value alpha,
ARGB expecting the alpha value before the RGB values (default in spreadsheets),
RGBA expects the alpha value after the RGB values (default in R),
and RGB is not encoding transparency at all.
If the colors some from functions such as adjustcolor
that provide color in the
RGBA format, it is necessary to specify the format = "RGBA"
when calling the
wb_color()
function.
Value
a wbColour
object
See Also
wb_get_base_colors()
grDevices::colors()
Helper to create a comment object
Description
Creates a wbComment
object. Use with wb_add_comment()
to add to a worksheet location.
Usage
wb_comment(
text = NULL,
style = NULL,
visible = FALSE,
author = getOption("openxlsx2.creator"),
width = 2,
height = 4
)
Arguments
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 |
Value
A wbComment
object
Examples
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
Description
Copy cells around within a worksheet
Usage
wb_copy_cells(
wb,
sheet = current_sheet(),
dims = "A1",
data,
as_value = FALSE,
as_ref = FALSE,
transpose = FALSE,
...
)
Arguments
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 |
Value
the wbWorkbook
invisibly
See Also
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()
Examples
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")
Add the wb_data
attribute to a data frame in a worksheet
Description
provide wb_data object as mschart input
Usage
wb_data(wb, sheet = current_sheet(), dims, ...)
## S3 method for class 'wb_data'
x[
i,
j,
drop = !((missing(j) && length(i) > 1) || (!missing(i) && length(j) > 1))
]
Arguments
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 |
Value
A data frame of class wb_data
.
See Also
wb_to_df()
wb_add_mschart()
, wb_add_pivot_table()
Examples
wb <- wb_workbook() %>%
wb_add_worksheet() %>%
wb_add_data(x = mtcars, dims = "B2")
wb_data(wb, 1, dims = "B2:E6")
Helper to specify the dims
argument
Description
wb_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.
Usage
wb_dims(..., select = NULL)
Arguments
... |
construct |
select |
A string, one of the followings.
it improves the selection of various parts of |
Details
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 amatrix
or adata.frame
, but a vector is also accepted.) -
from_row
/from_col
/from_dims
the starting position ofx
(Thedims
returned will assume that the top left corner ofx
is atfrom_row / from_col
-
rows
Optional Which row span inx
should this apply to. Ifrows
= 0, only column names will be affected. -
cols
a range of columns id inx
, or one of the column names ofx
(length 1 only accepted for column names ofx
.) -
row_names
A logical, this is to letwb_dims()
know thatx
has row names or not. Ifrow_names = TRUE
,wb_dims()
will incrementfrom_col
by 1. -
col_names
wb_dims()
assumes that ifx
has column names, then trying to find thedims
.
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
While it is possible to construct dimensions from decreasing rows and columns, the output will always order the rows top to bottom. So
wb_dims(rows = 3:1, cols = 3:1)
will not result in "C3:A1"
and if passed to functions, it will return the same as "C1:A3"
.
Value
A dims
string
Using wb_dims()
without an x
object
-
rows
/cols
(if you want to specify a single one, usefrom_row
/from_col
) -
from_row
/from_col
the starting position of thedims
(similar tostart_row
/start_col
, but with a clearer name.)
Using wb_dims()
with an x
object
wb_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 nameswb_dims(x = mtcars, select = "col_names")
provide the
dims
of row nameswb_dims(x = mtcars, row_names = TRUE, select = "row_names")
provide the
dims
of a row spanwb_dims(x = mtcars, rows = 1:10)
selects the first 10 data rows ofmtcars
(ignoring column names)provide the
dims
of the data in a column spanwb_dims(x = mtcars, cols = 1:5)
select the data first 5 columns ofmtcars
provide a column span (including column names)
wb_dims(x = mtcars, cols = 4:7, select = "x")
select the data columns 4, 5, 6, 7 ofmtcars
+ column namesprovide 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.
Examples
# 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)
Freeze pane of a worksheet
Description
Add a Freeze pane in a worksheet.
Usage
wb_freeze_pane(
wb,
sheet = current_sheet(),
first_active_row = NULL,
first_active_col = NULL,
first_row = FALSE,
first_col = FALSE,
...
)
Arguments
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 |
See Also
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()
Examples
## Create a new workbook
wb <- wb_workbook("Kenshin")
## Add some worksheets
wb$add_worksheet("Sheet 1")
wb$add_worksheet("Sheet 2")
wb$add_worksheet("Sheet 3")
wb$add_worksheet("Sheet 4")
## Freeze Panes
wb$freeze_pane("Sheet 1", 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
Description
List Excel tables in a worksheet
Usage
wb_get_tables(wb, sheet = current_sheet())
Arguments
wb |
A workbook object |
sheet |
A name or index of a worksheet |
Value
A character vector of table names on the specified sheet
Examples
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")
Load an existing .xlsx, .xlsm or .xlsb file
Description
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.
Usage
wb_load(file, sheet, data_only = FALSE, ...)
Arguments
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 |
Details
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.
Value
A Workbook object.
Examples
## load existing workbook
fl <- system.file("extdata", "openxlsx2_example.xlsx", package = "openxlsx2")
wb <- wb_load(file = fl)
Merge cells within a worksheet
Description
Worksheet cell merging
Usage
wb_merge_cells(
wb,
sheet = current_sheet(),
dims = NULL,
solve = FALSE,
direction = NULL,
...
)
wb_unmerge_cells(wb, sheet = current_sheet(), dims = NULL, ...)
Arguments
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
dims |
worksheet cells |
solve |
logical if intersecting merges should be solved |
direction |
direction in which to split the cell merging. Allows "row" or "col" |
... |
additional arguments |
Details
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.
See Also
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()
Examples
# 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)
Preview a workbook in a spreadsheet software
Description
You can also use the shorter wb$open()
as a replacement.
To open xlsx files, see xl_open()
.
Usage
wb_open(wb, flush = FALSE)
Arguments
wb |
a wbWorkbook object |
flush |
if the flush option should be used |
Order worksheets in a workbook
Description
Get/set order of worksheets in a Workbook object
Usage
wb_get_order(wb)
wb_set_order(wb, sheets)
Arguments
wb |
A |
sheets |
Sheet order |
Details
This function does not reorder the worksheets within the workbook object, it simply shuffles the order when writing to file.
Examples
## 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 of a worksheet
Description
Set page margins, orientation and print scaling.
Usage
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,
...
)
Arguments
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 |
Details
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) |
Examples
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 a workbook from modifications
Description
Protect or unprotect a workbook from modifications by the user in the graphical user interface. Replaces an existing protection.
Usage
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,
...
)
Arguments
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 |
Details
Lock types:
-
1
xlsx with password (default) -
2
xlsx recommends read-only -
4
xlsx enforces read-only -
8
xlsx is locked for annotation
Examples
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 a worksheet from modifications
Description
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.
Usage
wb_protect_worksheet(
wb,
sheet = current_sheet(),
protect = TRUE,
password = NULL,
properties = NULL
)
Arguments
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: |
Examples
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 a data table from a worksheet
Description
Remove Excel tables in a workbook using its name.
Usage
wb_remove_tables(wb, sheet = current_sheet(), table, remove_data = TRUE)
Arguments
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
table |
Name of table to remove. Use |
remove_data |
Default |
Value
The wbWorkbook
, invisibly
Examples
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
Description
Remove a worksheet from a workbook
Usage
wb_remove_worksheet(wb, sheet = current_sheet())
Arguments
wb |
A wbWorkbook object |
sheet |
The sheet name or index to remove |
Value
The wbWorkbook
object, invisibly.
Examples
## 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
Description
Save a workbook to file
Usage
wb_save(wb, file = NULL, overwrite = TRUE, path = NULL, flush = FALSE)
Arguments
wb |
A |
file |
A path to save the workbook to |
overwrite |
If |
path |
Deprecated argument. Please use |
flush |
Experimental, streams the worksheet file to disk |
Details
When saving a wbWorkbook
to a file, memory usage may spike
depending on the worksheet size. This happens because the entire XML
structure is created in memory before writing to disk. The memory
required depends on worksheet size, as XML files consist of character
data and include additional overhead for validity checks.
The flush
argument streams worksheet XML data directly to disk,
avoiding the need to build the full XML tree in memory. This reduces
memory usage but skips some XML validity checks. It also bypasses
the pugixml
functions that openxlsx2
uses, omitting certain
preliminary sanity checks before writing. As the name suggests,
the output is simply flushed to disk.
Value
the wbWorkbook
object, invisibly
See Also
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()
Examples
## Create a new workbook and add a worksheet
wb <- wb_workbook("Creator of workbook")
wb$add_worksheet(sheet = "My first worksheet")
## Save workbook to working directory
wb_save(wb, file = temp_xlsx(), overwrite = TRUE)
Get and Set the workbook position, size and filter
Description
Get and Set the workbook position, size and filter
Usage
wb_get_bookview(wb)
wb_remove_bookview(wb, view = 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,
view = 1L,
...
)
Arguments
wb |
A wbWorkbook object |
view |
Which view to modify. Default is |
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 |
Value
A data frame with the bookview properties
The Workbook object
The Workbook object
Examples
wb <- wb_workbook() %>% wb_add_worksheet()
# set the first and second bookview (horizontal split)
wb <- wb %>%
wb_set_bookview(
window_height = 17600, window_width = 15120,
x_window = 15120, y_window = 760) %>%
wb_set_bookview(
window_height = 17600, window_width = 15040,
x_window = 0, y_window = 760, view = 2
)
wb %>% wb_get_bookview()
# remove the first view
wb %>% wb_remove_bookview(view = 1) %>% wb_get_bookview()
# keep only the first view
wb %>% wb_remove_bookview(view = -1) %>% wb_get_bookview()
Modify grid lines visibility in a worksheet
Description
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)
Usage
wb_set_grid_lines(wb, sheet = current_sheet(), show = FALSE, print = show)
wb_grid_lines(wb, sheet = current_sheet(), show = FALSE, print = show)
Arguments
wb |
A workbook object |
sheet |
A name or index of a worksheet |
show |
A logical. If |
print |
A logical. If |
Examples
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)
Set headers and footers of a worksheet
Description
Set document headers and footers. You can also do this when adding a worksheet
with wb_add_worksheet()
with the header
, footer
arguments and friends.
These will show up when printing an xlsx file.
Usage
wb_set_header_footer(
wb,
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,
...
)
Arguments
wb |
A Workbook object |
sheet |
A name or index of a worksheet |
header , even_header , first_header , footer , even_footer , first_footer |
Character vector of length 3 corresponding to positions left, center,
right. |
align_with_margins |
Align header/footer with margins |
scale_with_doc |
Scale header/footer with document |
... |
additional arguments |
Details
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
Examples
wb <- wb_workbook()
# Add example data
wb$add_worksheet("S1")$add_data(x = 1:400)
wb$add_worksheet("S2")$add_data(x = 1:400)
wb$add_worksheet("S3")$add_data(x = 3:400)
wb$add_worksheet("S4")$add_data(x = 3:400)
wb$set_header_footer(
sheet = "S1",
header = c("ODD HEAD LEFT", "ODD HEAD CENTER", "ODD HEAD RIGHT"),
footer = c("ODD FOOT RIGHT", "ODD FOOT CENTER", "ODD FOOT RIGHT"),
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$set_header_footer(
sheet = 2,
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$set_header_footer(
sheet = 3,
header = c("ALL HEAD LEFT 2", "ALL HEAD CENTER 2", "ALL HEAD RIGHT 2"),
footer = c("ALL FOOT RIGHT 2", "ALL FOOT CENTER 2", "ALL FOOT RIGHT 2")
)
wb$set_header_footer(
sheet = 4,
first_header = c("FIRST ONLY L", NA, "FIRST ONLY R"),
first_footer = c("FIRST ONLY L", NA, "FIRST ONLY R")
)
# ---- Updating the header ----
## Variant a
## this will keep the odd and even header / footer from the original header /
## footerkeep the first header / footer and will set the first page header /
## footer and will use the original header / footer for the missing element
wb$set_header_footer(
header = NA,
footer = NA,
even_header = NA,
even_footer = NA,
first_header = c("FIRST ONLY L", NA, "FIRST ONLY R"),
first_footer = c("FIRST ONLY L", NA, "FIRST ONLY R")
)
## Variant b
## this will keep the first header / footer only and will use the missing
## element from the original header / footer
wb$set_header_footer(
first_header = c("FIRST ONLY L", NA, "FIRST ONLY R"),
first_footer = c("FIRST ONLY L", NA, "FIRST ONLY R")
)
Modify author in the metadata of a workbook
Description
Just a wrapper of wb$set_last_modified_by()
Usage
wb_set_last_modified_by(wb, name, ...)
Arguments
wb |
A workbook object |
name |
A string object with the name of the LastModifiedBy-User |
... |
additional arguments |
See Also
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()
Examples
wb <- wb_workbook()
wb_set_last_modified_by(wb, "test")
Modify the default view of a worksheet
Description
This helps set a worksheet's appearance, such as the zoom, whether to show grid lines
Usage
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,
...
)
Arguments
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 |
Value
The wbWorkbook
object, invisibly
Examples
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
)
Create a data frame from a Workbook
Description
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.
Usage
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,
...
)
Arguments
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 |
Details
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.
Before release 1.15, datetime variables (in 'yyyy-mm-dd hh:mm:ss' format)
were imported using the user's local system timezone (Sys.timezone()
).
This behavior has been updated. Now, all datetime variables are imported
with the timezone set to "UTC".
If automatic date detection and conversion are enabled but the conversion
is unsuccessful (for instance, in a column containing a mix of data types
like strings, numbers, and dates) dates might be displayed as a Unix
timestamp. Usually they are converted to character for character columns.
If date detection is disabled, dates will show up as a spreadsheet date
format. To convert these, you can use the functions convert_date()
,
convert_datetime()
, or convert_hms()
. If types are specified, date
detection is disabled.
See Also
wb_get_named_regions()
, openxlsx2
Examples
###########################################################################
# 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 a data table position in a worksheet
Description
Update the position of a data table, possibly written using wb_add_data_table()
Usage
wb_update_table(wb, sheet = current_sheet(), dims = "A1", tabname)
Arguments
wb |
A workbook |
sheet |
A worksheet |
dims |
Cell range used for new data table. |
tabname |
A table name |
Details
Be aware that this function does not alter any filter. Excluding or adding rows does not make rows appear nor will it hide them.
Examples
wb <- wb_workbook()$add_worksheet()$add_data_table(x = mtcars)
wb$update_table(tabname = "Table1", dims = "A1:J4")
Create a new Workbook object
Description
Initialize a wbWorkbook object. You can set workbook properties as well.
Usage
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,
...
)
Arguments
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 |
Details
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"
Value
A wbWorkbook
object
See Also
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()
Examples
## Create a new workbook
wb <- wb_workbook()
## Set Workbook properties
wb <- wb_workbook(
creator = "Me",
title = "Expense Report",
subject = "Expense Report - 2022 Q1",
category = "sales"
)
Write an object to a worksheet
Description
Use wb_add_data()
or write_xlsx()
in new code.
Usage
write_data(
wb,
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,
sep = ", ",
name = NULL,
apply_cell_style = TRUE,
remove_cell_style = FALSE,
na.strings = na_strings(),
inline_strings = TRUE,
enforce = FALSE,
...
)
Arguments
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 |
sep |
Only applies to list columns. The separator used to collapse list
columns to a character vector e.g. |
name |
The name of a named region if specified. |
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 |
Value
invisible(0)
Write to a worksheet as an Excel table
Description
Write to a worksheet and format as an Excel table. Use wb_add_data_table()
in new code.
This function is deprecated and may not be exported in the future.
Usage
write_datatable(
wb,
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,
...
)
Arguments
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 |
Details
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. Similar
factor labels "_openxlsx_Inf"
, "_openxlsx_nInf"
, and "_openxlsx_NaN"
are reserved.
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. When writing POSIXt, the users local
timezone should not matter. The openxml standard does not have a timezone
and the conversion from the local timezone should happen internally, so that
date and time are converted, but the timezone is dropped. This conversion
could cause a minor precision loss. The datetime in R and in spreadsheets
might differ by 1 second, caused by floating point precision. When read from
the worksheet, starting with openxlsx2
release 1.15
the datetime is
returned in "UTC"
.
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.
Write a character vector as an Excel Formula
Description
Write a a character vector containing Excel formula to a worksheet.
Use wb_add_formula()
or add_formula()
in new code. This function is
deprecated and may be defunct.
Usage
write_formula(
wb,
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,
...
)
Arguments
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 |
... |
additional arguments |
Write data to an xlsx file
Description
Write a data frame or list of data frames to an xlsx file.
Usage
write_xlsx(x, file, as_table = FALSE, ...)
Arguments
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
|
Details
columns of x
with class Date
or POSIXt
are automatically
styled as dates and datetimes respectively.
Value
A workbook object
Examples
## 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)))
# set base font color to automatic so LibreOffice dark mode works as expected
write_xlsx(l, temp_xlsx(), font_color = wb_color(auto = TRUE))
Open an xlsx file or a wbWorkbook
object
Description
This 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
), Calligra
Sheets (calligrasheets
) and ONLYOFFICE (onlyoffice-desktopeditors
).
Usage
xl_open(x, interactive = NA, flush = FALSE)
## S3 method for class 'wbWorkbook'
xl_open(x, interactive = NA, flush = FALSE)
## Default S3 method:
xl_open(x, interactive = NA, flush = FALSE)
Arguments
x |
A path to the Excel (xls/xlsx) file or wbWorkbook object. |
interactive |
If |
flush |
If |
Examples
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
Description
append xml child to node
Usage
xml_add_child(xml_node, xml_child, level, pointer = FALSE, ...)
Arguments
xml_node |
xml_node |
xml_child |
xml_child |
level |
optional level, if missing the first child is picked |
pointer |
pointer |
... |
additional arguments passed to |
Examples
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"))
adds or updates attribute(s) in existing xml node
Description
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.
Usage
xml_attr_mod(
xml_content,
xml_attributes,
escapes = FALSE,
declaration = FALSE,
remove_empty_attr = TRUE
)
Arguments
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 |
Details
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.
Examples
# 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)
create xml_node from R objects
Description
takes xml_name, xml_children and xml_attributes to create a new xml_node.
Usage
xml_node_create(
xml_name,
xml_children = NULL,
xml_attributes = NULL,
escapes = FALSE,
declaration = FALSE
)
Arguments
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 |
Details
if xml_children or xml_attributes should be empty, use NULL
Examples
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
Description
remove xml child to node
Usage
xml_rm_child(xml_node, xml_child, level, which = 0, pointer = FALSE, ...)
Arguments
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 |
Examples
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"))