Replacing an image in excel
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello everyone, I know how to write an image to a specific location/cell in Excel using Matlab, but I am having a really hard time finding or building a script that can exchange a specific image on a specific sheet.
Here's the first bit of code:
%Start Active X Server
xlApp = actxserver('Excel.Application');
xlApp.visible = 1;
%Open the the spreadsheet
xlworkbook = xlApp.Workbooks.Open([pwd,'\New.xls']);
%Select sheet:
Sheet = get(xlworkbook.Sheets,'Item',7); % sheet
Sheet.Select;
%Work in Sheet
xlsheet = xlworkbook.ActiveSheet;
xlsheet.Shapes.Item(1).Select
As can be seen, using the Activex commands, I was able to get as far as selecting the specific shape on a sheet, but after that I'm stuck, as I can't find any proper documentation on how to replace the selected image (i.e. .shape).
Thanks a lot!
2 commentaires
Kevin Chng
le 7 Sep 2018
I'm not sure. Do you mind try this?
xlsheet.Shapes.Fill.UserPicture ("C:\image.png")
I'm not sure. however, sometimes, i will take this link as guideline.
Réponse acceptée
Guillaume
le 7 Sep 2018
First, avoids relying on ActiveAnything, it's a recipe for bugs. For example, with your code something (e.g. the user) could activate a different sheet between the moment you activate the 7th sheet and the moment you retrieve the active sheet. In your case, it's also a complete waste of time since, assuming that the active sheet doesn't change, what your code is doing is simply
xlsheet = Sheet; %in a roundabout way
With regards to your question, to replace a picture you have to delete the existing shape and create a new one.
xlApp = actxserver('Excel.Application');
xlApp.Visible = true; %optional
xlworkbook = xlApp.Workbooks.Open(fullfile(pwd, 'New.xls')); %prefer fullfile to building the path yourself
xlSheet = xlworkbook.Sheets.Item(7); %or xlSheet = get(xlworkbook.Sheets,'Item',7);
oldshape = xlSheet.Shapes.Item(1);
newshape = xlSheet.Shapes.AddPicture(picturefile, 0, 1, oldshape.Left, oldshape.Top, oldshape.Width, oldshape.Height);
oldshape.Delete;
xlworkbook.Close(true); %close and save changes
xlApp.Quit;
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Use COM Objects in MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!