Clear Filters
Clear Filters

Is it possible to specify an output data format (ex: hh:mm:ss versus "custom") for xlswrite?

3 views (last 30 days)
Hello, I am using MATLAB to parse through hundreds of .txt files, build arrays, and export that array into excel (basically convert the data from .txt to excel for ease of use). The text data being read in from Notepad is a time in the form of '###:##:##.##' (h:m:s). The number is correctly read into Matlab in the correct format. My problem is, when I export this number to Excel, the format changes to a custom format of mm:ss:0. Now I have to manually change the final format in Excel to h:m:s. The number is correct, the format is wrong.
Question is: Is there a way to prevent this format change or have Matlab specify the format of data being exported to Excel?
Thanks!

Answers (2)

Image Analyst
Image Analyst on 11 Aug 2016
Why/how does the text from the Notepad file get converted to a number anyway? Do you need to? Why can't you just leave it as a string? If you need it as a number internally in your MATLAB program, and converted it with datenum, I still think you could keep the original string for later export to Excel. I think that's what I'd recommend.
Alternatively, if you have date numbers, you could convert them to a string with datestr() and then stick those strings into a cell array and write the cell array out.
Another option is to make an Excel workbook up in advance with the proper cell formatting. Then you just call xlswrite to that existing workbook (don't delete it first!) and the numbers will appear with the predefined format you set up.
Finally, the most flexible and powerful, but most complicated, is to use ActiveX to directly control Excel from MATLAB. If you want to go that route, I've attached a demo. Not for setting cell formatting, but just ActiveX in general. To figure out what you need to do you need to record a macro in Excel where you format the cells to the date appearance that you like, then look at the macro that got recorded, and transfer those commands over to your MATLAB code. I use ActiveX all the time, but it has a shallow learning curve (amount learned vs. time is low), not a steep learning curve (amount learned vs. time is high). But if you're up for it, give it a try - it's worth learning.

Walter Roberson
Walter Roberson on 10 Aug 2016
Not using xlswrite(), no. You would need to use activex() to connect with Excel and have Excel modify the format of the cells.

Community Treasure Hunt

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

Start Hunting!