如何使用R'对齐XLSX文件的单元格;s xlsx软件包?
使用R的XLSX包创建XLSX文件时,默认情况下,带字符串的列将向左对齐,带整数的列将向右对齐(带整数和字符串混合的列也将向左对齐)。最终,我希望通过将所有列都向左对齐来标准化所有列,但使用xlsx时遇到了问题。使用下面的示例,如何将所有单元格向左对齐如何使用R'对齐XLSX文件的单元格;s xlsx软件包?,r,xlsx,R,Xlsx,使用R的XLSX包创建XLSX文件时,默认情况下,带字符串的列将向左对齐,带整数的列将向右对齐(带整数和字符串混合的列也将向左对齐)。最终,我希望通过将所有列都向左对齐来标准化所有列,但使用xlsx时遇到了问题。使用下面的示例,如何将所有单元格向左对齐 library(xlsx) # Creating dataframe. df <- data.frame(c(1, 2, 3), c("one", "two", "three"),
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")
库(xlsx)
#创建数据帧。
df我用下面的解决方案解决了上述问题:
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")
库(xlsx)
#创建数据帧。
df