Insert an image into a excel cell in MATLAB

前端 未结 2 1755
暖寄归人
暖寄归人 2020-12-07 03:04

I was following this post and I need to do about the same thing only I want to put an image (m by n by 3 matrix) into a cell in excel.

this line wont work because m

2条回答
  •  情书的邮戳
    2020-12-07 03:37

    I'm borrowing some code from gnovice's answer. It was really helpful for me in writing this answer.


    Here is a working example to insert peppers.png in the cell B2 :

    im=imread('peppers.png');
    imshow(im);
    
    dpi = get(groot, 'ScreenPixelsPerInch');  % Get screen dpi
    print(gcf, sprintf('-r%d', dpi), ...      % Print the figure at the screen resolution
          '-clipboard', '-dbitmap');          %   to the clipboard as a bitmap
    
    excel = actxserver('Excel.Application');  % Create server object
    excelWorkbook = excel.Workbooks.Add(1);   % Add a workbook
    excelSheet = excel.ActiveSheet;           % Get the active sheet
    excelSheet.Range('B2').PasteSpecial();    % Paste from clipboard (top left corner
                                              %   of image will be in the cell 'B2')   
    %%%%%%%%%%%%%%%% My contribution %%%%%%%%%%%%%%%%
    excelSheet.Shapes.Item(1).LockAspectRatio='msoFalse';            %Unlocking aspect ratio
    excelSheet.Shapes.Item(1).Width=excelSheet.Range('B2').Width;    %Adjusting width
    excelSheet.Shapes.Item(1).Height=excelSheet.Range('B2').Height;  %Adjusting height
    %Uncomment the next line if you want the cell to keep the image fit in its particular 
    %cell even if the size of the cell is changed later
    % excelSheet.Shapes.Item(1).Placement='xlMoveandSize';
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    excelWorkbook.SaveAs('figtest.xlsx');     % Save workbook to a file
    excelWorkbook.Close();                    % Close workbook
    excel.Quit();                             % Quit server
    excel.delete();                           % Delete server object
    

    Output:

提交回复
热议问题