如何在openxlsx生成的XLSX中按年,月,日过滤

时间:2019-03-18 15:51:46

标签: r csv filter xlsx 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 是逗号分隔的值文件。看起来像这样:

CSV file view

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

CSV Date column with filter

但是,当我使用过滤器创建XSLX文件时,这种过滤器如下所示:

XLSX Date column with filter

可以看出Excel正在按绝对值进行过滤,并且没有按年,月和/或日对日期进行分组。

我怎么了?

1 个答案:

答案 0 :(得分:1)

您需要对代码进行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)