필터 지우기
필터 지우기

How to skip Excel files in a loop when special characters exist as sheet names?

조회 수: 1 (최근 30일)
I am processing multiple excel files by getting file info, finding the last sheet, if the last sheet has 'Number' in B2, I delete the file.
MS_xlsx=dir('*.xlsx'); % list of the files
for i=1:length(MS_xlsx)
[~,file]=xlsfinfo(MS_xlsx(i).name);
last_sheet=file{end};
[~,txt]=xlsread(MS_xlsx(i).name,last_sheet,'B2'); % read the text
if strcmp(txt,'Number:')
delete(MX_xlsx(i).name)
end
end
Some of the excel files have special characters within the sheet name (symbols, foreign language characters, odd spacing). The sheets are recognized as (Nut Plate???? or Nut Plate or ????) and the code errors out at the following when searching for the nonexistent sheet (Nut Plate???? or Nut Plate or ????).
[~,txt]=xlsread(SVMS_xlsx(i).name,last_sheet,'B2'); % read the text
Since this is the case, how can I skip the file if the sheet name 'doesn't exist' (it does but is translated) because MATLAB recognizes it with either additional spaces or question marks?

채택된 답변

Calabrese
Calabrese 2017년 7월 14일
This doesn't solve the question but provides another solution to the need. Find length of the file and instead of trying to read the sheet name, we can read the sheet position by inputting the length into the sheet section of xlsread.
MS_xlsx=dir('*.xlsx'); % list of the files
for i=1:length(MS_xlsx)
[~,file]=xlsfinfo(MS_xlsx(i).name);
L=length(file);
[~,txt]=xlsread(MS_xlsx(i).name,L,'B2'); % read the text
if strcmp(txt,'Number:')
delete(MX_xlsx(i).name)
end
end

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 7월 10일
For example,
if ~all(isstrprop(last_sheet, 'alphanum'))
  댓글 수: 1
Calabrese
Calabrese 2017년 7월 10일
편집: Calabrese 2017년 7월 10일
Hi Walter, MATLAB locates the last_sheet and assigns it a different name if the original had odd characters or odd spacing. Since sometimes it is just odd spacing, I was hoping to search the file worksheets for the translated sheet name and since it doesn't exist, skip it and move to the next file. Like this but it's not working...
MS_xlsx=dir('*.xlsx'); % list of the files
for i=1:length(MS_xlsx)
[~,file]=xlsfinfo(MS_xlsx(i).name);
last_sheet=file{end};
sheetValid = any(strcmp(MS_xlsx(i).name, last_sheet));
% if sheetValid == 1;
[~,txt]=xlsread(MS_xlsx(i).name,last_sheet,'B2'); % read the text
if strcmp(txt,'Number:')
delete(MS_xlsx(i).name)
end
% else if sheetValid == 0;
% end
% end
end

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

카테고리

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