MATLAB: Can I simultaneously create new Excel sheets and rename each new Excel sheet using the writetable function (without ActiveX)

excelimporting excel datawritetable

I wrote a piece of code which imports data from each text file in a specified directory, uses a for loop to sequentially analyze the data from each text file, and generate a new Excel sheet to export the data from each text file into. I am working on a Mac, so I have to use the writetable function to export my data into Excel, which also means I cannot use ActiveX. My question is, is there any way for me to use the writetable function to both create a new sheet, and rename the sheet as I'd wish as it is created?
As of now, I am having both the issue of not being able to name the sheets being made by specifying the worksheet index if I go that route, or the issue of the first default 3 sheets generated using the writetable function interfering with the naming of the sheets made by specifying the worksheet name, as I did in the code provided below.
I appreciate all of the help in advance.
directoryName=uigetdir('C:\Desktop', 'Open directory containing data');
directoryFiles=dir(fullfile(directoryName, '*.txt'));
ndirectoryFiles=length(directoryFiles);
[saveName,savePath] = uiputfile({'*.xlsx'},'Save Excel file as');
saveDirectory = strcat(savePath,saveName);
for i=1:ndirectoryFiles
%Here is where I analyze my data and and store it in variables var1,
%var2, and var3
dataSheet=table(var1, var2, var3);
sheet = i;
%I tried multiple variations of using the writetable function shown
%below, both separately and together
writetable(dataSheet, saveDirectory, 'sheet', directoryFiles(i).name,
'Range','A1');
writetable(dataSheet, saveDirectory, 'sheet', sheet,'Range','A1');
end

Best Answer

No. writetable cannot rename sheets or delete sheets. It is restricted to being used to write a new copy of the sheet with the new name and then being used to write data to the existing sheet name. But even that is not optimal as there is no operation for truncating a sheet so if the replacement sheet were smaller than the one with the same name it was replacing, you would be risking old data left around unless you padded with empty cells to fill out the former size.