使用 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")
Run Code Online (Sandbox Code Playgroud)
我已经用下面的解决方案解决了上述问题:
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")
Run Code Online (Sandbox Code Playgroud)
该解决方案涉及创建一个单元格样式,我将其存储在cs. 接下来,我选择了每一行和每个包含的单元格,并使用lapply().
| 归档时间: |
|
| 查看次数: |
4895 次 |
| 最近记录: |