我正在开发一个项目,需要从特定类型的数据框架自动生成数据电子表格。我读过关于如何执行此操作的有用解释here http://www.sthda.com/english/wiki/r-xlsx-package-a-quick-start-guide-to-manipulate-excel-files-in-r#create-and-format-a-nice-excel-workbook,并根据这个解释,我在中创建了一些代码R.Studio
(专业版1.1.383)使用xlsx
包(版本 0.5.7)。我的代码从现有数据框中生成数据电子表格TABLE
。这是我正在使用的代码,其中使用模拟数据框来创建可重现的示例:
#In this code we create a mock data frame called TABLE
#In practice we have a larger data frame with data that is not reproduced here
TABLE <- data.frame(Var1 = c(1, 6, 3, 9, 10, 4, 3, 5, 2, 2),
Var2 = c(18.1, 14.2, 12.0, 21.3, 33.4, 16.0, 15.4, 8.6, 6.7, 12.9),
Var3 = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 0));
#Create workbook, sheet, columns and styles
WB <- createWorkbook(type = "xlsx");
SHEET <- createSheet(WB, sheetName = "My Data");
rows <- createRow(SHEET, rowIndex = 1:5);
cells <- createCell(rows, colIndex = 1:(1+ncol(TABLE)));
STYLE_TITLE <- CellStyle(WB) +
Font(WB, name = "Calibri", heightInPoints = 16,
color = "black", isBold = TRUE, isItalic = FALSE);
#Add data from data frame TABLE
addDataFrame(TABLE, SHEET, startRow = 4L, startColumn = 2L,
colnamesStyle = STYLE_COLNAMES, row.names = FALSE);
#Add title
setCellValue(cells[[2, 2]], "This is my spreadsheet title");
setCellStyle(cells[[2, 2]], STYLE_TITLE);
#Save workbook
saveWorkbook(WB, "My Pretty Workbook.xlsx");
这段代码成功生成了我想要的电子表格,一切看起来都是我想要的,除了标题以白色字体出现,这意味着它们无法在电子表格的白色背景上看到。在我看来,这与我指定的代码部分相反Font
with color = "black"
。我也尝试过使用color = "#000000"
这得到了相同的结果。
为什么我的标题和信息文本以白色字体显示?我该如何解决?