如何通过openxlsx writeData()

时间:2017-05-11 21:09:54

标签: r excel

我有一个我用作模板的.xlsx文件。它充满了颜色,边框,数字格式等。我只想用来自R的数据填充这个工作簿。

我使用的xlsx软件包效果很好,但它似乎覆盖了预先存在的单元格格式。例如,让我们从生成模板工作簿开始:

#--------------------------------------------------
# Create a workbook with styling 
# (I'm not actually making my workbook via code. This is just to generate a reproducible example.)

library(xlsx)

## Create a new workbook
wb <- createWorkbook("Sample Workbook")
addWorksheet(wb, "Sample Worksheet") 
writeData(wb, sheet = "Sample Worksheet", data.frame(Dates = as.Date(c("2017-1-1", "2018-1-1"))))
addStyle(wb, sheet = "Sample Worksheet", createStyle(numFmt="mm/dd/yy"), rows = 2:3, cols = 1, gridExpand = TRUE)
saveWorkbook(wb, "Sample Workbook.xlsx", overwrite = TRUE)

这应该创建一个工作簿,“Sample Workbook.xlsx”,看起来像

enter image description here

现在让我们创建新值并将它们插入到我们的模板中:

#--------------------------------------------------
# Insert data and retain cell styles

newdates <- data.frame(Dates = as.Date(c("2019-1-1", "2020-1-1")))
wb <- loadWorkbook("Sample Workbook.xlsx")
writeData(wb, sheet = "Sample Worksheet", newdates)
saveWorkbook(wb, "Sample Workbook Modified.xlsx", overwrite = TRUE)

这会插入数据,但请注意它会删除我们在上面设置的日期格式

enter image description here

如何在模板工作簿中插入数据并保留格式?

0 个答案:

没有答案