基于MATLAB的Excel文件批量读取与循环处理

基于MATLAB的Excel文件批量读取与循环处理


一、基础实现方法

1. 使用dir函数遍历文件
matlab 复制代码
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 ME
        warning('读取失败: %s - %s', filePath, ME.message);
    end
end
2. 动态生成文件名(带日期序列)
matlab 复制代码
baseDir = 'D:\SensorData\';
year = 2024;
month = 8;

for day = 1:31
    fileName = sprintf('%s%04d%02d%02d.xlsx', baseDir, year, month, day);
    if exist(fileName, 'file')
        data = readtable(fileName);
        % 数据处理代码
    end
end

二、高级功能实现

1. 多工作表读取
matlab 复制代码
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:numSheets
        sheetData = readtable(filePath, 'Sheet', sheetNames{j});
        % 分工作表处理数据
    end
end
2. 指定数据范围读取
matlab 复制代码
% 读取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)
matlab 复制代码
parpool;  % 启动并行池
parfor i = 1:length(excelFiles)
    filePath = fullfile(excelFiles(i).folder, excelFiles(i).name);
    allData{i} = readtable(filePath);
end
delete(gcp);  % 关闭并行池
2. 内存映射读取(大文件处理)
matlab 复制代码
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:numChunks
    startIdx = (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. 合并多表格数据
matlab 复制代码
% 垂直合并(相同结构)
combinedData = vertcat(allData{:});

% 横向合并(不同变量)
horizontalData = [allData{1}, allData{2}];
2. 数据清洗示例
matlab 复制代码
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

五、异常处理与日志记录

matlab 复制代码
logFile = 'read_log.txt';
fid = fopen(logFile, 'w');

for i = 1:length(excelFiles)
    try
        filePath = 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 ME
        fprintf(fid, '[%s] 错误: %s - %s\n', datestr(now), filePath, ME.message);
    end
end
fclose(fid);

六、扩展应用场景

1. 实时数据监控
matlab 复制代码
folderPath = 'D:\RealTimeData\';
lastFile = dir(fullfile(folderPath, '*.xlsx'));
lastFile = lastFile(end).name;  // 获取最新文件

while true
    currentFiles = 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;
    end
    pause(5);  // 每5秒检查
end
2. 自动化报告生成
matlab 复制代码
reportFolder = 'D:\Reports\';
if ~exist(reportFolder, 'dir')
    mkdir(reportFolder);
end

for 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 智能识别数据格式和参数设置

八、常见问题解决方案

  1. 文件编码问题

    matlab 复制代码
    opts = detectImportOptions('data.xlsx');
    opts.Encoding = 'UTF-8';  % 设置编码格式
    data = readtable('data.xlsx', opts);
  2. 混合数据类型处理

    matlab 复制代码
    data = readtable('mixed_data.xlsx', 'TreatAsEmpty', {'NA', 'N/A'});
    numericData = convertvars(data, 'TextColumn', 'double');
  3. 大文件内存优化

    matlab 复制代码
    opts = detectImportOptions('large_file.xlsx');
    opts.SelectedVariableNames = {'Timestamp', 'Sensor1'};  // 仅加载必要列
    data = readtable('large_file.xlsx', opts);
相关推荐
机器学习之心8 小时前
PINN物理信息神经网络风电功率预测!引入物理先验知识嵌入学习的风电功率预测新范式!Matlab实现
神经网络·学习·matlab·风电功率预测·物理信息神经网络
woshigaowei514610 小时前
VS(QT)调用Matlab函数的方法
qt·matlab·vs
ghie909011 小时前
基于libsvm的支持向量机在MATLAB中的实现
算法·支持向量机·matlab
CodeCraft Studio14 小时前
Excel处理控件Aspose.Cells教程:使用 Python 将 HTML 转换为 Excel
python·html·excel·aspose·aspose.cells·html转excel
Leo6553514 小时前
Excel 读取阶段就去掉换行
excel
小镇学者15 小时前
【PHP】利用 xlswriter 扩展导出的Excel文件报错问题
php·excel
程序员杰哥16 小时前
Pytest与Unittest测试框架对比
自动化测试·软件测试·python·测试工具·测试用例·excel·pytest
cehuishi952717 小时前
excel中关联word邮件合并使用
word·excel·批量打印·邮件合并
fengfuyao98517 小时前
基于MATLAB的匈牙利算法实现任务分配
算法·数学建模·matlab