Displaying a linebreak in Excel without using xlswrite
17 views (last 30 days)
Show older comments
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?
2 Comments
dpb
on 14 Aug 2020
You can do whatever with ActiveX or just use xlswrite if it behaves more as desired; just because it has been deprecated doesn't preclude using it for specific reasons. Alternatively, you could try writetable and see if it behaves any differently than writecell
Accepted Answer
More Answers (1)
David Grilli
on 3 May 2022
Here, when doing writecell or writetable, add 'UseExcel',true to the function call and it'll start an instance of Excel to create the table. It'll take care of wrapping the line breaks.
So writecell(cellContents,fileName,'UseExcel',true)
0 Comments
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!