代码之家  ›  专栏  ›  技术社区  ›  michaelmccarthy404

如何使用R的XLSX包对齐XLSX文件的单元格?

  •  4
  • michaelmccarthy404  · 技术社区  · 6 年前

    使用R的XLSX包创建XLSX文件时,默认情况下,带字符串的列将向左对齐,带整数的列将向右对齐(带整数和字符串混合的列也将向左对齐)。最终,我想通过将所有列都向左对齐来标准化所有列,但在使用xlsx时遇到了问题。使用以下示例,如何将所有单元格向左对齐?

    library(xlsx)
    
    # Creating dataframe.
    df <- data.frame(c(1, 2, 3),
                     c("one", "two", "three"),
                     c("1", "2", "3"))
    
    # Creating a workbook using the XLSX package.
    wb <- xlsx::createWorkbook(type = "xlsx")
    
    # Creating a sheet inside the workbook.
    sheet <- xlsx::createSheet(wb, sheetName = "Sheet0")
    
    # Adding the full dataset into the sheet.
    xlsx::addDataFrame(df, sheet, startRow = 1, startCol = 1, row.names = FALSE, col.names = FALSE)
    
    # Saving the workbook.
    xlsx::saveWorkbook(wb, "df.xlsx")
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   michaelmccarthy404    6 年前

    我用下面的解决方案解决了上述问题:

    library(xlsx)
    
    # Creating dataframe.
    df <- data.frame(c(1, 2, 3),
                     c("one", "two", "three"),
                     c("1", "2", "3"))
    
    # Creating a workbook using the XLSX package.
    wb <- xlsx::createWorkbook(type = "xlsx")
    
    # Creating a sheet inside the workbook.
    sheet <- xlsx::createSheet(wb, sheetName = "Sheet0")
    
    # Adding the full dataset into the sheet.
    xlsx::addDataFrame(df, sheet, startRow = 1, startCol = 1, row.names = FALSE, col.names = FALSE)
    
    # Creating cell style needed to left-justify text.
    cs <- CellStyle(wb) + Alignment(horizontal = "ALIGN_LEFT")
    
    # Selecting rows to apply cell style to.
    all.rows <- getRows(sheet, rowIndex = 1:nrow(df))
    
    # Selecting cells within selected rows to apply cell style to.
    all.cells <- getCells(all.rows)
    
    # Applying cell style to selected cells.
    invisible(lapply(all.cells, setCellStyle, cs))
    
    # Saving the workbook.
    xlsx::saveWorkbook(wb, "df.xlsx")
    

    解决方案包括创建一个单元格样式,我将其存储在 cs 。接下来,我选择了每一行和每一个包含的单元格,并使用 lapply()

        2
  •  0
  •   Angela    2 年前

    未来读者请注意:上述解决方案会消耗大量内存。 我有10Mb的数据。框架和相应的 全部的单元格 该对象原来是1.1Gb。

    如果唯一的目的是使单元格保持左对齐,则可以这样做:

    openxlsx::write.xlsx(
        x = df,
        file = file,
        startRow = 1, 
        startColumn = 1, 
        rowNames = FALSE, 
        colNames = TRUE
      )