R Read and Write xlsx Files

Reading and writing Excel files in R can be done using various packages. Following examples using the readxl package for reading Excel files and the openxlsx package for writing Excel files.

Reading Excel Files using readxl Package

The readxl package allows you to read data from Excel files (.xls and .xlsx formats). You can specify the sheet name or index to read data from.

# Install and load the readxl package install.packages("readxl") library(readxl) # Example: Reading data from an Excel file using readxl excel_file_path <- "path/to/your/excelfile.xlsx" data <- read_excel(excel_file_path, sheet = "Sheet1") # Or use sheet = 1 for the first sheet print(data)

Writing Excel Files using openxlsx Package

The openxlsx package provides functions to create and write data to Excel files (.xlsx format). You can customize various aspects of the Excel file, such as sheet names and formatting.

# Install and load the openxlsx package install.packages("openxlsx") library(openxlsx) # Example: Writing data to an Excel file using openxlsx data <- data.frame( Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 28) ) excel_output_file_path <- "path/to/your/output.xlsx" wb <- createWorkbook() # Create a new Excel workbook addWorksheet(wb, "Sheet1") # Add a worksheet writeData(wb, sheet = "Sheet1", x = data) # Write data to the worksheet saveWorkbook(wb, file = excel_output_file_path) # Save the workbook

write.xlsx() function

Alternatively, you can use the write.xlsx() function directly to write a data frame to an Excel file:

# Using write.xlsx to write data to an Excel file write.xlsx(data, excel_output_file_path, sheetName = "Sheet1", row.names = FALSE)


Reading and writing Excel files in R can be achieved using packages like readxl and openxlsx. These packages provide the ability to handle Excel data, which is often used for sharing and analyzing structured information.