Trying to Insert Charts to specific Excel Sheets

6 views (last 30 days)
I am attempting to write a code that will insert charts into a varying number of sheets in excel. The format of each sheet is consistent, just different numbers. This is what I have so far:
Excel = actxserver('Excel.Application');
File = '\data_atmospheric.xlsx';
RT_number = 1917
ResultFile = [pwd File];
Workbook = invoke(Excel.Workbooks,'Open', ResultFile);
Sheet = invoke(Excel.Workbooks);
set(Excel, 'Visible' ,1);
Chart = Excel.ActiveSheet.Shapes.AddChart;
Chart.Name = 'ExperimentChart';
ExpChart = Excel.ActiveSheet.ChartObjects('ExperimentChart' );
ExpChart.Activate;
try Series = invoke(Excel.ActiveChart,'SeriesCollection',1);
invoke(Series,'Delete');
Series = invoke(Excel.ActiveChart,'SeriesCollection',1);
invoke(Series,'Delete');
Series = invoke(Excel.ActiveChart,'SeriesCollection',1);
invoke(Series,'Delete');
catch e
end
F= dir('*dat');
for ii = 1:length(F)
resultsheet = (F(ii).name);
NewSeries = invoke(Excel.ActiveChart.SeriesCollection,'NewSeries'); NewSeries.XValues = ['=' resultsheet '!A' int2str(3) ':A' int2str(999)]; NewSeries.Values = ['=' resultsheet '!B' int2str(2) ':B' int2str(999)]; NewSeries.Name = ['=' resultsheet '!B' int2str(1) ];
Excel.ActiveChart.ChartType = 'xlXYScatterLinesNoMarkers';
Axes = invoke(Excel.ActiveChart,'Axes',1); set(Axes,'HasTitle',1); set(Axes.AxisTitle,'Caption','Time(s)')
Axes = invoke(Excel.ActiveChart,'Axes',2); set(Axes,'HasTitle',1); set(Axes.AxisTitle,'Caption','RPM');
Excel.ActiveChart.HasTitle = 1; Excel.ActiveChart.ChartTitle.Characters.Text = 'RPM vs. Time';
ExpChart.Width = 350; ExpChart.Height= 200; ExpChart.Left= 300; ExpChart.Top= 50;
end
  2 Comments
Allen
Allen on 30 May 2021
Not sure how to directly add charts to specific worksheer, but it is fairly straightforward to add separate chartsheets to an Excel workbook. I provided an answer to a separate post explaing how to use programmatically setup new chartsheets and assign new dataseries to them. It may not be exactly what you are looking for, but possibly will work for you.

Sign in to comment.

Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!