MATLAB: How to create chart objects in Excel from MATLAB 7.8 (R2008a)

MATLAB

I want to create chart objects such as bar graphs in an excel sheet programmatically from inside MATLAB.

Best Answer

To be able to access or create chart objects in excel sheets, you have to communicate with Excel from MATLAB using COM. To do this, you will have to create an Automation server in MATLAB using the actxserver command and use COM API to talk to Excel. Once you establish this connection, you can use commands similar to the excel VBA editor to programmatically add or edit objects in excel sheet.
Here is an example on how you could access data in excel sheet and draw chart objects. The chart Book.xlsx that contains the data is attached.
excel = actxserver('excel.application');
excel.Visible = 1;
wkbk = excel.Workbooks.Open('<FullPath>\Book.xlsx');
wkbk.ActiveSheet;
wkbk.ActiveSheet.Shapes.AddChart.Select;
wkbk.ActiveChart.SetSourceData(wkbk.ActiveSheet.get('Range','A2:B4'))
wkbk.ActiveChart.ChartType = 'xlBarClustered';
wkbk.SaveAs('<FullPath>\Book2.xlsx'); % save the changes
wkbk.Close;
excel.Quit; % close excel
excel.delete;
The above API commands is provided by Microsoft Excel and for more specific information on these, refer to the Microsoft Excel's documentation page.