Learn R Programming  /  Import & Export  /  Excel Files

Excel Files

Base R cannot read .xlsx files directly. The readxl and writexl packages, both free and widely used, add that capability with a simple, consistent interface.

Installing the Packages (One-Time Setup)

R Code
install.packages("readxl")
install.packages("writexl")
💡 Tip
You only need to install a package once per computer. After that, load it with library() at the start of every script where you use it.

Reading an Excel File

R Code
library(readxl)

df <- read_excel("students.xlsx")
df
Output
# A tibble: 2 x 2
  name   score
  <chr>  <dbl>
1 Rafi      88
2 Meera     92

Reading a Specific Sheet

R Code
excel_sheets("students.xlsx")          # list all sheet names first

read_excel("students.xlsx", sheet = "Term2")
read_excel("students.xlsx", sheet = 2)      # or by position
Output
[1] "Term1" "Term2"

Writing an Excel File

R Code
library(writexl)

write_xlsx(df, "students_out.xlsx")

# write multiple sheets in one file at once
write_xlsx(list(Term1 = df, Term2 = df), "report.xlsx")

Advanced: Skipping Header Rows and Limiting Range

🚀 Advanced Example
Real Excel files often have title rows, notes, or merged cells above the actual data table. skip and range let you point precisely at the data you need.
R Code
# skip the first 3 rows (title/notes), then read the data
read_excel("messy_report.xlsx", skip = 3)

# or target an exact cell range
read_excel("messy_report.xlsx", range = "B4:D20")

Key Points

  • readxl::read_excel() reads .xlsx/.xls; writexl::write_xlsx() writes them back out.
  • Use excel_sheets() first to see what sheets exist before choosing one with sheet = .
  • write_xlsx() can write several data frames as separate sheets in one call using a named list.
  • skip and range help you read messy, real-world spreadsheets with extra header rows.