【问题标题】:Openxlsx in R Cell Merging and Centering contentR 单元格合并和居中内容中的 Openxlsx
【发布时间】:2019-11-07 07:29:55
【问题描述】:

我在 r 中使用openxlsx 创建具有某些格式参数的 excel 文件。以下是可复用的代码:

library(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "TestSheet")
df <- mtcars
df$Car <- row.names(mtcars)
row.names(df) <- NULL
df <- df[,c(length(df), 1:length(df)-1)]

forTopTit <- createStyle(fontColour = "#ffffff", fgFill = "#F4D03F",halign = "center",wrapText = TRUE,valign = "center")
forColHdr <- createStyle(fontColour = "#ffffff", fgFill = "#4F81BD",halign = "center",wrapText = TRUE,valign = "center")
forDatStl <- createStyle(fontColour = "#ffffff", halign="center")

writeData(wb,"TestSheet", "THIS IS A TEST MESSAGE", startCol = 1,startRow = 1,colNames = FALSE, rowNames = TRUE,
          headerStyle = forTopTit,borders = "surrounding",borderStyle = "medium")

writeData(wb,"TestSheet", df, startCol = 1,startRow = 2,colNames = TRUE,rowNames = FALSE,
          headerStyle = forColHdr,borders='all',borderStyle = "thin")
mergeCells(wb, "TestSheet", cols=1:length(df), rows=1)
setColWidths(wb, "TestSheet", ignoreMergedCells = TRUE,cols = 1:ncol(df), widths = "auto")
openXL(wb)

我面临两个问题:

  1. 我试图在第一列第一行(这是一个合并的单元格)中创建的标题始终左对齐,并且没有应用任何颜色。

  2. 我想将第 3 行第 2 列的数据居中,但我无法做到。我尝试使用以下代码:

    addStyle(wb, "TestSheet", style=forDatStl, rows = 3:nrow(df), cols=3:length(df), gridExpand=TRUE)

上述类型隐藏了所有数据点,尽管它仍然保留在单元格中。我看不到它们,但是当我选择单元格时,我可以在工作表上方的摘要行上看到它。我正在使用 Ubuntu 18.04 和 Libre Office Calc。

【问题讨论】:

    标签: r excel openxlsx


    【解决方案1】:

    您的单元格被“隐藏”了,因为您设置了颜色#ffffff,即白色,背景为白色。

    使用另一种颜色:

    forDatStl <- createStyle(fontColour = "#000000", halign="center")
    

    将合并的单元格居中:

    centerStyle <- createStyle(halign = "center")
    mergeCells(wb, "TestSheet", cols=1:length(df), rows=1)
    addStyle(wb, "TestSheet", centerStyle, rows = 1, cols = 1)
    

    【讨论】:

    • 非常感谢,我确实发现了字体颜色问题...但是,我无法对齐文本中心。再次感谢您
    • 你知道如何使用openxlsx::InsertImage使图像居中吗?
    猜你喜欢
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多