matlab使用activex接口自动保存excel文件

时间:2012-04-13 02:15:07

标签: excel matlab activex

我在matlab中有一个代码。运行程序后,创建了一个文件'example2.xlsx'。

现在我有了下面的代码,我希望matlab用新的'example2.xlsx'替换当前的'example2.xlsx'(自动保存而不询问我是否要替换它):

e = actxserver ('Excel.Application'); % # open Activex server
filename = fullfile(pwd,'example2.xlsx'); % # full path required
ewb = e.Workbooks.Open(filename); % # open the file
esh = ewb.ActiveSheet;


str = num2str(num_rows+1);
esh.Range(strcat('J',str)).Interior.Color = clr;

sheet1 = e.Worksheets.get('Item', 'Sheet1');
range1 = get(sheet1,'Range', strcat('A',str),strcat('I',str));
range1.Value = values{num_rows+1};

[num, txt, raw] = xlsread('example2.xlsx');
num_rows = length(num(:,1));


xlWorkbookDefault = 51; % # it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(fullfile(pwd,'example2'), xlWorkbookDefault)
ewb.Close(false)
e.Quit
e.delete

1 个答案:

答案 0 :(得分:6)

您可以将Excel应用程序对象的DisplayAlerts属性设置为false,以阻止显示这些对话框。

以下是您的代码的简化版本:

e = actxserver ('Excel.Application'); % # open Activex server
filename = fullfile(pwd,'example2.xlsx'); % # full path required
ewb = e.Workbooks.Open(filename); % # open the file
esh = ewb.ActiveSheet;

sheet1 = e.Worksheets.get('Item', 'Sheet1');
range1 = get(sheet1,'Range', 'A1');
range1.Value = 3;

set(e, 'DisplayAlerts', 0); % # Stop dialog!

xlWorkbookDefault = 51; % # it's the Excel constant, not sure how to pass it other way
ewb.SaveAs(fullfile(pwd,'example2'), xlWorkbookDefault)
ewb.Close(false)
e.Quit
e.delete