Rename excel worksheets based on other file names in a folder

조회 수: 7 (최근 30일)
Melody Lyu
Melody Lyu 2020년 2월 13일
댓글: Melody Lyu 2020년 2월 13일
I have a folder with 23 files named below:
'9-5365_Kr1.4_Fir.xlsx'
'2-4534_Op4.6_Sec.xlsx'
...
I started with importing the folder in a for loop:
path = 'C:\Users\Documents\MATLAB';
files = dir(fullfile(path, '*.xlsx'));
for k = length(files):-1:1 %import the 23 files
filename = [path filesep files(k).name];
%do something
end
myfile = 'C:\Users\Downloads\myfile.xlsx';%the excel file with 23 worksheets of data
How do I rename the worksheets in 'myfile' based on the random names in the folder?

채택된 답변

fred  ssemwogerere
fred ssemwogerere 2020년 2월 13일
Hello, i think i've dealt with a previous question from you about writing files to different sheets. However, i do not think you can rename the "sheetnames" in Matlab. I advise that this would have been done while writing the files to different excel sheets. Below i have copied part of the code i used in one of the previous questions you asked, but edited some part to show how you can add custom "Sheetnames" during writing of the files to the sheets.
% If "C" is a cell array holding your imported files, and with each having a different name, then create
% a separate array holding your random names you wish to use for the sheets, say "T". As an example:
T={'9-5365_Kr1.4_Fir','2-4534_Op4.6_Sec'}; % A cell array of random sheet names (should have same length as "C")
for k=1:size(C,2)
xlswrite('myfile.xlsx',C{k},T{k}); % with "T{k}", Here you are indexing into the cell array of predefined sheetnames
end
  댓글 수: 4
fred  ssemwogerere
fred ssemwogerere 2020년 2월 13일
Sure. That could do. But their order should match the order of the imported files.
Melody Lyu
Melody Lyu 2020년 2월 13일
for i=1:size(C,2)
xlswrite('myFile.xlsx',C{i},files1{1,i});% where files has 1x23 cell array for filenames
end
Got it, thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by