how to paste figure to excel file and then save and exit excel?
Show older comments
I generated an excel file in my MatLab script, added data to it, and then using PlotInExcel (below), I have added a figure:
function PlotInExcel
x= {1:10};
a= cell2mat(x);
y= {1:10};
b= cell2mat(y);
%............plotting..............................................................................................
plot(a,b);
xlabel('X Values');
ylabel('Y Values');
print -dmeta; %.................Copying to clipboard
FILE = 'C:DATA.xlsx';
Range='OL14';
%.............excel COM object............................................................................
Excel = actxserver ('Excel.Application');
Excel.Visible = 1;
if ~exist(FILE,'file')
ExcelWorkbook=Excel.Workbooks.Add;
ExcelWorkbook.SaveAs(FILE);
ExcelWorkbook.Close(false);
end
invoke(Excel.Workbooks,'Open',FILE); %Open the file
ActiveSheet = Excel.ActiveSheet;
ActiveSheetRange = get(ActiveSheet,'Range',Range);
ActiveSheetRange.Select;
ActiveSheetRange.PasteSpecial; %.................Pasting the figure to the selected location
%-----------------------------------end of function"PlotInExcel--------------------------------------
Now I want to add a second figure to another Range (so it doesn't overwrite the first figure). But if I don't manually Save and Exit the Excel file before re-running PlotInExcel (with a new Range, of course), PlotInExcel merely erases the first figure and adds the second one. Yet, if I manually save/exit my Excel file, PlotInExcel with the new range works fine.
How can I either (1) edit the above PlotInExcel functon to Save/Exit my excel file after adding a figure, or (2) edit my script to Save/Exit the excel file after running PlotInExcel?
I should add that the following, which worked well before I included PlotInExcel, worked fine to save my file:
invoke(Workbook,'Save') % Save file
invoke(Excel,'Quit'); % Close Excel and clean up
delete(Excel);
clear Excel;
..but no longer does the trick.
Accepted Answer
More Answers (1)
Ayush Gupta
on 1 Sep 2020
The problem is arising because at the end of the function, once the graph is pasted to the excel file, it is not saved and directly exit from the program which is the main issue behind this. Refer to the following code for a work-around.
xls = xl.Workbooks.Open('myexcelfile.xlsx'); % Open specific document
% Perform functions like attach graphs to it or do anything
xls.Save; % Save the document
xl.Quit; % Close the document
xl.delete; % Remove Excel reference to allow the document to be opened independently
1 Comment
Stephen
on 2 Sep 2020
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!