如何在单元格不重叠的情况下编写数据框架以实现卓越

时间:2019-12-17 11:54:03

标签: r openxlsx

我有一个要写入excel的数据框,但我正在努力适应单元格周围的边框。

如果数据框的一个单元格与另一个单元格重叠,则我想将这些列合并在一起,并且其列名也要相同。

这是我追求的目标的可复制示例:

library(openxlsx)
wb <- createWorkbook()
Sheet <- addWorksheet(wb, "Sheet 1")

Df <- data.frame(Location = c("AAAAAAAAAAAAAAAAAAAAAAAAA"))

writeDataTable(wb, Sheet, Df)

shell(shQuote(string = wb$saveWorkbook()), wait = TRUE)

enter image description here

1 个答案:

答案 0 :(得分:3)

当然,您只需要合并和居中单元格即可。以下代码将完成您的要求(尽管请参阅我的脚注)

library(openxlsx)
wb <- createWorkbook()
Sheet <- addWorksheet(wb, "Sheet 1")

Df <- data.frame(Location = c("AAAAAAAAAAAAAAAAAAAAAAAAA"))

# Write the data without a filter
writeData(wb, Sheet, Df, withFilter = FALSE)

# Create a style to allow the cells to be centred
centred <- createStyle(halign = "center")

# Merge and center each row                   <- Loop referred to in footnote
for (i in 1:(length(Df$Location) + 1) )
{
  addStyle(wb, Sheet, centred, i, 1:4)
  mergeCells(wb, Sheet, 1:4, i)
}

# Save the file
saveWorkbook(wb, path.expand("~/test_merge.xlsx"))

脚注

与其合并单元格,不如根据其内容调整它们的宽度。这将允许您编写多列数据帧。因此,除了上面的循环,您可以做

addStyle(wb, Sheet, centred, 1:(length(Df$Location) + 1), 1)
setColWidths(wb, Sheet, 1, max(nchar(as.character(Df$Location))) * 1.5)