不少小夥伴們在日常學習工作中遇到需要整合大量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