使用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")
答案 0 :(得分:3)
我用下面的解决方案解决了上述问题:
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()
将单元格样式应用于它们。