使用 readxl 导入 Excel 文件
读取 .xls 和 .xlsx 工作表,并使用工作表选择和单元格范围选项
使用 readxl 导入 Excel 文件 是 CoddyKit 上的免费 R Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。
为什么使用 readxl 读取 Excel 文件?
Excel 文件(.xlsx 和 .xls)在商业环境中非常普遍。readxl 软件包无需安装 Excel 即可读取这些文件,也不依赖 Java。它返回 tibble,并支持多个工作表、命名区域和单元格类型检测。
library(readxl)
# readxl can read:
# .xlsx - modern Excel format (XML-based)
# .xls - older Excel format (binary)
# .xlsm - Excel with macros (reads data, ignores macros)
# Core functions:
# read_excel() - auto-detects .xls vs .xlsx
# read_xlsx() - always reads as .xlsx
# read_xls() - always reads as .xls
# excel_sheets() - lists all sheet names
cat('readxl requires no Java, no Excel installation!')excel_sheets() — 列出所有工作表
excel_sheets('file.xlsx') 返回包含所有工作表名称的字符向量。读取前可以使用它检查工作簿结构,然后将工作表名称传递给 read_excel()。
library(readxl)
# Using readxl's built-in example file
path <- readxl_example('datasets.xlsx')
# List all sheets in the workbook
sheets <- excel_sheets(path)
print(sheets)
cat('\nNumber of sheets:', length(sheets))read_excel() — 基本用法
read_excel(path) 默认读取第一个工作表。它会自动检测文件是 .xls 还是 .xlsx。返回结果是一个 tibble,列类型根据数据自动猜测。
library(readxl)
path <- readxl_example('datasets.xlsx')
# Read the first sheet (default)
df <- read_excel(path)
print(head(df, 4))
cat('\nDimensions:', nrow(df), 'rows x', ncol(df), 'cols')sheet 参数 — 按名称或索引选择
使用 sheet='Sheet1' 按名称选择,或使用 sheet=2 按位置选择(索引从 1 开始)。两种方式都有效。如果工作表顺序可能变化,使用名称更加稳妥;在迭代处理中,使用索引更加方便。
library(readxl)
path <- readxl_example('datasets.xlsx')
sheets <- excel_sheets(path)
print(sheets)
# Read by name
df_name <- read_excel(path, sheet = 'iris')
cat('iris sheet rows:', nrow(df_name), '\n')
# Read by index
df_idx <- read_excel(path, sheet = 2)
cat('Sheet 2 rows:', nrow(df_idx))range — 读取单元格区域
range='A1:D10' 只读取 Excel 表示法中指定的单元格区域。当工作表包含多个表格、带有格式边框,或数据区域外存在您需要排除的元数据时,这种方式非常有用。
library(readxl)
path <- readxl_example('datasets.xlsx')
# Read only the first 5 data rows of columns A-D
df <- read_excel(path, sheet='iris', range='A1:D6')
print(df)
cat('\nShape:', nrow(df), 'rows,', ncol(df), 'cols')col_names — 自定义列名
设置 col_names=FALSE 可跳过表头行并自动命名列。向 col_names 传入字符向量即可使用自定义名称(同时跳过表头行)。如果表头位于其他行,请与 skip 结合使用。
library(readxl)
path <- readxl_example('datasets.xlsx')
# Read with custom column names (skip original header)
df <- read_excel(
path,
sheet = 'iris',
col_names = c('sepal_l','sepal_w','petal_l','petal_w','species'),
skip = 1 # Skip the original header row
)
print(head(df, 3))
print(names(df))skip 参数 — 跳过元数据行
skip=n 会在读取前跳过工作表开头的 n 行。当工作表中的实际数据表上方有报告标题、生成日期或其他元数据时,这一参数很有用。
library(readxl)
# Simulating a sheet with metadata rows (using a range instead)
path <- readxl_example('datasets.xlsx')
# Skip first row (pretend it has a title)
# and read only first 5 data rows
df <- read_excel(
path,
sheet = 'chickwts',
skip = 1, # Skip first data row
col_names = FALSE # Row 2 has no header now
)
print(head(df, 4))col_types — 指定列类型
使用 col_types 覆盖类型猜测结果。有效类型包括:'text'、'numeric'、'date'、'logical'、'skip'(删除该列)和 'list'(用于混合类型的列)。
library(readxl)
path <- readxl_example('datasets.xlsx')
# Read with explicit column types
# iris sheet: 4 numeric + 1 text
df <- read_excel(
path,
sheet = 'iris',
col_types = c('numeric','numeric','numeric','numeric','text')
)
print(sapply(df, class))使用 map() 读取所有工作表
将 excel_sheets() 与 purrr::map() 结合使用,可以一次性读取所有工作表,并将结果放入带名称的列表中。列表中的每个元素都是对应工作表的 tibble。使用 map_df(.id='sheet') 可以按行绑定所有工作表。
library(readxl)
library(purrr)
path <- readxl_example('datasets.xlsx')
sheets <- excel_sheets(path)
# Read all sheets into a named list
all_data <- map(sheets, ~read_excel(path, sheet=.x))
names(all_data) <- sheets
# Show dimensions of each sheet
map_df(all_data, function(df) {
data.frame(rows=nrow(df), cols=ncol(df))
}, .id='sheet')n_max — 限制读取的行数
n_max=n 最多读取 n 行数据(不包括表头)。您可以使用它预览大型工作表、加载用于测试的样本,或在内存受限的环境中分块读取数据。
library(readxl)
path <- readxl_example('datasets.xlsx')
# Preview just the first 5 rows
preview <- read_excel(path, sheet='iris', n_max=5)
print(preview)
cat('\nPreviewed', nrow(preview), 'of', nrow(read_excel(path, sheet='iris')), 'rows')na 参数 — 缺失值字符串
与 readr 类似,readxl 接受一个 na 参数,用于指定哪些文本字符串应被读取为 NA。Excel 通常会将缺失值存储为空单元格(会自动处理),或者存储为 'N/A'、'#N/A' 之类的哨兵字符串。
library(readxl)
path <- readxl_example('datasets.xlsx')
# Handle Excel error strings and custom NA markers
# In real files these might be '#N/A', '#VALUE!', 'N/A', '-'
df <- read_excel(
path,
sheet = 'iris',
na = c('', 'NA', 'N/A', '#N/A', '-')
)
cat('Missing values per column:\n')
print(colSums(is.na(df)))快速检查
excel_sheets('file.xlsx') 会返回什么?
回顾:导入 Excel 文件
使用 readxl 导入 Excel 的要点:
excel_sheets(path)— 列出所有工作表名称read_excel(path)— 读取第一个工作表;自动识别 .xls/.xlsxsheet='Name'或sheet=2— 按名称或索引选择工作表range='A1:D10'— 读取指定单元格范围col_names, skip— 处理元数据行和自定义表头col_types = c('text','numeric','date','skip')— 覆盖类型推断n_max=5— 预览大型文件;na=c('N/A','#N/A')— 自定义 NA 字符串- 结合
map(excel_sheets(path), ~read_excel(path, sheet=.x))可读取所有工作表
library(readxl)
library(purrr)
path <- readxl_example('datasets.xlsx')
# Full workflow: discover, select, read
cat('Sheets available:', paste(excel_sheets(path), collapse=', '), '\n\n')
# Read a specific sheet with explicit types
df <- read_excel(
path,
sheet = 'iris',
col_types = c('numeric','numeric','numeric','numeric','text'),
n_max = 5
)
print(df)常见问题解答
「使用 readxl 导入 Excel 文件」课时是免费的吗?
是的 — 「使用 readxl 导入 Excel 文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「使用 readxl 导入 Excel 文件」这节课中我会学到什么?
读取 .xls 和 .xlsx 工作表,并使用工作表选择和单元格范围选项 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 readxl 导入 Excel 文件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 read_csv() 读取 CSV 文件
- 解析 TSV 与定宽文件
- 使用 readxl 导入 Excel 文件
- 将数据写入多种格式