To read an Excel file in R, use the read_excel() function from the readxl package: install and load readxl, then call read_excel("path/to/file.xlsx"). This returns a tibble with the first sheet by default. You can specify a different sheet with the sheet argument, skip rows, and set column types. The package supports .xlsx and .xls files and does not require Java or Excel to be installed.
What You'll Need
- R installed (version 3.6 or later recommended) and optionally RStudio.
- The
readxlpackage, which you can install from CRAN withinstall.packages("readxl"). - An Excel file saved on your computer or accessible via a URL.
- Basic familiarity with R syntax and working directories.
Step-by-Step
- Install the readxl package (once). In the R console, run
install.packages("readxl"). This downloads and installs the package and its dependencies. You only need to do this once per R installation. - Load the package. At the start of your script, run
library(readxl). This makesread_excel()available. If you see no error, the package is ready. - Set your working directory or use a full path. Use
setwd("C:/Users/YourName/Documents")(Windows) orsetwd("~/Documents")(macOS/Linux) to point R to the folder containing your file. Alternatively, provide the full path in the function call. On Windows, use forward slashes/or double backslashes\\. - Check available sheets (optional). Run
excel_sheets("data.xlsx")to list all sheet names. This helps you pick the right one for thesheetargument. - Read the file. Use
read_excel("data.xlsx")to import the first sheet. To read a specific sheet, useread_excel("data.xlsx", sheet = "Sheet2")orsheet = 2. The result is a tibble (a modern data frame). - Inspect the data. Run
head(mydata)to see the first six rows,str(mydata)for column types, andsummary(mydata)for quick statistics. Check that column names and types look correct. - Handle common arguments. Use
skip = nto skip the first n rows (e.g., if there are title rows). Usecol_names = FALSEif the first row is not headers, orcol_names = c("A","B")to supply names. Userange = "A1:C10"to read a specific cell range. Usena = c("", "NA")to specify strings to treat as missing values. - Save the imported data if needed. Assign the result to a variable:
mydata <- read_excel("data.xlsx"). You can then write it to CSV withwrite.csv(mydata, "mydata.csv", row.names = FALSE)or continue analysis.
Common Mistakes
- Forgetting to load the package. Calling
read_excel()withoutlibrary(readxl)gives an error. Always load it first. - Using backslashes in Windows paths without escaping.
"C:\Users\file.xlsx"causes an error because\Uis interpreted as a Unicode escape. Use"C:/Users/file.xlsx"or"C:\\Users\\file.xlsx". - Assuming the first sheet is the right one. Many workbooks have multiple sheets. Use
excel_sheets()to check and specify the sheet explicitly. - Ignoring column type guessing.
read_excel()guesses types from the first 1000 rows. If later rows contain different types (e.g., numbers mixed with text), you may get warnings or incorrect types. Use thecol_typesargument to set types manually, e.g.,col_types = c("text", "numeric", "date"). - Not handling missing values. By default, empty cells become
NA. If your file uses other codes like "N/A" or "-", specify them withna = c("", "NA", "N/A", "-"). - Reading a file that is open in Excel. On Windows, Excel locks the file, and R may fail to read it. Close the file in Excel before reading.
Tips
- Use
read_excel()for both.xlsxand.xlsfiles; it handles both without extra setup. - For large files, consider using the
rangeargument to read only the necessary cells, which speeds up import. - If you need to read many sheets, loop over
excel_sheets()and uselapply()to read each sheet into a list of data frames. - Use
readxl::read_excel()with the double-colon operator to avoid conflicts if other packages also defineread_excel. - To preserve leading zeros in text columns (e.g., ZIP codes), set
col_types = "text"for those columns. - When sharing code, use relative paths or the
herepackage to make scripts portable.
Troubleshooting
If read_excel() fails, work through these checks in order:
- Error: could not find function "read_excel". The package is not loaded. Run
library(readxl). - Error: 'data.xlsx' does not exist. Check the file path. Use
getwd()to see the current working directory, andlist.files()to list files. Ensure the file name and extension are correct. - Error: file is not a valid Excel file. The file may be corrupted or in a different format (e.g., CSV saved with .xlsx extension). Open it in Excel to verify, or try
read.csv()if it is actually CSV. - Warning: expecting numeric, got text. Column type mismatch. Use
col_typesto force the correct type, or clean the data before import. - Permission denied. Close the file in Excel or other programs. On macOS/Linux, check file permissions with
file.access("data.xlsx", 4). - Package installation fails. Ensure you have an internet connection and write permissions to the library folder. Try
install.packages("readxl", dependencies = TRUE). - If that did not work, try reading the file with the
openxlsxpackage (openxlsx::read.xlsx()) as an alternative, or convert the file to CSV and useread.csv().
Frequently Asked Questions
Can read_excel read .xls files?
Yes, readxl supports both .xlsx and .xls formats without needing Java or Excel installed.
How do I read a specific sheet by name?
Use the sheet argument: read_excel("file.xlsx", sheet = "Sheet2"). You can also use the sheet index, e.g., sheet = 2.
Why are my column names not correct?
If the first row does not contain headers, set col_names = FALSE. If headers are in a different row, use skip to skip rows before the headers, or use range to start at the header row.
How can I read only a range of cells?
Use the range argument, e.g., range = "B2:D10" or range = "Sheet1!A1:C5". This reads only the specified cells.
Does read_excel work with password-protected files?
No, readxl cannot read password-protected Excel files. You must remove the password first using Excel or another tool.
What is the difference between read_excel and read.xlsx?
read_excel is from the readxl package and returns a tibble. read.xlsx is from the openxlsx package and returns a data frame. Both work, but readxl is part of the tidyverse and often preferred for its simplicity.