MATLAB: How to apply conditional formatting to an Excel spreadsheet via MATLAB

MATLAB

I would like to add conditional formatting to cells based upon data computed in MATLAB. Is it possible to do this with "writetable" or ACTXSERVER?

Best Answer

As of R2020b, there is no built-in functionality to apply conditional formatting to cells via "writetable"; however, you can achieve this through ACTXSERVER as follows:
Suppose that we have a file, "data.xls" and would like to set any cell in the range "A1:J10" to read if its value is over the threshold of 5. This could be accomplished using code like:
%% Create an XLS file
data = repmat(1:10,10,1);
fname = 'data.xls';
xlswrite(fname, data);
%% Open the workbook, select a range and show Excel
Excel = actxserver('Excel.Application');
Excel.Workbooks.Open(fullfile(pwd, fname));
Range= Excel.Range('A1:J10');
Excel.Visible = 1;
%% Set the cells to red if they are over 5
valueType = 1;
operatorIndex = 5;
maxVal = 5;
Range.FormatConditions.Add(valueType, operatorIndex, maxVal).Interior.ColorIndex = 3;
%% Save and close the file
Excel.ActiveWorkbook.Save()
Excel.Quit()