在MATLAB中将图像插入excel单元格

hav*_*kok 4 excel matlab image export-to-excel

我正在关注这篇文章,我需要做同样的事情,只是我想把一个图像(m乘n 3矩阵)放入excel的单元格中.

这条线不会工作,因为我的图像im是矩阵而不是句柄:

print(im, '-dbitmap');
Run Code Online (Sandbox Code Playgroud)

我是否需要以某种方式为图像创建句柄?还有另外\更好的方法吗?

最终我想要更改单元格以使其适合图像(不改变图像的大小).

gno*_*ice 5

print语句将图形窗口的内容打印到文件中,因此您必须首先绘制图像:

image(im);                        % Plot image
set(gca, 'Visible', 'off', ...    % Turn off axes visibility
         'Position', [0 0 1 1]);  %   and make axes fill figure window
hFigure = gcf;                    % Get handle to figure
pos = get(hFigure, 'Position');   % Get current figure position
set(hFigure, 'Position', [pos(1:2) size(im, 2) size(im, 1)]);  % Set position so image
                                                               %   is scaled properly
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建一个COM服务器并将图形打印到Excel文件,如下所示:

excel = actxserver('Excel.Application');  % Create server object
excelWorkbook = excel.Workbooks.Add(1);   % Add a workbook
excelSheet = excel.ActiveSheet;           % Get the active sheet

dpi = get(groot, 'ScreenPixelsPerInch');  % Get screen dpi
print(hFigure, sprintf('-r%d', dpi), ...  % Print the figure at the screen resolution
      '-clipboard', '-dbitmap');          %   to the clipboard as a bitmap
excelSheet.Range('B2').PasteSpecial();    % Paste from clipboard (top left corner
                                          %   of image will be in the cell 'B2')

excelSheet.Range('B2').RowHeight = ...    % Set cell height to image height
  excelSheet.Shapes.Item(1).Height;
widthScale = excelSheet.Range('B2').ColumnWidth./...  % Column width (in characters)
             excelSheet.Range('B2').Width;            % Column width (in points)
excelSheet.Range('B2').ColumnWidth = ...  % Set cell width to scaled image width
  excelSheet.Shapes.Item(1).Width.*widthScale;

excelWorkbook.SaveAs('figtest.xlsx');  % Save workbook to a file
excelWorkbook.Close();                 % Close workbook
excel.Quit();                          % Quit server
excel.delete();                        % Delete server object
Run Code Online (Sandbox Code Playgroud)

以上尝试缩放单元以适合整个图像.这适用于行高,但由于某种原因,列宽已关闭.确定适当的缩放似乎很困难,因为列宽是根据字符定义的,图像宽度是以点/英寸来定义的.我不确定是否有一个很好的解决方法.

例如,以下是示例MATLAB图像的结果'peppers.png':

在此输入图像描述