0

我已经开始通过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 文件视图

如果我在 Date 列中添加一个过滤器,它将如下所示:

带过滤器的 CSV 日期列

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

带过滤器的 XLSX 日期列

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

我在做什么错?

4

1 回答 1

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) 
于 2019-03-18T16:29:12.507 回答