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

How to align the cells of an XLSX file using R's xlsx package?

使用 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")

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

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().

将单元格样式应用于它们

未来读者请注意:上述解决方案会占用大量内存。 我有一个 10Mb data.frame,相应的 all.cells 对象结果是 1.1Gb。

如果唯一的目的是拥有 left-alignment 的单元格,这样做会更容易:

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