0

I need to export data to excel sheet with a specific name using Activex. Here is what I did: First i export the data to excel in first for loop and then modify the names of the sheet using second for loop. Can it be done even in one single for loop? I think there should be another better idea. Note: The size of the data varies.

try
    filename = fullfile(pwd,'example.xlsx');
    for i=1:5
        xlswrite(filename,[1 2;3 4]*i,i);
    end
    for i = 1:5
        myExcel = actxserver('Excel.Application');
        excelWorkBook = myExcel.Workbooks.Open(filename,0,false);
        excelWorkBook.Worksheets.Item(i).Name = ['new_sheet_' num2str(i)]; 
        excelWorkBook.Save;
        excelWorkBook.Close;
        myExcel.Quit;
    end

catch
    % Disp Error message.....
end

2 Answers 2

4

The xlswrite function also accepts a string as sheet parameter. So just replace your call by this one:

xlswrite(filename,[1 2;3 4]*i,['new_sheet_' num2str(i)]);
Sign up to request clarification or add additional context in comments.

Comments

1

Fratyx's answer is the simplest to implement, but a bit of knowledge of the Excel Object Model goes a long way, so here's how to implement your solution with ActiveX in one loop:

     e = actxserver('excel.application');
     w = e.Application.Workbooks.Add();
     numnewsheets = 4;
     for i = 1:numnewsheets
         w.Worksheets.Add([],w.Sheets.Item(w.Sheets.Count),1);
         w.Worksheets.Item(i).Name = ['new_sheet_' num2str(i)];
         w.Worksheets.Item(i).Cells.Range('A1:B2').Value = [1 2;3 4];
     end
     w.SaveAs(filename)
     w.Close
     e.Quit
     e.delete

To calculate the range required for the size of your data, you will have to open file "xlswrite" and copy out the sub-function "calcrange".

1 Comment

The range and the number of sheets are fixed in this case. How can I make it flexible. The size of the data varies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.