【问题标题】:How to import multiple excel file into one excel file by using matlab?如何使用matlab将多个excel文件导入一个excel文件?
【发布时间】:2017-11-11 14:00:46
【问题描述】:

我是 matlab 的新手,在这件事上陷入困境。我尝试使用 matlab 代码从多个 excel 文件中创建一个新文件。它设法生成了新文件。但是文件一团糟,我真的不知道该怎么做。代码如下:

% Merge multiple XLS files into one XLS file
[filenames, folder] = uigetfile('*.xls','Select the data file','MultiSelect','on');   % gets directory from any folder
% Create output file name in the same folder.
outputFileName = fullfile(folder, 'rainfall.xls');
fidOutput = fopen(outputFileName, 'wt');                            % open output file to write
for k = 1 : length(filenames)
    % Get this file name.
    thisFileName = fullfile(folder, filenames{k});
    % Open input file:
    fidInput = fopen(thisFileName);  
    % Read text from it
    thisText = fread(fidInput, '*char');
    % Copy to output file:
    fwrite(fidOutput, thisText);    
    fclose(fidInput);   % close the input file
end
fclose(fidOutput);

我附上图片,显示结果数据是多么混乱。请你帮助我好吗?非常感谢。

【问题讨论】:

  • 同样的问题一遍又一遍,没有努力让事情正常进行。只需查看 OP 的配置文件活动即可。

标签: excel matlab matlab-guide


【解决方案1】:
[files,folder] = uigetfile('*.xls','Select Files','MultiSelect','on');
output = fullfile(folder,'rainfall.xls');

c = cell(0,5);

for i = 1:numel(files)
    c_curr = table2cell(readtable(fullfile(folder,files{i}),'ReadVariableNames',false));
    c = [c; c_curr];
end

tab = cell2table(c,'VariableNames',{'MyVar1' 'MyVar2' 'MyVar3' 'MyVar4' 'MyVar5'});

writetable(tab,output);

当然,每个文件必须包含相同数量的列,并且每个列必须在所有文件中具有相同的基础数据类型。

【讨论】:

  • 我不知道你的文件长什么样,所以很难说。无论如何,您需要做的就是将您读取的表合并到 for 循环中的单个表中。然后将 writetable 调用移到循环之外,在脚本的末尾,并对其进行更改,使其以合并结果为目标。
  • 感谢您的回复,托马索。我尝试了上面的代码,但出现错误“使用 cell2table 时出错(第 57 行)VariableNames 属性必须为表中的每个变量包含一个名称。”
  • 当然,我不会向您发送现成的代码。特别是如果我不知道你的桌子是什么样子的。说真的,你有没有尝试过看看你的代码发生了什么?因为在我看来,这显然是让其他人以零努力完成工作的尝试。我要在这里召集主持人干预。
【解决方案2】:

使用 xlsread(或 readtable,如果您有最新版本的 Matlab)代替 fread。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多