基于MATLAB的Excel文件批量读取与循环处理
基于MATLAB的Excel文件批量读取与循环处理
一、基础实现方法
1. 使用dir
函数遍历文件
folderPath = 'D:\Data\Excel'; % 设置文件夹路径
filePattern = fullfile(folderPath, '*.xlsx'); % 匹配所有xlsx文件
excelFiles = dir(filePattern); % 获取文件列表% 初始化数据存储单元格数组
allData = cell(length(excelFiles), 1);% 循环读取文件
for i = 1:length(excelFiles)filePath = fullfile(excelFiles(i).folder, excelFiles(i).name);try% 读取数据(自动识别工作表和范围)allData{i} = readtable(filePath);fprintf('成功读取: %s\n', filePath);catch MEwarning('读取失败: %s - %s', filePath, ME.message);end
end
2. 动态生成文件名(带日期序列)
baseDir = 'D:\SensorData\';
year = 2024;
month = 8;for day = 1:31fileName = sprintf('%s%04d%02d%02d.xlsx', baseDir, year, month, day);if exist(fileName, 'file')data = readtable(fileName);% 数据处理代码end
end
二、高级功能实现
1. 多工作表读取
folderPath = 'D:\MultiSheetData';
excelFiles = dir(fullfile(folderPath, '*.xlsx'));for i = 1:length(excelFiles)filePath = fullfile(excelFiles(i).folder, excelFiles(i).name);[numSheets, sheetNames] = xlsfinfo(filePath); % 获取工作表信息for j = 1:numSheetssheetData = readtable(filePath, 'Sheet', sheetNames{j});% 分工作表处理数据end
end
2. 指定数据范围读取
% 读取Sheet1中A1:D100区域
dataRange = 'A1:D100';
dataTable = readtable('data.xlsx', 'Range', dataRange);% 读取多个不连续区域
multiRange = {'A1:B10', 'D1:D100'};
for i = 1:numel(multiRange)data{i} = readtable('data.xlsx', 'Range', multiRange{i});
end
三、性能优化策略
1. 并行处理(需Parallel Computing Toolbox)
parpool; % 启动并行池
parfor i = 1:length(excelFiles)filePath = fullfile(excelFiles(i).folder, excelFiles(i).name);allData{i} = readtable(filePath);
end
delete(gcp); % 关闭并行池
2. 内存映射读取(大文件处理)
filePath = 'large_dataset.xlsx';
opts = detectImportOptions(filePath);
opts.SelectedVariableNames = {'Time','Value'}; % 选择特定列
opts.TreatAsEmpty = {'NA', 'N/A'}; % 定义空值标识% 分块读取
chunkSize = 10000;
numChunks = ceil(opts.NumVariables / chunkSize);
for i = 1:numChunksstartIdx = (i-1)*chunkSize + 1;endIdx = min(i*chunkSize, opts.NumVariables);dataChunk = readtable(filePath, opts, 'ReadVariableNames', false, ...'DataRange', sprintf('A%d:Z%d', startIdx, endIdx));% 分块处理数据
end
四、数据整合与处理
1. 合并多表格数据
% 垂直合并(相同结构)
combinedData = vertcat(allData{:});% 横向合并(不同变量)
horizontalData = [allData{1}, allData{2}];
2. 数据清洗示例
cleanData = cell(size(allData));
for i = 1:length(allData)% 删除空行tbl = allData{i};tbl = rmmissing(tbl);% 类型转换tbl.Date = datetime(tbl.Date, 'InputFormat', 'yyyy-mm-dd');cleanData{i} = tbl;
end
参考代码 批量读取excel文件或者循环读取excel文件 www.youwenfan.com/contentcsi/63279.html
五、异常处理与日志记录
logFile = 'read_log.txt';
fid = fopen(logFile, 'w');for i = 1:length(excelFiles)tryfilePath = fullfile(excelFiles(i).folder, excelFiles(i).name);data = readtable(filePath);% 保存处理结果outputName = strrep(filePath, '.xlsx', '_processed.xlsx');writetable(data, outputName);fprintf(fid, '[%s] 成功处理: %s\n', datestr(now), filePath);catch MEfprintf(fid, '[%s] 错误: %s - %s\n', datestr(now), filePath, ME.message);end
end
fclose(fid);
六、扩展应用场景
1. 实时数据监控
folderPath = 'D:\RealTimeData\';
lastFile = dir(fullfile(folderPath, '*.xlsx'));
lastFile = lastFile(end).name; // 获取最新文件while truecurrentFiles = dir(fullfile(folderPath, '*.xlsx'));if ~isempty(currentFiles) && ~strcmp(currentFiles(1).name, lastFile)newData = readtable(fullfile(folderPath, currentFiles(1).name));% 更新监控界面updateDashboard(newData);lastFile = currentFiles(1).name;endpause(5); // 每5秒检查
end
2. 自动化报告生成
reportFolder = 'D:\Reports\';
if ~exist(reportFolder, 'dir')mkdir(reportFolder);
endfor i = 1:length(allData)tbl = allData{i};fig = figure;plot(tbl.Time, tbl.Value);title(tbl.FileName{1});exportgraphics(fig, fullfile(reportFolder, sprintf('plot_%d.png', i)));close(fig);
end
七、版本兼容性说明
MATLAB版本 | 推荐函数 | 特点 |
---|---|---|
R2016b及更早 | xlsread/xlswrite | 兼容旧版Excel格式 |
R2019a及以上 | readtable/writetable | 更高效,支持动态数据类型 |
R2021b及以上 | detectImportOptions | 智能识别数据格式和参数设置 |
八、常见问题解决方案
-
文件编码问题
opts = detectImportOptions('data.xlsx'); opts.Encoding = 'UTF-8'; % 设置编码格式 data = readtable('data.xlsx', opts);
-
混合数据类型处理
data = readtable('mixed_data.xlsx', 'TreatAsEmpty', {'NA', 'N/A'}); numericData = convertvars(data, 'TextColumn', 'double');
-
大文件内存优化
opts = detectImportOptions('large_file.xlsx'); opts.SelectedVariableNames = {'Timestamp', 'Sensor1'}; // 仅加载必要列 data = readtable('large_file.xlsx', opts);