将数据导出到Excel并对其应用格式

时间:2017-04-24 09:03:57

标签: excel matlab formatting export-to-excel

我想使用1xm-Cellarray导出xlswrite。单元格数组由m个单元格组成,每个单元格包含ixn-Cellarray,其中i大多数为2,但也可以是3,4,5或6.这是数据看起来的示例喜欢:

a=[{{{'a'},{'b'},{'c'},{'d'};{'a'},{'b'},{'c'},{'d'}}},{{{'a'},{'b'},{'c'},{'d'};{'a'},{'b'},{'c'},{'d'};{'a'},{'b'},{'c'},{'d'}}},{{{'a'},{'b'},{'c'},{'d'};{'a'},{'b'},{'c'},{'d'}}}]

a = 

    {2x4 cell}    {3x4 cell}    {2x4 cell}

我希望所有单元格都在彼此之下写入,但我希望能够在Excel中看到哪些行属于一个单元格。我的想法是在Array单元格和另一个像

之间放置一个空行
exportTable=[];
for jj=1:numel(a)
    exportTable=[exportTable;a{jj};repmat({[]},1,18)];
end

然后使用exportTable导出xlswrite,但这在导出的工作表中看起来很丑陋并且不易阅读。
现在我正在寻找一种方法,可以直接使用matlab中的导出功能或使用带有相应行向量的Excel作为输入,使每个单元格的行在同一颜色中着色。
我可以使用

获得每个单元格的结束索引
rows=cumsum(cellfun(@(x) size(x,1),a))

rows =

     2     5     7

但我不知道如何根据rownumbers在Excel中为行着色 我的示例所需的输出如下所示:
example output

感谢使用Matlab或Excel的任何帮助。

1 个答案:

答案 0 :(得分:1)

rows = cumsum(cellfun(@(x) size(x,1),a))

%Create an Excel object.
e = actxserver('Excel.Application');

%Add a workbook.
eWorkbook = e.Workbooks.Add;
e.Visible = 1;

%Make the first sheet active.
eSheets = e.ActiveWorkbook.Sheets;
eSheet1 = eSheets.get('Item',1);
eSheet1.Activate

for i = 1:length(a)
    ai = table2array( cell2table( a{:,i} ) ); % sorry for this construction

    if mod(i,2)
        ai_color = 3;
    else
        ai_color = 4;
    end

    ai_range = ['A',num2str(rows(i)-size(ai,1)+1),':',char('A'-1+size(ai,2)),num2str(rows(i))]; % ... and this :)

    % Set the color of cells
    eSheet1.Range(ai_range).Interior.ColorIndex = ai_color;

    %Put MATLAB data into the worksheet.
    eActivesheetRange = get(e.Activesheet,'Range',ai_range);
    eActivesheetRange.Value = ai;
end


SaveAs(eWorkbook,'myfile.xlsx')

%If the Excel program displays a dialog box about saving the file, select the appropriate response to continue.

%If you saved the file, then close the workbook.
eWorkbook.Saved = 1;
Close(eWorkbook)

%Quit the Excel program and delete the server object.
Quit(e)
delete(e)

%Note:   Make sure that you close workbook objects you create to prevent potential memory leaks.