使用 openxlsx 将日期写入 excel sheet 作为具有自定义样式的日期格式

Write dates to excel sheet as date format with custom styles using openxlsx

我在excelsheet中写代码如下:

wb <- createWorkbook("wb_Object1")

addWorksheet(wb, "Report_MicronV1", gridLines = TRUE)

writeData(wb, sheet = "Report_MicronV1", Report_Micron, rowNames = FALSE)

setColWidths(wb, "Report_MicronV1", cols = 1:length(Report_Micron[1,]), widths = 15)

headerS <- createStyle(
           fontSize = 12,
           textDecoration = "bold",
           fontColour = "#0F0E0E",
           halign = "left",
           valign = "center",
           fgFill = "#FCF707",
           border = "TopBottom",
           borderColour = "#22FC07",
           borderStyle = "thick",
           wrapText = TRUE)

bodyS <-  createStyle(
          fontSize = 9,
          textDecoration = "bold",
          fontColour = "#0F0E0E",
          halign = "left",
          border = "TopBottom",
          borderColour = "#d7dcde")

 addStyle(wb, sheet = 1, headerS, rows = 1, cols = 1:length(Report_Micron[1,]), gridExpand = 
          TRUE)

 addStyle(wb, sheet = 1, bodyS, rows = 2:nrow(Report_Micron), cols = 
          1:length(Report_Micron[1,]), gridExpand = TRUE)

 saveWorkbook(wb, "Report_MicronV1.xlsx", overwrite = TRUE)

预期输出为“mm/dd/yyyy”

但是R是这样写的(参考屏幕打印)

请帮忙

excel sheet 的屏幕截图,由 R:

编写

问题是添加样式时日期格式被覆盖。要解决这个问题,首先添加样式,然后将数据写入工作簿:

调整来自 openxlsx 的默认示例:

library(openxlsx)

dates <- data.frame("d1" = Sys.Date() - 0:4)
for(i in 1:3) dates <- cbind(dates, dates)
names(dates) <- paste0("d", 1:8)
dates$d1 <- "Text"
dates$d2 <- 1:5

## Date Formatting
wb <- createWorkbook()

addWorksheet(wb, "Date Formatting", gridLines = FALSE)

setColWidths(wb, 1, cols = 1:length(dates[1,]), widths = 15)

headerS <- createStyle(
  fontSize = 12,
  textDecoration = "bold",
  fontColour = "#0F0E0E",
  halign = "left",
  valign = "center",
  fgFill = "#FCF707",
  border = "TopBottom",
  borderColour = "#22FC07",
  borderStyle = "thick",
  wrapText = TRUE)

bodyS <-  createStyle(
  fontSize = 9,
  textDecoration = "bold",
  fontColour = "#0F0E0E",
  halign = "left",
  border = "TopBottom",
  borderColour = "#d7dcde")

addStyle(wb, sheet = 1, headerS, rows = 1, cols = 1:length(dates[1,]), gridExpand = 
           TRUE)

addStyle(wb, sheet = 1, bodyS, rows = 2:(nrow(dates) + 1), cols = 
           1:length(dates[1,]), gridExpand = TRUE)

writeData(wb, 1, dates) ## write without styling

saveWorkbook(wb, "date.xlsx", overwrite = TRUE)