MATLAB Answers

Writing MATLAB image to Excel file at a specific position

202 views (last 30 days)
Homayoun on 26 Jun 2012
Answered: Noam Greenboim on 13 May 2019
I have a function like [summary,image1,image2,image3] = funca(x,y). I wonder how I can write each image to a separate sheet in an Excel workbook at a specific position. Thanks for your comments!

Answers (2)

Image Analyst
Image Analyst on 27 Jun 2012
MATLAB can't do this directly. You'd need to use ActiveX programming to call Excel API functions. Fortunately MATLAB can do that (make ActiveX calls). I don't recall doing that (stuffing images into Excel) so I don't have any demo code for you.
It's going to look somewhat similar to this:
% Open Excel file.
objExcel = actxserver('Excel.Application');
objExcel.Workbooks.Open(fullfile(excelFilePath, excelFileName)); % Full path is necessary!
oWB = objExcel.Workbooks.Add();
oSheet = oWB.ActiveSheet;
oSheet.Pictures.Insert("<< full path to image file >>").Select();
But you can look up ActiveX in Answers or elsewhere. Here's one example:
The Microsoft Excel methods you need are listed here:
This code may also be useful:
Image Analyst
Image Analyst on 24 Oct 2018
Strange - that is the command that gets recorded if you record a macro. But I was also able to reproduce the error. Not sure why it errored out but I found an alternate way. I've tested this and it works:
% Get the name of the workbook you want to paste a picture into.
folder = pwd;
excelFileName = 'PicturePaste.xlsx';
fullFileName = fullfile(folder, excelFileName);
if ~exist(fullFileName, 'file')
message = sprintf('Existing Excel workbook not found"\n%s', fullFileName);
% Open Excel as an ActiveX server.
objExcel = actxserver('Excel.Application');
objExcel.Visible = true;
% Open the workbook we want to paste the image onto.
ExcelWorkbook = objExcel.Workbooks.Open(fullFileName); % Full path is necessary!
% ExcelWorkbook = objExcel.Workbooks.Add(); % Add new, blank workbook.
oSheet = objExcel.ActiveSheet;
% oSheet.Range('A1').Select;
% Get the name of the image file.
imageFolder = fileparts(which('cameraman.tif')); % Determine where demo folder is (works with all versions).
imageFullFileName = fullfile(imageFolder, 'cameraman.tif')
% Get a handle to Shapes for Sheet 1
Shapes = oSheet.Shapes;
% Add image by importing one from an image file on disk.
Shapes.AddPicture(imageFullFileName, 0, 1, 400, 18, 300, 235);
% Save the workbook.
% Tell it to not wait and pop up alerts like "This file exists. Do you want to overwrite it."
objExcel.DisplayAlerts = false;
% Save this workbook we just created to disk. Image will be saved with the workbook.
% Close the workbook. Excel will still be open though.
objExcel.Quit; % Shut down Excel.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!