简体   繁体   中英

Matlab : Copy Excel Sheet and Save Workbook

I would like to copy multiple sheets from an existing workbook to a new one. Here is my code, I can copy the sheets but I am not able to save the workbook properly.

In my following code, I copy the first three sheets and save the workbook but when I open it, it is empty. I think my workbook handle is wrong.

Excel = actxserver('Excel.Application');
Excel.Visible = true;

WB = invoke(Excel.Workbooks,'open','C:\Example.xlsx');
SHS = WB.Sheets; %sheets of template Workbook
SH = WB.Worksheets.Item(3); 
invoke(SH,'Copy');
SH = Excel.ActiveSheet; 
SH1 = WB.Worksheets.Item(2);
SH2 = WB.Worksheets.Item(1);
invoke(SH2,'Copy',SH);
invoke(SH1,'Copy',SH);
SH = Excel.ActiveSheet;
nWB = Excel.ActiveWorkbook;
nWB.SaveAs('C:\TEST.xlsx',1)
Excel.Quit()

For horizontal concatenation of sheets

Step 1: Make one cell array containing repetitions of your filename (same number as number of sheets you want to combine), and one cell array with numbers of the sheets. Then use cellfun to read all sheets.

Step 2: Define from which column you would like to write data. The first sheet you read should be written from column 'A' I suppose. You probably want to start on the first line, so range is 'A1' first time (ie k = 1 ) you write data to your new file. For k > 1 it's a bit more tricky. You need to keep to track on the number of columns of all sheets you read, in order to know where the new range will be when you write sheet 2, 3, ... , n in your new file. Convert your count to Excel column names. This can be done with the char command. Make sure to take care of the wrapping (After Z comes AA).

Solution:

% STEP 1
n = 3; %number of sheets you want to combine
filename = strcat(cell(1,n), 'C:\Example.xlsx');
sheets = num2cell(1:n);
combinedSheets = cellfun(@xlsread,filename, sheets,'un',0);

% STEP 2
range = {'A1'};
cols = 0;
for k = 1:n
    xlswrite('C:\TEST.xlsx',combinedSheets{k},1, cell2mat(range))
    cols = cols + size(combinedSheets{k},2);
    q = floor(cols/26);
    d = mod(cols,26);
    range = strcat(cell(1,q+1), 'A');
    range{end} = [char(d+'A'),'1'];
end

For vertical concatenation of sheets

This is a bit simpler as we do not need to handle column names and wrapping etc.

Solution:

n = 3; %number of sheets you want to combine
filename = strcat(cell(1,n), 'C:\Example.xlsx');
sheets = num2cell(1:n);
combinedSheets = cellfun(@xlsread,filename, sheets,'un',0);

range = 'A1';
rows = 1;
for k = 1:n
    xlswrite('C:\TEST.xlsx',combinedSheets{k},1, range)
    rows = rows + size(combinedSheets{k},1);
    range = sprintf('A%s', num2str(rows));
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM