How do I write data to an Excel Spreadsheet with a custom cell background color and custom font color via MATLAB?
187 views (last 30 days)
MathWorks Support Team on 27 Jun 2009
I have data that I want to write to a cell in an Excel Spreadsheet, but I also want to assign a background color and font color to this cell. I would like to know the way to do this through MATLAB.
MathWorks Support Team on 30 Apr 2021
Edited: MathWorks Support Team on 30 Apr 2021
This task can be accomplished using ActiveX with Excel. The following example function shows one way to do this:
function xlscolor(file, data, range)
%XLSCOLOR writes data like XLSWRITE
%but adds color options
% XLSCOLOR(FILE,DATA,RANGE) writes the variable in
% DATA to FILE, in the range specified by RANGE.
%Obtain the full path name of the file
file = fullfile(pwd, file);
%Open an ActiveX connection to Excel
h = actxserver('excel.application');
%Create a new work book (excel file)
%Select the appropriate range
ran = h.Activesheet.get('Range',range);
%write the data to the range
ran.value = data;
%The color is specified as an BGR triplet in hexadecimal notation
%RED = 0000FF
% save the file with the given file name, close Excel
For more information on programming with Excel (For example, the commands like 'Add'), please consult the "Microsoft Excel Visual Basic Reference" via Excel's help menu.
For further information please refer:
2. MATLAB software as an Automation client and the Microsoft® Excel® spreadsheet program as the server:
3. Information on the hexadecimal notation of colors values (IMPORTANT: please note, Microsoft uses BGR ordering as opposed to the RGB notation explained below)