How can I open an existing Excel file and communicate with it using ActiveX?

조회 수: 143(최근 30일)
MathWorks Support Team
MathWorks Support Team 2009년 6월 27일
답변: Pruthvi G 2020년 4월 13일
I would like an example where ActiveX is used to open an existing spreadsheet to perform read and write operations. I would like to manipulate the data in Excel and then retrieve such changes in MATLAB without having to resave the spreadsheet.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2009년 6월 27일
This bug has been fixed in Release 14 Service Pack 3 (R14SP3). For previous product releases, read below for any possible workarounds:
The following provides an example of opening an existing Excel file named example.xls and proceeding to write and read with it:
% Specify file name
file = 'D:\Applications\MATLAB701\work\example.xls'; % This must be full path name
% Open Excel Automation server
Excel = actxserver('Excel.Application');
Workbooks = Excel.Workbooks;
% Make Excel visible
% Open Excel file
% Specify sheet number, data, and range to write to
data=rand(4); % use a cell array if you want both numeric and text data
range = 'F10:I13';
% Make the first sheet active
Sheets = Excel.ActiveWorkBook.Sheets;
sheet1 = get(Sheets, 'Item', sheetnum);
invoke(sheet1, 'Activate');
Activesheet = Excel.Activesheet;
% Put MATLAB data into Excel
ActivesheetRange = get(Activesheet,'Range',range);
set(ActivesheetRange, 'Value', data);
% Here you might manipulate the data in Excel
% Now read the data from the sheet; you could specify a new range here
Range = get(Activesheet,'Range',range);
out = Range.value;
% Save file
% Close Excel and clean up
clear Excel;

추가 답변(1개)

Pruthvi G
Pruthvi G 2020년 4월 13일
% Name : xl_xlsfinfo
% Author : Pruthvi Raj G
% Version : Version 1.0 - 2011b Compactible
% Description : Finds all the sheets in the Excel file (.xls,.xlsm,.xlsx)
% Input : File_Name with path included.
% Date : 11-Feb-2020
% Examples : xl_xlsfinfo('D:\Pruthvi\Test_file.xls')
Use the Below Lines of Code ::
sheets = xl_xlsfinfo('D:\Pruthvi\Test_file.xls')
sheets =
1×5 cell array
{'Sheet1'} {'Sheet2'} {'Sheet3'} {'Sample'} {'Data'}

Community Treasure Hunt

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

Start Hunting!

Translated by