1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# 包加载/安装包
loadLibrary <- function(pkgs) {
uninstalledPkgs <- pkgs[!(pkgs %in% installed.packages()[, "Package"])]
if (length(uninstalledPkgs)) {
install.packages(uninstalledPkgs)
}
for (pkg in pkgs) {
library(pkg, character.only = TRUE, quietly = TRUE)
}
}
# 自定义配置
setwd("/path/to/work/dir") # 工作目录
fileName = "summary_sheet_demo.xlsx" # 处理的表格文件
summaryName = "汇总" # 汇总的 sheet 表名
summarySheet = FALSE # 对象变量、忽略
startRow = 2 # 汇总表中操作起始行
# 设置CRAN
options(repos = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/")
# 加载依赖包
loadLibrary(c("xlsx", "rJava"))
# 打开Excel表格
wb <- loadWorkbook(fileName)
# 获取所有表格
sheets <- getSheets(wb)
# 循环所有表格,找出需要写入的表
for (sheet in sheets) {
sheetName <- sheet$getSheetName()
if (sheetName == summaryName) {
summarySheet <- sheet
}
}
if (summarySheet == FALSE) {
stop(paste("表:", summaryName, "未找到"))
}
# 指定Date格式(此处可忽略)
# options(xlsx.date.format='yyyy/MM/dd')
# 遍历所有表格
for (sheet in sheets) {
# 过滤掉需写入的表
sheetName <- sheet$getSheetName()
if (sheetName == summaryName) {
next
}
# 获取表格【内容行数】
rowNum <- sheet$getLastRowNum()
print(paste("表名:", sheetName, "总共:", rowNum, "行,", sep = " "))
# 读取表格内容 参数 colClasses 指定每列的类型(实际是指定处理该列的类/对象)
data <- read.xlsx2(fileName, sheetName = sheetName, header = FALSE, startRow = 2, colClasses = c("character",
"Date", "integer", "integer", rep("numeric", 2), "integer"))
print(data)
# 将表格内容写入汇总的那张表
addDataFrame(data, summarySheet, col.names = FALSE, row.names = FALSE, startRow = startRow)
# 累加行数
startRow <- startRow + rowNum
}
# 最后需要把对象内容写入文件中
saveWorkbook(wb, fileName)
|