【发布时间】:2017-07-23 06:23:05
【问题描述】:
我正在尝试使用 R 在我的 Excel 文件的每张纸上添加一个标题(因为我的所有数据都来自 R,我需要将它组织到一个 Excel 文件中)。为了做到这一点,我使用'xlsx'包中的这个函数,我发现了here:
#++++++++++++++++++++++++
# Helper function to add titles
#++++++++++++++++++++++++
# - sheet : sheet object to contain the title
# - rowIndex : numeric value indicating the row to
#contain the title
# - title : the text to use as title
# - titleStyle : style object to use for title
xlsx.addTitle<-function(sheet, rowIndex, title, titleStyle){
rows <-createRow(sheet,rowIndex=rowIndex)
sheetTitle <-createCell(rows, colIndex=1)
setCellValue(sheetTitle[[1,1]], title)
setCellStyle(sheetTitle[[1,1]], titleStyle)
}
程序是: 1)创建一个新行 2) 在此行中创建一个单元格以包含标题。 3) 设置单元格值。
为了在每张纸上添加标题,我把这个函数放在一个循环中:
# preparing for the loop
wb <- loadWorkbook(file = "tmp_regioes.xlsx")
sheets <- getSheets(wb)
z <- length(titles)
# creating the style
SUB_TITLE_STYLE <- CellStyle(wb) +
Font(wb, heightInPoints=14,
isItalic=TRUE, isBold=FALSE)
# loop
for (i in (1:z)) {
sheet <- sheets[[i]]
# Add sub title
xlsx.addTitle(sheet, rowIndex=1,
title= paste0(titles[i]),
titleStyle = SUB_TITLE_STYLE)
}
但它并没有真正创建一个新行;相反,它会删除我的第一行的内容,其中包含值(我的表的列名)。
澄清一下,文件“tmp_regioes.xlsx”是使用函数WriteXLS创建的,因为我需要在同一个文件中保存10个表;例如,此功能似乎没有将表格保存在第二行的选项。
如果有人可以帮助我,我会很高兴。 提前谢谢大家。
【问题讨论】: