我想避免在通过MATLAB将数据写入Excel电子表格时写入现有单元格。
我需要使用MATLAB将1X2的实验结果数组保存到Excel中。每次运行脚本时,MATLAB都会将结果覆盖到Excel中的单元格A1。我需要阻止这种情况发生,并让MATLAB在Excel中找到下一个空闲行并写入它。
我的方法是首先读取电子表格并将其存储为数组。计算数组的大小,找出下一个空闲单元格并写入它以避免覆盖。但是,我似乎无法找到如何从MATLAB写入特定单元格。
有关如何写入特定单元格或避免使用简单代码完全覆盖的任何建议?
示例代码:
num = xlsread('var_data.xlsx');
row_no = size(num,1);
xlswrite('var_data.xlsx',var_dat,'**ideally row_no**')
答案 0 :(得分:0)
<强>代码强>
%%// Filenames
temp_csvfile = 'temp1.txt';
final_excelfile = 'final_data.xls';
for k = 1:4 %// No. of steps
%// Generate data to be written to CSV/Excel files (random data for now)
a1 = num2cell(20.*rand(1,2));
%%// Temporarily store data into a CSV file
fid = fopen(temp_csvfile,'a');
fprintf(fid, '%f,%f\n',a1{:} );
fclose(fid);
%%// Verify the CSV file contents
type(temp_csvfile)
end
%%// Final stage of storing into excel file
fid = fopen(temp_csvfile,'r');
all_data = textscan(fid, '%f,%f');
fclose(fid);
xlswrite(final_excelfile,num2cell(cell2mat(all_data)))
输出(增长行)
12.982309,14.634448
12.982309,14.634448
12.954919,9.018474
12.982309,14.634448
12.954919,9.018474
10.940178,5.926416
12.982309,14.634448
12.954919,9.018474
10.940178,5.926416
14.893856,3.779100
答案 1 :(得分:0)
这可能会有所帮助。
fname='Book1.xlsx';
sname='Sheet1';
startingColumn='A'; %change if you want a different column
newData=[10 11]; %this is for test only
[~,~,Data]=xlsread(fname,sname); %read in the old data, text and all
nextRow=size(Data,1)+1; %get the row number of the end
range=sprintf('%s%d',startingColumn,nextRow); %this tells excel where to stick it
xlswrite(fname,newData,sname,range) % write the new data after the old data
如果你愿意,你可以在没有excel的情况下做到这一点。使用matlab save and load命令,并连接数据。代码片段看起来像
load oldDataFile %mat file containging variable oldData
oldData=[oldData;newData]; %update the data record
save oldDataFile oldData %save the concatenated record