How do I insert a MATLAB figure into an Excel Workbook through ActiveX?
79 views (last 30 days)
Show older comments
MathWorks Support Team
on 25 Feb 2010
Edited: Kevin Gleason
on 11 Apr 2017
I would like to paste a figure into a workbook directly from an MATLAB file.
Accepted Answer
MathWorks Support Team
on 25 Feb 2010
This change has been incorporated into the documentation in Release 14 Service Pack 3 (R14SP3). For previous releases, read below for any additional information:
You can put a MATLAB figure into Excel using ActiveX. Here is an example that demonstrates two alternatives:
% Create sample image from figure
img = 'figure1.png';
plot(1:10);
print('-dpng', img);
% Get handle to Excel COM Server
Excel = actxserver('Excel.Application');
% Set it to visible
set(Excel,'Visible',1);
% Add a Workbook
Workbooks = Excel.Workbooks;
Workbook = invoke(Workbooks, 'Add');
% Get a handle to Sheets and select Sheet 1
Sheets = Excel.ActiveWorkBook.Sheets;
Sheet1 = get(Sheets, 'Item', 1);
Sheet1.Activate;
% Alternative 1 BEGIN.
% Get a handle to Shapes for Sheet 1
Shapes = Sheet1.Shapes;
% Add image
Shapes.AddPicture([pwd '\' img] ,0,1,400,18,300,235);
% Alternative 1 END.
% Alternative 2 BEGIN.
% Add image
Sheet1.invoke('Pictures').Insert([pwd '\' img]);
% Alternative 2 END.
% Save the workbook and Close Excel
invoke(Workbook, 'SaveAs', [pwd '\myfile.xls']);
invoke(Excel, 'Quit');
In the above code (Alternative 1), Excel's Shapes.AddPicture Method is used to insert a figure in the Excel Sheet. The syntax for AddPicture is:
expression.AddPicture(Filename, LinkToFile, SaveWithDocument, Left, Top, Width, Height), where expression is a variable that represents a Shapes object.
1 Comment
Kevin Gleason
on 11 Apr 2017
Edited: Kevin Gleason
on 11 Apr 2017
You can get "Workbook" to be the existing book using the code in the link above, then insert the figure the same way as this answer tells.
More Answers (0)
See Also
Categories
Find more on Use COM Objects in MATLAB 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!