0

我想将类似于下面的数据集导出到一个 excel 文件中,并为行着色,并将 colnames+rownames 格式更改为粗体。

data("HairEyeColor")

mat<-table(HairEyeColor$Hair,HairEyeColor$Eye)
class(mat)

df<-as.data.frame(cbind(mat[,1],mat[,2],mat[,3],mat[,4]))

colnames(df)<-colnames(mat)

write.xlsx(df,"df.xlsx",col.names = TRUE,
           row.names = TRUE)

像这个:)(我用这些颜色来解释:#0070C0 #8DB4E2 #DAEEF3)

在此处输入图像描述

4

1 回答 1

1

尝试openxlsx

这种方法可能看起来有点冗长,但是您正在逐行构建电子表格代码,这与您通过单击构建电子表格的方式非常相似。

openxlsx 的一个衬里默认为 :write.xlsx(mtcars, "openxlsx_table_default.xlsx", asTable = TRUE)让您成为其中的一部分。

library(openxlsx)

df <- mtcars


# Create workbook
wb <- createWorkbook("df_eg")

# Add a worksheets
addWorksheet(wb, sheet = 1, gridLines = FALSE)

# write data
writeData(wb, sheet = 1, df, rowNames = TRUE)

# set column widths
setColWidths(wb, sheet = 1, cols = LETTERS[0:ncol(df)+1], widths = c(20, rep(10, ncol(df))))

# header style
header_style <- 
  createStyle(fontSize = 10, fontColour = "white", halign = "left", fgFill = "#0070C0", textDecoration = "bold")

addStyle(wb, sheet = 1, header_style, rows = 1, cols = 0:ncol(df)+1, gridExpand = TRUE)

# row names (style same as header)

addStyle(wb, sheet = 1, header_style, rows = 1:nrow(df)+1, cols = 1, gridExpand = TRUE)


# table body style
table_body_style1 <- 
  createStyle(fontSize = 10, fgFill = "#8DB4E2")

addStyle(wb, sheet = 1, table_body_style1, rows = seq(2, nrow(df)+1, by = 2), cols = 1:ncol(df)+1, gridExpand = TRUE)

table_body_style2 <- 
  createStyle(fontSize = 10, fgFill = "#DAEEF3")

addStyle(wb, sheet = 1, table_body_style2, rows = seq(3, nrow(df)+1, by = 2), cols = 1:ncol(df)+1, gridExpand = TRUE)

# save workbook
saveWorkbook(wb, "df.xlsx", overwrite = TRUE)

reprex 包(v2.0.0)于 2021-09-19 创建

在此处输入图像描述

于 2021-09-19T21:19:42.777 回答