从R

2016-08-15 55 views
3

正确的将日期写入Excel当我将数据框写入文件时,它将所有列视为包括日期列在内的字符。从R

options(xlsx.date.format = "yyyy-mm-dd") 
write.xlsx(data, excel_filename, sheetName = "Data") 

enter image description here

我怎样才能将数据写入XLSX文件,这样当我与此列其视为默认日期工作?

解决方案:打开列的类是字符。经过as.Date转换后,一切都妥善保存。

+0

它应该代替是['选项(openxlsx.dateFormat = “YYYY-MM-DD”)'](https://cran.r-project.org/web/packages/openxlsx/vignettes/formatting .PDF)? – r2evans

+1

http://stackoverflow.com/questions/23295571/how-to-prevent-write-csv-from-changing-posixct-dates-and-times-class-back-to-ch,这有帮助吗? – user5249203

+0

@ r2evans没有工作:( –

回答

2

您可以尝试使用lubridatechron库执行此任务。不过,我认为你的问题不是来自R,而是更多的是由于excel是如何读取它的。在你的问题中,你展示的图像是你想要的样子,还是它目前的样子?在任何情况下,例如使用chron时,可以说

format.Date(dates, "%Y/%m/%d") 
2

xlsx的参考手册用示例非常清楚地解释了它。下面是一个稍微修改的资料来源:https://cran.r-project.org/web/packages/xlsx/xlsx.pdf 我想,你是在按照相同的方法。使用工作簿保存日期的格式。

wb <- createWorkbook(type="xlsx") 
sheet <- createSheet(wb, sheetName="addDataFrame1") 
data <- data.frame(date=seq(as.Date("1999-01-01"), by="1 year", length.out=10)) 
addDataFrame(data, sheet, startRow = 1, startColumn=1) 
# to change the default date format use something like this 
options(xlsx.date.format="dd MMM, yyyy") 
# Don't forget to save the workbook ... 
saveWorkbook(wb, "Path/test.xlsx") # your path to the excel sheet