簡體   English   中英

如何使用 R 將大型 Excel 文件拆分為多個 Excel 文件

[英]How to split large Excel file into multiple Excel files using R

我正在尋找一種使用 R 將大型 Excel 文件拆分為多個較小 Excel 文件的方法。

具體來說,我想做三件事:

  1. 我有一個大型數據集,其中包含有關學生的信息(他們的學校、學校所在的地區、考試成績 A、考試成績 B),我想將這些信息分成單獨的文件,每個學校一個文件包含所有就讀該特定學校的學生。
  2. 我還希望所有單獨的 Excel 文件包含覆蓋每個 Excel 文件的第一行和列 A、B、C 和 D 的圖像。 數據集中所有學校的圖像都是相同的。
  3. 最后,我還希望 Excel 文件在創建后最終位於我桌面上的各個文件夾中。 文件夾名稱將是學校所在的區域。 一個地區大約有 3-5 所學校,因此該文件夾將包含 3-5 個 Excel 文件,每個學校 1 個。

我的數據結構如下:

區域 學校 學生卡 考試成績A 考試成績 B
一個 134 24 31
一個 221 26 33
122 22 21
126 25 25

我的數據涵蓋了位於 5 個不同地區的大約 200 所學校。

任何有關如何執行此操作的指導將不勝感激!

正如一些評論所引用的,如果不知道您的特定操作環境和文件夾結構,這將很難解決,我使用 Windows 10/ C 驅動器用戶文件夾解決了這個問題,但您可以自定義您的系統。 您將需要一個文件夾,其中包含以學校名稱(或我創建的 ID)保存的所有學校圖像,並且它們都需要采用相同的格式(JPG 或 PNG)。 另外,您需要為您想要 output 的每個區域創建文件夾(openxlsx 可以寫入文件但不能為您創建文件夾)。 一旦你完成了這些設置,類似的東西應該對你有用,但我強烈建議你參考 openxlsx 文檔以獲取更多信息:

library(dplyr)
library(openxlsx)

# Load your excel file into a df
# g0 = openxlsx::read.xlsx(<your excel file & sheet..see openxlsx documentation>)

# Replace this tibble with your actual excel file, this was just for an example
g0 = tibble(
  Area = c("North","North","North","North"),
  School = c("A","A","B","B"),
  Student_ID = c(134,221,122,126),
  test_score_a = c(24,26,22,25),
  test_score_b = c(31,33,21,25))

# Need a numeric school id for the loop
g0$school_id = as.numeric(as.factor(g0$School))

# Loop through schools, filter using dplyr and create a sheet per school
for (i in 1:n_distinct(g0$school_id)){
  g1 = g0 %>% 
  filter(school_id == i)
  
  ## Create a new workbook
  wb <- createWorkbook(as.character(g1$School))
  
  ## Add some worksheets
  addWorksheet(wb, as.character(g1$School))
  
  ## Insert images
  ## I left the image as a direct path for example but you can change to a
  ## relative path once you get it working
  img <- system.file("C:","Users","your name","Documents","A","A.jpg", package = "openxlsx")
  insertImage(wb, as.character(g1$School), img, startRow = 5, startCol = 3, width = 6, height = 5)

  ## Save workbook
  saveWorkbook(wb, paste0("C://Users//your name//Documents//",g0$Area,"//",g0$school,".xlsx"), overwrite = TRUE)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM