0
0
R-programmingHow-ToBeginner · 3 min read

How to Write Excel Files in R: Simple Guide

To write Excel files in R, use the openxlsx package which allows creating and saving Excel workbooks easily. Use write.xlsx() to write data frames to Excel files with simple syntax.
📐

Syntax

The main function to write Excel files in R is write.xlsx() from the openxlsx package.

  • write.xlsx(x, file, sheetName = NULL, colNames = TRUE, rowNames = FALSE)
  • x: The data frame or list of data frames to write.
  • file: The path and name of the Excel file to create.
  • sheetName: Optional name of the sheet (default is "Sheet1").
  • colNames: Whether to write column names (default TRUE).
  • rowNames: Whether to write row names (default FALSE).
r
write.xlsx(x, file, sheetName = NULL, colNames = TRUE, rowNames = FALSE)
💻

Example

This example shows how to write a simple data frame to an Excel file named example.xlsx with default settings.

r
library(openxlsx)

# Create a sample data frame
my_data <- data.frame(Name = c("Alice", "Bob", "Carol"), Age = c(25, 30, 22), Score = c(88, 95, 79))

# Write the data frame to an Excel file
write.xlsx(my_data, file = "example.xlsx")
Output
[No console output, but file 'example.xlsx' is created in working directory]
⚠️

Common Pitfalls

Common mistakes when writing Excel files in R include:

  • Not installing or loading the openxlsx package before using write.xlsx().
  • Forgetting to specify the file extension .xlsx in the file name.
  • Trying to write unsupported object types instead of data frames or lists.
  • Overwriting existing files without warning.

Always check your working directory or specify a full path to avoid confusion.

r
## Wrong: Not loading package
# write.xlsx(my_data, file = "data.xlsx") # Error: could not find function "write.xlsx"

## Right: Load package first
library(openxlsx)
write.xlsx(my_data, file = "data.xlsx")
📊

Quick Reference

FunctionPurposeNotes
write.xlsx()Write data frame to Excel fileMain function to save Excel files
createWorkbook()Create a new Excel workbookUse for advanced Excel file creation
addWorksheet()Add a sheet to workbookUsed with createWorkbook()
saveWorkbook()Save workbook to fileUsed with createWorkbook() and addWorksheet()

Key Takeaways

Use the openxlsx package and its write.xlsx() function to write Excel files in R.
Always load the openxlsx package with library(openxlsx) before writing files.
Specify the file name with .xlsx extension to create a valid Excel file.
write.xlsx() works best with data frames or lists of data frames.
Check your working directory or provide full file paths to avoid confusion.