如何在单元格不重叠的情况下将数据框写入 excel
How can I write a data frame to excel without cells overlapping
我有一个要写入的数据框 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)
当然可以,您只需要合并单元格并将其居中。以下代码将执行您的要求(尽管请参阅我的脚注)
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)
我有一个要写入的数据框 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)
当然可以,您只需要合并单元格并将其居中。以下代码将执行您的要求(尽管请参阅我的脚注)
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)