在 matlab 中读取文本分隔文件并写入 excel

read text delimited file and write to excel in matlab

我有一个这种格式的 txt 文件:
Right,28772.163,39356.163,1,Speaker1 sp,39356.163,49499.163,99,Speaker1 sp,129129.21,147210.21,99,Speaker2 Next step is,147210.21,160881.21,1,Speaker2 surgery's,160881.21,181608.21,1,Speaker2

它继续(它有 1016 行)。我想将它转换成 excel 文件。我尝试了以下

fileID = fopen('test_datum.txt');
C = textscan(fileID,'%s %f32 %f32 %d8 %s');

但是它将数据插入到一个 1016X5 的单元格中。我想稍后将此单元格写入 excel 文件。
谢谢

textscan 函数有时很难处理。数据格式很难定义,而且它倾向于将数据塞入单元格向量(将结果重新排序到单个单元格矩阵中有点烦人)。我建议您改用 readtable function

T = readtable('data.txt')


     Var1           Var2         Var3       Var4       Var5   
______________    _________    _________    ____    __________

'Right'           28772.163    39356.163     1      'Speaker1'
'sp'              39356.163    49499.163    99      'Speaker1'
'sp'              129129.21    147210.21    99      'Speaker2'
'Next step is'    147210.21    160881.21     1      'Speaker2'
'surgery's'       160881.21    181608.21     1      'Speaker2'

如果您的 Matlab 版本大于或等于 R2016b,您可以先前 运行 文件上的 detectImportOptions function。可以根据您的需要调整扫描结果(您可以更改变量名称、变量类型、缺失值的默认值等...):

opts = detectImportOptions('data.txt');

% the previous values where char, double, double, double, char
opts.VariableTypes = {'char' 'single' 'single' 'int8' 'char'};
% alternatively, this can be used:
% opts = setvartype(opts,{'char' 'single' 'single' 'int8' 'char'})

T = readtable('data.txt',opts)


     Var1           Var2        Var3      Var4       Var5   
______________    ________    ________    ____    __________

'Right'           28772.16    39356.16     1      'Speaker1'
'sp'              39356.16    49499.16    99      'Speaker1'
'sp'              129129.2    147210.2    99      'Speaker2'
'Next step is'    147210.2    160881.2     1      'Speaker2'
'surgery's'       160881.2    181608.2     1      'Speaker2'

最重要的是,表格非常容易导出到 Excel 文件。您所要做的就是使用具有适当设置的 writetable function

这是一种更简单的替代方法,可以让 MATLAB 函数自动处理更多数据处理:

% read the file into a table
T = readtable('test_datum.txt');

% convert the table to a cell array
C = table2cell(T);

% write the cell array to an Excel file
xlswrite('output.xlsx', C);