dir 返回结构体数组是正确的。此数组中的每个元素都是有关使用 dir 时与您的搜索查询匹配的每个文件的信息。你显然不能直接使用这个结构,所以你必须访问它里面的东西才能得到你需要的东西。首先,您需要将dir 的输出分配给某物:
d = dir('*.xlsx');
之后,您将获得一个结构数组,其中每个元素都有一个name 字段。此字段是使用dir 匹配您的查询的每个文件的名称。因此,您必须单独访问每个文件的每个 name 字段,并使用它来最终打开您的文件。
例如,如果您想要第一个 Excel 文件,您可以:
fileName = d(1).name;
fileName 将包含第一个 Excel 文件名称的字符串,然后您可以使用它来读取文件:
out = xlsread(fileName);
或者,如果您有多个 Excel 文件并且想要单独处理它们,请考虑将其放入循环中:
d = dir('*.xlsx'); %// Find all Excel files
%// For each file...
for idx = 1 : numel(d)
fileName = d(idx).name; %// Get the file name
out = xlsread(fileName); %// Read the Excel file
%//..... rest of your code follows
end
如果您想查找不在当前工作目录中的 Excel 文件,您可以执行以下操作。请记住,当使用dir 时,它会找到与您指定的输入目录相关的文件。这不会形成绝对路径。因此,要成功打开文件,您需要将您指定的目录以及该目录本地的相关文件名拼凑在一起。您可以使用fullfile 来帮助您做到这一点:
directory = '/put/my/directory/here'; %// Place directory to search for Excel files here
%// Create absolute path to search for Excel files
searchString = fullfile(directory, '*.xlsx');
%// Find the file names
d = dir(searchString);
%// For each file...
for idx = 1 : numel(d)
fileName = fullfile(directory, d(idx).name); %// Get the file name
out = xlsread(fileName); %// Read the Excel file
%//..... rest of your code follows
end
如果您在当前工作目录中查找文件,则不需要 fullfile 内容....如果您想搜索不在工作目录中的 Excel 文件,则需要考虑这一点。