How do I write data to an Excel Spreadsheet with a custom cell background color and custom font color via MATLAB?
19 ビュー (過去 30 日間)
古いコメントを表示
MathWorks Support Team
2009 年 6 月 27 日
編集済み: MathWorks Support Team
2023 年 4 月 13 日
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
2023 年 4 月 10 日
編集済み: MathWorks Support Team
2023 年 4 月 13 日
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)
wb=h.WorkBooks.Add();
%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
%BLUE= FF00FF
%GREEN=00FF00
%BLACK=000000
%WHITE=FFFFFF
ran.interior.Color=hex2dec('00FF00'); %Green
ran.font.Color=hex2dec('FF0000'); %Blue
% save the file with the given file name, close Excel
wb.SaveAs(file);
wb.Close;
h.Quit;
h.delete;
end
Example invocation:
xlscolor('Tone.xls',rand(5,5),'A1:E5')
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 to the following documentation:
For MATLAB R2017b:
1. ACTXSERVER:
>> web(fullfile(docroot, 'matlab/ref/actxserver.html'))
2. MATLAB software as an Automation client and the Microsoft® Excel® spreadsheet program as the server:
>> web(fullfile(docroot, 'matlab/matlab_external/supported-client-server-configurations.html#bq9yam7-8')
For the latest release documentation:
1. ACTXSERVER:
2. MATLAB software as an Automation client and the Microsoft® Excel® spreadsheet program as the server:
Information on the hexadecimal notation of colors values (IMPORTANT: please note, Microsoft uses BGR ordering as opposed to the RGB notation explained below)
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Use COM Objects in MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!