gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:20:56 26 4
gpt4 key购买 nike

使用 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() 将单元格样式应用于它们。 .

关于r - 如何使用 R 的 xlsx 包对齐 XLSX 文件的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50030410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com