How do you insert the date and time as the file name when using xlswrite?

121 次查看(过去 30 天)
Hi all,
I have seen solutions to this question but they don't appear to work when I try implementing them.
I want to create an Excel file using xlswrite, the data for the file are in a matrix called 'a'. In the matrix are data called from a server at specific times by a for loop. The loop runs for 1 hour and the halts. I want to write these data before the process starts again. I don't want to overwrite the file on the next run so I want to use xlswrite to export the data and by using the date and time in the file name each file will have a unique name.
I call the date and time using the datestr(now) function.
%%This writes a file with my data, but the file name is 'FileName'
FileName=sprintf('FileName_%s.xlsx',datestr(now)); xlswrite('FileName', a)
%%This does not work FileName=sprintf('FileName_%s.xlsx',datestr(now)); xlswrite(FileName, a)
Any help in doing this would be greatly appreciated.
Thanks,
Lucas

采纳的回答

Ralf
Ralf 2016-1-29
Hi Lucas, that's because datestr(now) creates characters like colon (:) which are not allowed for file names. You should define your own date and time Format without These characters. Try
Filename = sprintf('test_%s.xlsx', datestr(now,'mm-dd-yyyy HH-MM'));
xlswrite(Filename, a)
That will work.
  2 个评论
Lucas
Lucas 2016-1-29
Many thanks for your help Ralf. That works perfectly well, you have saved me a lot of time!
Luke
Stephen23
Stephen23 2016-1-29
编辑:Stephen23 2016-1-29
You might also like to consider using an ISO 8601 timestamp, which has the significant advantage that the dates then sort into the correct order when the filenames are sorted. ISO 80601 is simply the best date format: unambiguous, sortable and readable.
To make it easy to use ISO 8601 dates and timestamps you could use my FEX submission datestr8601. By default datestr8601 uses the current time and returns the basic ISO 8601 calendar notation timestamp: this is very useful for naming files that can be sorted ASCIIbetically into chronological order!
>> datestr8601
ans =
20160129T161425
>> sprintf('test_%s.txt',datestr8601)
ans =
test_20160129T161450.txt
>> sprintf('test_%s.txt',datestr8601(now,'ymd'))
ans =
test_20160129.txt

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by