Read Excel Files in R: A Step-by-Step Guide
Reading an Excel file in R brings spreadsheet data into a data frame or tibble so you can inspect, clean, and analyze it. You will need the file path and an Excel-reading package; the steps below use readxl, which reads .xls and .xlsx files without requiring Excel to be installed.
What You’ll Need
- R and, optionally, RStudio or another R editor.
- An Excel workbook saved as .xlsx or .xls.
- The readxl package, installed from CRAN, and permission to access the file.
- The worksheet name or number if the workbook has more than one sheet.
Step-by-Step
- Install readxl once. In the R console, run
install.packages("readxl"). Installation requires an internet connection and normally only needs to be done once for each R library. If R asks you to select a CRAN mirror, choose one near you. - Load the package in each new session. Run
library(readxl). If you prefer not to attach the package, call the function by its full name later asreadxl::read_excel(). - Locate the workbook. The simplest reliable option is to use its full file path. For example, a Windows path might be
"C:/Users/Ana/Documents/sales.xlsx"; on macOS or Linux, it might be"/home/ana/Documents/sales.xlsx". In R strings, forward slashes work on Windows too. Alternatively, place the file in your working directory and use just its name. - Check or set the working directory if using a relative path. Run
getwd()to see the current directory. In RStudio, you can use the Files pane to navigate to the folder and choose its More menu, then Set As Working Directory. You can also set it in code withsetwd("C:/Users/Ana/Documents"). The directory must exist; a full path often avoids confusion. - List the workbook’s sheets. Use
excel_sheets("C:/Users/Ana/Documents/sales.xlsx"), replacing the example path with yours. This returns the worksheet names in order and confirms that R can open the workbook. You can also supply a short filename if it is in the working directory. - Read a sheet. Import the first worksheet with
sales <- read_excel("C:/Users/Ana/Documents/sales.xlsx"). To select a named sheet, usesales <- read_excel("C:/Users/Ana/Documents/sales.xlsx", sheet = "January"). You may select by position instead, for examplesheet = 2. The result is stored insales; the original workbook is not changed. - Inspect what was imported. Run
dim(sales)for row and column counts,names(sales)for column names, andhead(sales)for a preview. Usestr(sales)to see each column’s data type. These checks can reveal an incorrect sheet, shifted headers, or values interpreted as text. - Handle headers and data types when necessary. By default, readxl treats the first non-skipped row as column names. If the sheet has no header row, use
col_names = FALSE. If its headers start after two introductory rows, useskip = 2. To read a column as text, specify a type such ascol_types = c("text", "numeric", "date"); provide one type per column when setting types explicitly. Supported types include text, numeric, date, date-time, logical, and skip. - Import only the section you need, if appropriate. The
rangeargument can limit the import, for exampleread_excel("sales.xlsx", range = "A1:D20"). Excel cell ranges are useful when a worksheet contains notes or multiple tables. A specified range takes precedence over arguments such asskipandn_max, so check that it covers the intended data. - Save or continue using the result. Use
salesin your R analysis, or export it as a CSV withwrite.csv(sales, "sales.csv", row.names = FALSE). Exporting to CSV does not preserve workbook formatting, formulas, or multiple sheets; it writes the imported values as a plain-text table.
Common Mistakes
- Using the wrong path: A filename alone works only when the file is in the current working directory. Check
getwd()or provide a full path. - Misspelling the sheet: Sheet names must match, including spaces and punctuation. Copy a name from
excel_sheets(). - Expecting formulas to be recalculated: readxl imports the values saved in the workbook, not Excel’s formula logic. If a workbook has not recalculated and saved its formulas, imported formula results may be missing or out of date.
- Assuming every column has the right type: Mixed entries, blank cells, or formatting can lead to unexpected types or missing values. Inspect with
str()and check suspicious columns. - Confusing blank cells with zero: Empty cells are generally read as missing values (
NA), not as numeric zero. Treat them according to what they mean in your data.
Tips
- Use
read_excel()for both .xls and .xlsx files; it can usually identify the format automatically. You can specifysheet =,range =,skip =, andcol_names =as needed. - For a quick interactive file selection, try
read_excel(file.choose()). A file dialog opens, though this is less convenient for a repeatable script. - Column names that are blank or duplicated may be adjusted to make them usable. Check
names(sales)before referring to columns by name. - Keep a copy of the source workbook and make cleaning changes in R or in a separate output file. Importing data does not preserve Excel cell formatting.
Troubleshooting
“File does not exist” or a similar path error: Check spelling, file extension, and folder. Use file.exists("C:/Users/Ana/Documents/sales.xlsx"); it should return TRUE if R can see the file. Avoid mistaking a browser download folder for your working directory.
“Package ‘readxl’ is not installed”: Run install.packages("readxl"), then retry library(readxl). If installation fails, check your internet connection and whether R can write to its package library; an administrator or R support resource may be needed on a managed computer.
The wrong worksheet or an empty result appears: Print excel_sheets(path), select the intended sheet by its exact name, and verify that the sheet actually contains data. If you set a range, confirm its row and column coordinates.
Headers or columns look incorrect: Inspect the first rows with read_excel(path, col_names = FALSE, n_max = 6). Adjust skip or col_names to match the layout, and specify column types only after confirming the column order.
A workbook cannot be read: Confirm that it is a valid Excel file, not a renamed CSV or a temporary lock file (often starting with ~$). Close the workbook in other programs and try again. For a damaged or password-protected file, open it in spreadsheet software and save an accessible copy; readxl does not unlock protected workbooks.
Frequently Asked Questions
Do I need Microsoft Excel installed?
No. readxl reads workbook files directly and does not require Excel.
Can I read a specific sheet by number?
Yes. Use sheet = 2 for the second sheet, or pass its exact name as a character string.
What does read_excel() return?
It returns a tibble, a table-like data frame. You can use it with base R functions and many R data-analysis tools.
How do I read an Excel file with several header rows?
Use skip to ignore rows above the table, then inspect the result. For more complex headers, import without column names and reshape or rename the columns afterward.
Can readxl import multiple sheets at once?
One call reads one sheet. Use excel_sheets() to get the names, then read the sheets separately, for example with a loop or a function such as lapply().
How can I read dates correctly?
Excel stores dates as numeric values with workbook-specific date systems. readxl recognizes many date-formatted cells, but check the imported class and values; explicitly set col_types to "date" if needed.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.