How to specify format when writing to Excel?
조회 수: 37 (최근 30일)
이전 댓글 표시
I'm writing a big cell array to an Excel sheet, but two of my columns need work. Both my Date and Time columns are not being recognized as dates and times, so my filters are just match-based (instead of organizing from year > month > day > etc. it just lets you choose singular days).
If my cell array consists of data formatted as '02/27/2021 15:18:34' how do I make Excel display the date as: 02/27/2021 and the time as: 15:18:34? Both columns get the same data written into Excel, but the cells should display either the date or time.
The following lines don't do anything useful:
xlsWS.Columns.Item(2).NumberFormat = 'mm/dd/yyyy';
xlsWS.Columns.Item(3).NumberFormat = 'h:mm:ss;@';
This is what the Excel should look like:

I don't have much VBA experience. I appreciate any suggestions!
Thank you!
Bobby
댓글 수: 0
답변 (1개)
Image Analyst
2022년 2월 17일
You can either make up the Excel workbook in advance and format it exactly as you want it, then have MATLAB write into it.
Or you can get an ActiveX server and manually specify formatting, like the attached demo code shows.
댓글 수: 2
Image Analyst
2022년 2월 17일
You can use writecell(). Starting with a recent version (not sure which) it will retain the formatting you've set up in the existing workbook. Before that it used to blow away all your custom formatting.
You can either use writecell() or not. If you don't you can write stuff in with the ActiveX commands instead. Regardless if you use ActiveX before or after writecell(), it should maintain your formatting as long as you save your ActiveX changes to the file.
I'm sure you'll be able to learn ActiveX commands. If you ever need to do something new, not in my class, just go into Excel and record a macro and then see what code it recorded and try to transfer that to MATLAB.
참고 항목
카테고리
Help Center 및 File Exchange에서 Use COM Objects in MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!