How can I append new columns to an existing Excel file with MATLAB?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 5K views
kelvin490
Gold Member
Messages
227
Reaction score
3
I would like to ask how to use MATLAB to append new columns into existing excel file without altering the original data in the file? In my case I don't know the original number of columns and rows in the file and it is inefficient to open the files one by one and check in practice. Another difficulty is that the new columns may have different number of rows to the existing data so that I cannot use the trick of reading in the data, forming a new matrix and replace the data with the new matrix.

I have seen many posts teaching people how to add new rows but adding new column seems quite a different thing since the columns are named by letters instead of numbers.

Thank you.
 
on Phys.org
  • Like
Likes   Reactions: kelvin490
jedishrfu said:
What about exporting the spreadsheet to a CSV file format and then using a scripting language like awk or python to append data to the end of each line and then reimport the spreadsheet?

and from MATLAB a similar approach:

https://www.mathworks.com/matlabcentral/newsreader/view_thread/274697

and using xlswrite in matlab:

http://www.mathworks.com/matlabcent...y-matlab-matrix-when-i-write-it-to-excel-in-m

Finally I solve it in the following way:

if (step==1)
xlswrite(filename,array,sheetname,'A1'); %Create the file
else

[~,~,Data]=xlsread(filename,sheetname); %read in all the old data

OriCol=size(Data,2); %get the column number of the old data

NewCol=OriCol+1; %the new array is placed right next to the original data

ColLetter=xlcolumnletter(NewCol);

StartCell=[ColLetter,'1'];

xlswrite(filename,array,sheetname,StartCell);

end

The xlcolumnletter function is found here:
http://www.mathworks.com/matlabcentral/answers/54153-dynamic-ranges-using-xlswrite