我在MATLAB中生成了一个excel文件,并使用以下命令成功保存和关闭:
invoke(Workbook,'Save')
invoke(Excel,'Quit');
delete(Excel);
clear Excel;
但是,当我使用PlotInExcel将图形添加到excel文件中时,我无法再次使用相同的代码保存和关闭该文件。这是PlotInExcel:
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----------
如何让MatLab立即保存此文件并退出?上面提到的代码现在不起作用了。有没有办法给函数添加代码?或者我可以/应该在脚本中保存/关闭函数外的文件?
经过足够的抨击,我终于能够回答自己的问题了。如果其他人有这个问题,我会在这里发布解决方案。我一开始删除了这些行,因为它们只是生成了一个测试图。下面的函数假设你有自己的图,你想粘贴到excel电子表格中。顺便说一句,在运行此功能之前,您必须将您的数字保存到剪贴板。
function PlotInExcel
FILE = 'C:DATA.xlsx'; %identify the name and location of your excel spreadsheet
Range='R1'; %select where you want your figure pasted in the speadsheet (cell ID)
%.............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
Excel.ActiveWorkbook.Save % Now save the workbook
if eq(Excel.ActiveWorkbook.Saved,1)
Excel.ActiveWorkbook.Close;
else
Excel.ActiveWorkbook.Save;
end
invoke(Excel, 'Quit'); % Quit Excel
delete(Excel); % End process
end