【发布时间】:2014-07-08 19:42:56
【问题描述】:
我一直在玩弄 xlsx 包作为从 R 导出输出的一种方式,当您(事先)不知道哪些列将以哪种方式格式化时,我在设置列数据格式时遇到了问题。
顺便说一句,我发现这个关于 tradeblotter 的最精彩的帖子对我达到这一点有很大帮助。我强烈推荐它:background post from Tradeblotter blog
在我的用例中,我每月生成报告,每个月要导出的 data.frame 将增加 1 列或更多列(然后需要正确格式化)。我不想手动进入并在代码中设置列名,而是希望 R 为我计算列数,然后将索引向量提供给 xlsx 代码。
在研究了 colStyle 列表对象的结构后,我能够创建这个解决方法,但我必须相信有更好的方法,我正在寻找一些帮助来找到它。
提前致谢! 克里斯
require(xlsx)
iris$cost <- rbinom(nrow(iris), 3, .85)+1000
iris$cost2 <- rbinom(nrow(iris), 3, .85)+1000
test <- createWorkbook()
# Define some cell styles within that workbook
csSheetTitle <- CellStyle(test) + Font(test, heightInPoints=18, isBold=TRUE)
csdollar <- CellStyle(test, dataFormat=DataFormat("$###,##0.00")) # ... for ratio results
csdefault <- CellStyle(test, dataFormat=DataFormat("0.00")) # ... for ratio results
csTableColNames <- CellStyle(test) + Font(test, isBold=TRUE) + Alignment(wrapText=TRUE, h="ALIGN_CENTER") + Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK"))
csTableColNames <- CellStyle(test) + Font(test, isBold=TRUE) + Alignment(wrapText=TRUE, h="ALIGN_CENTER") + Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK"))
sheet <- createSheet(test, sheetName = names(ytddflist)[i])
rows <- createRow(sheet,rowIndex=1)
sheetTitle <- createCell(rows, colIndex=1)
setCellValue(sheetTitle[[1,1]], "iris data with cost ($)")
setCellStyle(sheetTitle[[1,1]], csSheetTitle)
default.format = list(
'1'=csdefault,
'2'=csdefault,
'3'=csdefault,
'4'=csdefault)
dollar.format =list(
'notused'=csdollar)
# here is where I create the dollar.format list object that will eventuall be fed to addDataFrame
dollar.format.list <- rep(dollar.format, 2)
names(dollar.format.list) <- as.character(c(6, 7))
addDataFrame(iris, sheet, startRow=3, startColumn=1, colStyle=c(default.format,dollar.format.list), colnamesStyle = csTableColNames)
saveWorkbook(test , "iriswithdollarx2.xlsx")
【问题讨论】: