2013-01-04 48 views
4

當我使用下面的代碼。我得到正確導出的數字數據,但是當每列的第一行應該有標題(標題)時,第一行是空白的。任何解決方案matlab,如何將文本和數字數據導出到excel csv文件?

clc 
clear 

filename = 'file.csv'; 
fileID = fopen(filename,'wt'); 
%************************************************************************** 
%Sample data (note sample data are transposed row, i.e. columns) 

sample1 = [1,2,3,4]'; 
sample2 = [332.3, 275.8, 233.3, 275]'; 
sample3 = [360, 416.7, 500, 360]'; 
sample4= [-0.9, -0.9, -0.9, -0.9]'; 
sample5 = [ 300000, 0, 0, 0]'; 

A ={'text1','text2', 'text3', 'text4', 'text5'}; %' 

%*************************************************************************** 
%write string to csv 

[rows, columns] = size(A); 
for index = 1:rows  
    fprintf(fileID, '%s,', A{index,1:end-1}); 
    fprintf(fileID, '%s\n', A{index,end}); 
end 

fclose(fileID); 

%*************************************************************************** 
%write numerical data to csv 

d = [sample1, sample2, sample3, sample4, sample5]; 

csvwrite(filename, d, 1); 

回答

5

你在寫數字數據時擦除字符串,運行你的腳本直到數字數據 - 它工作正常。只需切換操作順序 - 首先寫入數字,然後寫入字符串,它將起作用。

編輯: 解決上述不起作用,因爲寫串以前將覆蓋寫入數值數據,更簡單,更intuitivesolution將通過

dlmwrite(filename, d,'-append', 'delimiter', ','); 

在原來的例子取代

csvwrite(filename, d, 1); 

+0

標頭工作正常,但數據沒有正確寫入。我只得到2行隨機數據 – user1945925

+0

確實,它覆蓋了數字數據,它看起來像dlmwrite是更好的選擇反正... –

+0

你有沒有運氣讓文本和數字數據正確顯示在CSV文件上?我可以得到或者。但不正確。謝謝! – user1945925

相關問題