You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R实现Excel指定数据范围跨工作簿复制?

Copy Specific Excel Range Between Workbooks (Values Only) in R

Absolutely feasible! This is a common task, and we can use two reliable R packages—readxl for reading specific ranges, and openxlsx for writing values back without carrying over formatting. Here's a complete, commented script to get this done smoothly:

Step 1: Install & Load Required Packages

First, make sure you have the necessary packages installed (run this once if you haven't already):

# Install packages if they're missing
if (!require("readxl")) install.packages("readxl")
if (!require("openxlsx")) install.packages("openxlsx")

# Load the packages into your R session
library(readxl)
library(openxlsx)

Step 2: Read the Target Range from WorkbookX

We'll pull only the raw values from WorksheetX, range A5:X1000—no formatting will be included here:

# Read the exact range we need
source_data <- read_excel(
  path = "WorkbookX.xlsx",
  sheet = "WorksheetX",
  range = "A5:X1000"
)

Step 3: Write Values to WorkbookY's Target Range

Next, we'll open WorkbookY, navigate to WorksheetY, and paste the values into A5:X1000. This will overwrite any existing data in that range but leave all other sheets and content in the workbook untouched:

# Load the existing WorkbookY
target_workbook <- loadWorkbook("WorkbookY.xlsx")

# Write the raw values to the specified range
writeData(
  wb = target_workbook,
  sheet = "WorksheetY",
  x = source_data,
  startCol = 1,  # Column A corresponds to column index 1
  startRow = 5,  # Start pasting at row 5
  keepNA = FALSE  # Optional: replaces NA values with blank cells (adjust if needed)
)

# Save the modified WorkbookY (overwrites the original file)
saveWorkbook(target_workbook, "WorkbookY.xlsx", overwrite = TRUE)

Quick Tips to Avoid Headaches

  • Values Only Guarantee: Both packages handle raw values by default—no cell colors, fonts, or formulas will be copied over, which is exactly what you requested.
  • Preserve Other Data: Using loadWorkbook() ensures we don't wipe out any other sheets or content in WorkbookY; we only modify the A5:X1000 range in WorksheetY.
  • Empty Cells: If A5:X1000 in WorkbookX has empty rows/columns, the script will still read the full range and fill empty spots with blanks (or NAs if you set keepNA = TRUE).

内容的提问来源于stack exchange,提问作者Analyst Guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:39:59