如何允许在 openxlsx 生成的 XLSX 中按年、月、日过滤

How to allow filtering by year, month, date in XLSX generated by openxlsx

我已经开始通过 openxlsx 生成 XLSX 文件而不是 CSV。但是,我在日期过滤方面遇到了不同的行为。

我生成了以下虚拟代码:

library(openxlsx)

df <- data.frame(ID=c(1,2,3,4,5,6), Date=c("1900-01-12","2010-12-29","1934-03-17", "1989-09-19","1978-11-27","2010-01-13"))

write.csv(df, "dateTestCSV.csv")

# Create the workbook
wb = createWorkbook()

hs <- createStyle(fontColour = "#ffffff", fgFill = "#4F80BD",
                  halign = "center", valign = "center", textDecoration = "bold", 
                  border = "TopBottomLeftRight")

addWorksheet(wb=wb, sheetName = "Test", gridLines=T, zoom=70)

writeData(
  wb,     
  sheet = "Test",
  x = df,
  withFilter=T,
  borders="all",
  borderStyle="thin",
  headerStyle=hs
)       

setColWidths(wb, sheet = "Test", cols=1:ncol(df), widths = "auto")

openxlsx::saveWorkbook(wb, "dateTestXLSX.xlsx", overwrite=T)

生成的第一个文件 dateTestCSV.csv 是逗号分隔值文件。看起来如下:

如果我向“日期”列添加过滤器,它将如下所示:

但是,当我使用过滤器创建 XSLX 文件时,此类过滤器看起来如下所示:

可见Excel是按绝对值过滤,并没有按年月and/or日分组。

我做错了什么?

您需要对代码进行如下 2 处更改,过滤器应该可以正常工作:

df <- data.frame(ID=c(1,2,3,4,5,6), 
   Date=c("1900-01-12","2010-12-29","1934-03-17", "1989-09-19","1978-11-27","2010-01-13"),
   stringsAsFactors = F) # Ensure your dates are initially strings and not factors

# Actually convert the character dates to Date before writing them to excel
df$Date <- as.Date(df$Date)