matlab将多个excel读取并存到一个excel的不同sheet中

  不少小伙伴们在日常学习工作中遇到需要整合大量excel的工作,比如需要将1000个excel的sheet1工作表中的数据读取后存放到一个excel文件中并按1000个工作表分别保存,手动操作吗,那肯定费时费力。如果仅仅是提取数据而不保留原格式,不妨使用MATLAB。(如果要求合并多个excel并且保留原格式,那使用VBA是最好的选择,后期另写一个博客发布代码)

  首先贴上代码:

 function readExcel
 %Tips:最好不要用中文的路径和文件名,可能会出现乱码
 %Coded by theSunrize ,2017.04.09
 %on matlabR2015b 
clear;
clc;

filePath=uigetdir({},'choose your filepath'); %获取excel文件存储目录
getFileName=ls(strcat(filePath,'\*.xl*'));  %获取所选目录下的文件名
fileName = cellstr(getFileName); %将string数组转为cell数组

if  isequal(getFileName,'')%防止选择空文件夹
   msgbox('no excel file in the path you selected');
else 

mkdir(strcat(filePath,'\output'));%新建输出文件夹
waiting=waitbar(0,'excuting...,please wait!');%进度条
for i=1: length(fileName)                                                  %foreach your files  
    [excelData,str] = xlsread(strcat(filePath,'\',fileName{i}));%读取excel
  xlswrite(strcat(filePath,'\output\output.xlsx'),str,strcat('Sheet',num2str(i)), 'A1');%将读取的工作表表头写入excel
    xlswrite(strcat(filePath,'\output\output.xlsx'),excelData,strcat('Sheet',num2str(i)), 'A2');%将读取的工作表数字写入excel

end
close(waiting)%关闭进度条
disp 'you can find output file there:'
outputPath = strcat(filePath,'\output\output.xlsx')
msgbox(strcat('finished,get output file in:',outputPath),'Success','Help');%prompt message
end
end

以上代码只适合以下格式的数据读写,即第一行是字符串型表头,第二行开始是数字类型的数据。


这里写图片描述

新建几个用于演示的excel如下:


这里写图片描述

运行代码,选择excel所在目录


这里写图片描述

选择后开始读取和写入数据


这里写图片描述
运行完毕,生成输出文件

这里写图片描述

根据提示信息找到输出文件夹


这里写图片描述

将三个excel写入一个excel中的效果如下


这里写图片描述

代码及演示文件下载http://download.csdn.net/detail/thesunrize/9808425
或者github https://github.com/Miaor/readExcel

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章