How to write data into an excel file but keep the original formatting?
22 views (last 30 days)
Show older comments
How can I write values into my excel file without changing the formatting that already exists. specifically I want to keep the cell formulas and cell colours unchanged. This is what I have so far but it wipes out all formatting:
writetable(ResultMtx,Result_File);
1 Comment
Mathieu NOE
on 25 Aug 2021
hello
have you tried to protect your excel file before your write into it from matlab ?
Answers (1)
Image Analyst
on 25 Aug 2021
Edited: Image Analyst
on 25 Aug 2021
What release are you using? You forgot to enter it for some reason when you filled out the submission form. Yes that was a problem but I believe they fixed it now. Try release r2021a or later. If I recall correctly, it's no longer blowing away my formatting present in an already-existing workbook.
8 Comments
Image Analyst
on 15 Sep 2025
When you reply, there should be an icon that looks like a paperclip. Use that. If you see an INSERT icon with a downward pointing arrow, then click on that.
Leo
on 13 Oct 2025 at 3:01
Hello. Sorry for the delayed response - I'll check that email account regularly in future.
So, I've attached two Excel sheets. The first shows the original formatting in each of the sheets - just a copy of "ReadSheet". The second, "..._After", shows the formatting after I use the code below to test writecell, writetimetable, writematrix, and xlswrite . Only the latter leaves the original formatting unchanged.
cd('C:\MATLAB\MatLabTesting')
clc
clear
%% Read data as cells, timetable, and Excel data.
Test1=readcell('ExcelFormatTest.xlsx','Sheet','ReadSheet','Range','E10:K40');
Test2=readtimetable('ExcelFormatTest.xlsx','Sheet','ReadSheet','Range','E10:K40');
Test3=readmatrix('ExcelFormatTest.xlsx','Sheet','ReadSheet','Range','F11:K40');
disp('Finished reading.')
%% Write cells.
writecell(Test1,'ExcelFormatTest.xlsx','Sheet','writecell','Range','E10','PreserveFormat',true);
disp('Finished writing cells.')
%% Write timetable.
writetimetable(Test2,'ExcelFormatTest.xlsx','Sheet','writetimetable','Range','E10','PreserveFormat',true);
disp('Finished writing timetable.')
%% Write matrix. Note: only writes data, leaving dates and headings.
Matrix=Test2.Variables;
writematrix(Test3,'ExcelFormatTest.xlsx','Sheet','writematrix','Range','F11','PreserveFormat',true);
disp('Finished writing matrix.')
%% Write Excel data. Note: only writes data, leaving dates and headings.
xlswrite('ExcelFormatTest.xlsx',Matrix,'xlswrite','F11:K40');
disp('Finished writing Excel data.')
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!