MATLAB: Displaying a linebreak in Excel without using xlswrite

excelMATLABwritecellxlswrite

I want to write som text into Excel, and I want a linebreak so that the cell in Excel don't have to be very wide to display all of the text.
I try with the following code:
% The variable 'period' has some text that I want to show in a cell in an Excel spreadsheet.
period = '2020-01-01 - 2020-12-31';
% I add a linebreak
cellContents = {sprintf([period(1:13) '\n' period(14:end)])};
% I write the text into Excel files using two different methods
xlswrite('FirstFile.xls', cellContents)
writecell(cellContents, 'SecondFile.xls')
When opened in Excel, 'FirstFile.xls' gives the result that I want. (I just have to adjust the column width, but I can do that using actxserver.) However, it uses the function xlswrite which is not recommended (and which gives me other problems).
When I open 'SecondFile.xls' in Excel, it shows the text without any linebreak. But the linebreak is there, if I go to that cell and press F2 and then Enter the text is displayed as I want it to. But I don't want to have to do anything manually like that.
Can I use actxserver to programmatically do something like "F2 and Enter"? Or do you have any other ideas how the text can be shown with linebreak in excel, without having to do anything manually and without having to use xlswrite?

Best Answer

I found a solution myself on how to do it with actxserver:
Excel = actxserver('excel.application');
WB = Excel.Workbooks.Open('C:\Temp\SecondFile.xls',0,false);
WB.Worksheets.Item(1).Range("A1").WrapText = true;
WB.Save();
WB.Close();
Excel.Quit();
Related Question