| wbWorkbook {openxlsx2} | R Documentation |
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_namesThe names of the sheets
calcChaincalcChain
chartscharts
is_chartsheetA logical vector identifying if a sheet is a chartsheet.
customXmlcustomXml
connectionsconnections
ctrlPropsctrlProps
Content_TypesContent_Types
appapp
coreThe XML core
customcustom
drawingsdrawings
drawings_relsdrawings_rels
docMetadatadoc_meta_data
embeddingsembeddings
externalLinksexternalLinks
externalLinksRelsexternalLinksRels
headFootThe header and footer
mediamedia
metadatacontains cell/value metadata imported on load from xl/metadata.xml
personsPersons of the workbook. to be used with
wb_add_thread()pivotTablespivotTables
pivotTables.xml.relspivotTables.xml.rels
pivotDefinitionspivotDefinitions
pivotRecordspivotRecords
pivotDefinitionsRelspivotDefinitionsRels
queryTablesqueryTables
richDatarichData
slicersslicers
slicerCachesslicerCaches
sharedStringssharedStrings
styles_mgrstyles_mgr
tablestables
tables.xml.relstables.xml.rels
themetheme
vbaProjectvbaProject
vmlvml
vml_relsvml_rels
commentsComments (notes) present in the workbook.
threadCommentsThreaded comments
timelinestimelines
timelineCachestimelineCaches
workbookworkbook
workbook.xml.relsworkbook.xml.rels
worksheetsworksheets
worksheets_relsworksheets_rels
sheetOrderThe sheet order. Controls ordering for worksheets and worksheet names.
pathpath
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(), theme = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, ... )
Arguments
creatorcharacter vector of creators. Duplicated are ignored.
title, subject, category, keywords, comments, manager, companyworkbook properties
datetime_createdThe 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.themeOptional 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
fieldA valid field name
valueA 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
valueA value for
self$workbook$sheets
Method validate_sheet()
validate sheet
Usage
wbWorkbook$validate_sheet(sheet)
Arguments
sheetA 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
sheetThe name of the sheet
tab_colortab_color
zoomzoom
visiblevisible
...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
sheetThe name of the sheet
grid_linesgridLines
row_col_headersrowColHeaders
tab_colortabColor
zoomzoom
headerheader
footerfooter
odd_headeroddHeader
odd_footeroddFooter
even_headerevenHeader
even_footerevenFooter
first_headerfirstHeader
first_footerfirstFooter
visiblevisible
has_drawinghasDrawing
paper_sizepaperSize
orientationorientation
hdpihdpi
vdpivdpi
...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
oldname of worksheet to clone
newname of new worksheet to add
fromname 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
sheetThe name of the sheet
xx
dimsCell range in a sheet
start_colstartCol
start_rowstartRow
arrayarray
col_namescolNames
row_namesrowNames
with_filterwithFilter
namename
sepsep
apply_cell_styleapplyCellStyle
remove_cell_styleif writing into existing cells, should the cell style be removed?
na.stringsValue used for replacing
NAvalues fromx. Defaultna_strings()uses the special#N/Avalue within the workbook.inline_stringswrite characters as inline strings
enforceenforce that selected dims is filled. For this to work,
dimsmust matchx...additional arguments
returnThe
wbWorkbookobject
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
sheetThe name of the sheet
xx
dimsCell range in a sheet
start_colstartCol
start_rowstartRow
col_namescolNames
row_namesrowNames
table_styletableStyle
table_nametableName
with_filterwithFilter
sepsep
first_columnfirstColumn
last_columnlastColumn
banded_rowsbandedRows
banded_colsbandedCols
apply_cell_styleapplyCellStyle
remove_cell_styleif writing into existing cells, should the cell style be removed?
na.stringsValue used for replacing
NAvalues fromx. Defaultna_strings()uses the special#N/Avalue within the workbook.inline_stringswrite characters as inline strings
total_rowwrite 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
xa wb_data object
sheetThe name of the sheet
dimsthe worksheet cell where the pivot table is placed
filtera character object with names used to filter
rowsa character object with names used as rows
colsa character object with names used as cols
dataa character object with names used as data
funa character object of functions to be used with the data
paramsa list of parameters to modify pivot table creation
pivot_tablea character object with a name for the pivot table
slicera character object with names used as slicer
timelinea 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
xa wb_data object
dimsthe worksheet cell where the pivot table is placed
sheetThe name of the sheet
pivot_tablethe name of a pivot table on the selected sheet
slicera variable used as slicer for the pivot table
paramsa 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
sheetThe 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
xa wb_data object
dimsthe worksheet cell where the pivot table is placed
sheetThe name of the sheet
pivot_tablethe name of a pivot table on the selected sheet
timelinea variable used as timeline for the pivot table
paramsa 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
sheetThe 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, ... )
Arguments
sheetThe name of the sheet
xx
dimsCell range in a sheet
start_colstartCol
start_rowstartRow
arrayarray
cmcm
apply_cell_styleapplyCellStyle
remove_cell_styleif writing into existing cells, should the cell style be removed?
enforceenforce dims
...additional arguments
Returns
The wbWorkbook object
Method add_style()
add style
Usage
wbWorkbook$add_style(style = NULL, style_name = NULL)
Arguments
stylestyle
style_namestyle_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, ... )
Arguments
sheetEither sheet name or index. When missing the first sheet in the workbook is selected.
start_rowfirst row to begin looking for data.
start_colfirst column to begin looking for data.
row_namesIf TRUE, the first col of data will be used as row names.
col_namesIf TRUE, the first row of data will be used as column names.
skip_empty_rowsIf TRUE, empty rows are skipped.
skip_empty_colsIf TRUE, empty columns are skipped.
skip_hidden_rowsIf TRUE, hidden rows are skipped.
skip_hidden_colsIf TRUE, hidden columns are skipped.
rowsA numeric vector specifying which rows in the Excel file to read. If NULL, all rows are read.
colsA numeric vector specifying which columns in the Excel file to read. If NULL, all columns are read.
detect_datesIf TRUE, attempt to recognize dates and perform conversion.
na.stringsA character vector of strings which are to be interpreted as NA. Blank cells will be returned as NA.
na.numbersA numeric vector of digits which are to be interpreted as NA. Blank cells will be returned as NA.
fill_merged_cellsIf TRUE, the value in a merged cell is given to all cells within the merge.
dimsCharacter string of type "A1:B2" as optional dimensions to be imported.
show_formulaIf TRUE, the underlying Excel formulas are shown.
convertIf TRUE, a conversion to dates and numerics is attempted.
typesA 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_regionCharacter string with a named_region (defined name or table). If no sheet is selected, the first appearance will be selected.
keep_attributesIf TRUE additional attributes are returned. (These are used internally to define a cell type.)
check_namesIf TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names.
...additional arguments
Returns
a data frame
Method load()
load workbook
Usage
wbWorkbook$load(file, sheet, data_only = FALSE, ...)
Arguments
filefile
sheetThe name of the sheet
data_onlydata_only
...additional arguments
Returns
The wbWorkbook object invisibly
Method save()
Save the workbook
Usage
wbWorkbook$save(file = self$path, overwrite = TRUE, path = NULL)
Arguments
fileThe path to save the workbook to
overwriteIf
FALSE, will not overwrite whenpathexistspathDeprecated argument previously used for file. Please use file in new code.
Returns
The wbWorkbook object invisibly
Method open()
open wbWorkbook in Excel.
Usage
wbWorkbook$open(interactive = NA)
Arguments
interactiveIf
FALSEwill throw a warning and not open the path. This can be manually set toTRUE, otherwise whenNA(default) uses the value returned frombase::interactive()
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
sheetThe name of the sheet
colNamescolNames
refref
showColNamesshowColNames
tableStyletableStyle
tableNametableName
withFilterwithFilter
totalsRowCounttotalsRowCount
totalLabeltotalLabel
showFirstColumnshowFirstColumn
showLastColumnshowLastColumn
showRowStripesshowRowStripes
showColumnStripesshowColumnStripes
Returns
The wbWorksheet object, invisibly
Method update_table()
update a data_table
Usage
wbWorkbook$update_table(sheet = current_sheet(), dims = "A1", tabname)
Arguments
sheetThe name of the sheet
dimsCell range in a sheet
tabnamea 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
sheetThe name of the sheet
dimsCell range in a sheet
dataa wb_data object
as_valueshould a copy of the value be written
as_refshould references to the cell be written
transposeshould 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_sizefontSize
font_colorfont_color
font_namefont_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
xmlxml
plotplot
Method get_base_colours()
Get the base colour
Usage
wbWorkbook$get_base_colours(xml = FALSE, plot = TRUE)
Arguments
xmlxml
plotplot
Method set_base_colors()
Set the base color
Usage
wbWorkbook$set_base_colors(theme = "Office", ...)
Arguments
themetheme
......
Returns
The wbWorkbook object
Method set_base_colours()
Set the base colour
Usage
wbWorkbook$set_base_colours(theme = "Office", ...)
Arguments
themetheme
......
Returns
The wbWorkbook object
Method set_bookview()
Set the book views
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, ... )
Arguments
active_tabactiveTab
auto_filter_date_groupingautoFilterDateGrouping
first_sheetfirstSheet
minimizedminimized
show_horizontal_scrollshowHorizontalScroll
show_sheet_tabsshowSheetTabs
show_vertical_scrollshowVerticalScroll
tab_ratiotabRatio
visibilityvisibility
window_heightwindowHeight
window_widthwindowWidth
x_windowxWindow
y_windowyWindow
...additional arguments
Returns
The wbWorkbook object
Method get_sheet_names()
Get sheet names
Usage
wbWorkbook$get_sheet_names(escape = FALSE)
Arguments
escapeLogical 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
oldOld sheet name
newNew 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
sheetThe name of the sheet
rowsrows
heightsheights
hiddenhidden
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
sheetThe name of the sheet
rowsrows
Returns
The wbWorkbook object, invisibly
Method createCols()
creates column object for worksheet
Usage
wbWorkbook$createCols(sheet = current_sheet(), n, beg, end)
Arguments
sheetThe name of the sheet
nn
begbeg
endend
Method group_cols()
Group cols
Usage
wbWorkbook$group_cols( sheet = current_sheet(), cols, collapsed = FALSE, levels = NULL )
Arguments
sheetThe name of the sheet
colscols
collapsedcollapsed
levelslevels
Returns
The wbWorkbook object, invisibly
Method ungroup_cols()
ungroup cols
Usage
wbWorkbook$ungroup_cols(sheet = current_sheet(), cols)
Arguments
sheetThe name of the sheet
colscolumns
Returns
The wbWorkbook object
Method remove_col_widths()
Remove row heights from a worksheet
Usage
wbWorkbook$remove_col_widths(sheet = current_sheet(), cols)
Arguments
sheetA name or index of a worksheet
colsIndices 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
sheetThe name of the sheet
colscols
widthsWidth of columns
hiddenA 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
sheetThe name of the sheet
rowsrows
collapsedcollapsed
levelslevels
Returns
The wbWorkbook object, invisibly
Method ungroup_rows()
ungroup rows
Usage
wbWorkbook$ungroup_rows(sheet = current_sheet(), rows)
Arguments
sheetThe name of the sheet
rowsrows
Returns
The wbWorkbook object
Method remove_worksheet()
Remove a worksheet
Usage
wbWorkbook$remove_worksheet(sheet = current_sheet())
Arguments
sheetThe 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
sheetThe name of the sheet
dimsCell range in a sheet
typetype
operatoroperator
valuevalue
allow_blankallowBlank
show_input_msgshowInputMsg
show_error_msgshowErrorMsg
error_styleThe 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_titleThe error title
errorThe error text
prompt_titleThe prompt title
promptThe 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, ... )
Arguments
sheetThe name of the sheet
dimsCell range in a sheet
solvelogical if intersecting cells should be solved
...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
sheetThe name of the sheet
dimsCell 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
sheetThe name of the sheet
first_active_rowfirst_active_row
first_active_colfirst_active_col
first_rowfirst_row
first_colfirst_col
...additional arguments
Returns
The wbWorkbook object, invisibly
Method add_comment()
Add comment
Usage
wbWorkbook$add_comment(sheet = current_sheet(), dims = "A1", comment, ...)
Arguments
sheetThe name of the sheet
dimsrow and column as spreadsheet dimension, e.g. "A1"
commenta 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
sheetsheet
dimsdims
Returns
A data frame containing comments
Method remove_comment()
Remove comment
Usage
wbWorkbook$remove_comment(sheet = current_sheet(), dims = "A1", ...)
Arguments
sheetThe name of the sheet
dimsrow 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
sheetThe name of the sheet
dimsCell range in a sheet
commentthe comment to add
person_idthe person Id this should be added for
replylogical if the comment is a reply
resolvelogical if the comment should be marked as resolved
Method get_thread()
Get threads
Usage
wbWorkbook$get_thread(sheet = current_sheet(), dims = NULL)
Arguments
sheetsheet
dimsdims
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
sheetThe name of the sheet
dimsCell range in a sheet
rulerule
stylestyle
typetype
paramsAdditional 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
sheetsheet
dimsdims
firstfirst
lastlast
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, ... )
Arguments
sheetThe name of the sheet
dimsCell range in a sheet
filefile
widthwidth
heightheight
row_offset, col_offsetoffsets
unitsunits
dpidpi
...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
sheetThe name of the sheet
dimsCell range in a sheet
widthwidth
heightheight
row_offset, col_offsetoffsets
file_typefileType
unitsunits
dpidpi
...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
sheetThe name of the sheet
dimsCell range in a sheet
xmlxml
col_offset, row_offsetoffsets 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
sheetThe name of the sheet
dimsCell range in a sheet
xmlxml
col_offset, row_offsetpositioning 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
sheetThe name of the sheet
dimsthe dimensions where the sheet will appear
graphmschart graph
col_offset, row_offsetoffsets 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
sheetThe name of the sheet
dimsCell range in a sheet
typetype
texttext
linklink
rangerange
checkedchecked
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
protectprotect
passwordpassword
lock_structurelock_structure
lock_windowslock_windows
typetype
file_sharingfile_sharing
usernameusername
read_only_recommendedread_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
sheetThe name of the sheet
protectprotect
passwordpassword
propertiesA 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 = Sys.time(), modifier = NULL, keywords = NULL, comments = NULL, manager = NULL, company = NULL, custom = NULL )
Arguments
creatorcharacter vector of creators. Duplicated are ignored.
title, subject, category, datetime_created, modifier, keywords, comments, manager, company, customA workbook property to set
Method add_mips()
add mips string
Usage
wbWorkbook$add_mips(xml = NULL)
Arguments
xmlA mips string added to self$custom
Method get_mips()
get mips string
Usage
wbWorkbook$get_mips(single_xml = TRUE, quiet = TRUE)
Arguments
single_xmlsingle_xml
quietquiet
Method set_creators()
Set creator(s)
Usage
wbWorkbook$set_creators(creators)
Arguments
creatorsA character vector of creators to set. Duplicates are ignored.
Method add_creators()
Add creator(s)
Usage
wbWorkbook$add_creators(creators)
Arguments
creatorsA character vector of creators to add. Duplicates are ignored.
Method remove_creators()
Remove creator(s)
Usage
wbWorkbook$remove_creators(creators)
Arguments
creatorsA 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
nameA 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
sheetThe name of the sheet
black_and_whiteblack_and_white
cell_commentscell_comment
copiescopies
draftdraft
errorserrors
first_page_numberfirst_page_number
idid
page_orderpage_order
paper_height, paper_widthpaper size
hdpi, vdpihorizontal and vertical dpi
use_first_page_numberuse_first_page_number
use_printer_defaultsuse_printer_defaults
orientationorientation
scalescale
leftleft
rightright
toptop
bottombottom
headerheader
footerfooter
fit_to_widthfitToWidth
fit_to_heightfitToHeight
paper_sizepaperSize
print_title_rowsprintTitleRows
print_title_colsprintTitleCols
summary_rowsummaryRow
summary_colsummaryCol
tab_colortabColor
...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
sheetThe name of the sheet
orientationorientation
scalescale
leftleft
rightright
toptop
bottombottom
headerheader
footerfooter
fit_to_widthfitToWidth
fit_to_heightfitToHeight
paper_sizepaperSize
print_title_rowsprintTitleRows
print_title_colsprintTitleCols
summary_rowsummaryRow
summary_colsummaryCol
...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, ... )
Arguments
sheetThe name of the sheet
headerheader
footerfooter
even_headerevenHeader
even_footerevenFooter
first_headerfirstHeader
first_footerfirstFooter
...additional arguments
Returns
The wbWorkbook object, invisibly
Method get_tables()
get tables
Usage
wbWorkbook$get_tables(sheet = current_sheet())
Arguments
sheetThe 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
sheetThe name of the sheet
tabletable
remove_dataremoves the data as well
Returns
The wbWorkbook object
Method add_filter()
add filters
Usage
wbWorkbook$add_filter(sheet = current_sheet(), rows, cols)
Arguments
sheetThe name of the sheet
rowsrows
colscols
Returns
The wbWorkbook object
Method remove_filter()
remove filters
Usage
wbWorkbook$remove_filter(sheet = current_sheet())
Arguments
sheetThe 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
sheetThe name of the sheet
showshow
printprint
Returns
The wbWorkbook object
Method grid_lines()
grid lines
Usage
wbWorkbook$grid_lines(sheet = current_sheet(), show = FALSE, print = show)
Arguments
sheetThe name of the sheet
showshow
printprint
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
sheetThe name of the sheet
dimsCell range in a sheet
namename
local_sheetlocal_sheet
overwriteoverwrite
commentcomment
hiddenhidden
custom_menucustom_menu
descriptiondescription
is_functionfunction
function_group_idfunction group id
helphelp
local_namelocalName
publish_to_serverpublish to server
status_barstatus bar
vb_procedurevb procedure
workbook_parameterworkbookParameter
xmlxml
...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
tablesReturn tables as well?
xNot 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
sheetThe name of the sheet
namename
Returns
The wbWorkbook object
Method set_order()
set worksheet order
Usage
wbWorkbook$set_order(sheets)
Arguments
sheetssheets
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
sheetThe name of the sheet
valuevalue
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
sheetThe name of the sheet
rowrow
colcol
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 )
Arguments
sheetThe name of the sheet
dimsCell range in a sheet
numbersremove all numbers
charactersremove all characters
stylesremove all styles
merged_cellsremove all merged_cells
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, ... )
Arguments
sheetThe name of the sheet
dimsdimensions on the worksheet e.g. "A1", "A1:A5", "A1:H5"
bottom_color, left_color, right_color, top_color, inner_hcolor, inner_vcolora color, either something openxml knows or some RGB color
left_border, right_border, top_border, bottom_border, inner_hgrid, inner_vgridthe border style, if NULL no border is drawn. See create_border for possible border styles
...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
sheetThe name of the sheet
dimsCell range in a sheet
colorthe colors to apply, e.g. yellow: wb_color(hex = "FFFFFF00")
patternvarious 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_filla gradient fill xml pattern.
every_nth_colwhich col should be filled
every_nth_rowwhich 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 = "", ... )
Arguments
sheetThe name of the sheet
dimsCell range in a sheet
namefont name: default "Aptos Narrow"
colorrgb color: default "FF000000"
sizefont size: default "11",
boldbold
italicitalic
outlineoutline
strikestrike
underlineunderline
charsetcharset
condensecondense
extendextend
familyfont family
schemefont scheme
shadowshadow
vert_alignvertical alignment
...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
sheetThe name of the sheet
dimsCell range in a sheet
numfmtnumber 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
sheetThe name of the sheet
dimsCell range in a sheet
apply_alignmentlogical apply alignment
apply_borderlogical apply border
apply_filllogical apply fill
apply_fontlogical apply font
apply_number_formatlogical apply number format
apply_protectionlogical apply protection
border_idborder ID to apply
ext_lstextension list something like
<extLst>...</extLst>fill_idfill ID to apply
font_idfont ID to apply
hiddenlogical cell is hidden
horizontalalign content horizontal ('left', 'center', 'right')
indentlogical indent content
justify_last_linelogical justify last line
lockedlogical cell is locked
num_fmt_idnumber format ID to apply
pivot_buttonunknown
quote_prefixunknown
reading_orderreading order left to right
relative_indentrelative indentation
shrink_to_fitlogical shrink to fit
text_rotationdegrees of text rotation
verticalvertical alignment of content ('top', 'center', 'bottom')
wrap_textwrap text in cell
xf_idxf 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
sheetThe name of the sheet
dimsCell 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
sheetThe name of the sheet
dimsCell range in a sheet
stylestyle
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
sheetsheet
stylestyle
colscols
rowsrows
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
sheetThe name of the sheet
dimsCell range in a sheet
namename
font_name, font_sizeoptional 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
namethe style name
font_namethe font name
font_sizethe font size
font_colorthe font color (a
wb_color()object)num_fmtthe number format
borderlogical if borders are applied
border_colorthe border color
border_stylethe border style
bg_fillany background fill
gradient_fillany gradient fill
text_boldlogical if text is bold
text_italiclogical if text is italic
text_underlinelogical 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
fromthe worksheet you are cloning
tothe worksheet the style is applied to
Method add_sparklines()
apply sparkline to worksheet
Usage
wbWorkbook$add_sparklines(sheet = current_sheet(), sparklines)
Arguments
sheetThe name of the sheet
sparklinessparkline 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
sheetThe name of the sheet
dimsCell range in a sheet
calculated_columncalculatedColumn
empty_cell_referenceemptyCellReference
eval_errorevalError
formulaformula
formula_rangeformulaRange
list_data_validationlistDataValidation
number_stored_as_textnumberStoredAsText
two_digit_text_yeartwoDigitTextYear
unlocked_formulaunlockedFormula
...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
sheetThe name of the sheet
color_id, default_grid_colorInteger: A color, default is 64
right_to_leftLogical: if TRUE column ordering is right to left
show_formulasLogical: if TRUE cell formulas are shown
show_grid_linesLogical: if TRUE the worksheet grid is shown
show_outline_symbolsLogical: if TRUE outline symbols are shown
show_row_col_headersLogical: if TRUE row and column headers are shown
show_rulerLogical: if TRUE a ruler is shown in page layout view
show_white_spaceLogical: if TRUE margins are shown in page layout view
show_zerosLogical: if FALSE cells containing zero are shown blank if !showFormulas
tab_selectedInteger: zero vector indicating the selected tab
top_left_cellCell: the cell shown in the top left corner / or top right with rightToLeft
viewView: "normal", "pageBreakPreview" or "pageLayout"
window_protectionLogical: if TRUE the panes are protected
workbook_view_idinteger: Pointing to some other view inside the workbook
zoom_scale, zoom_scale_normal, zoom_scale_page_layout_view, zoom_scale_sheet_layout_viewInteger: 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
namename
idid
user_iduser_id
provider_idprovider_id
Method get_person()
description get person
Usage
wbWorkbook$get_person(name = NULL)
Arguments
namename
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
sheetThe 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
sheetThe name of the sheet
Method clone()
The objects of this class are cloneable with this method.
Usage
wbWorkbook$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.