批量将图片插入word(二)

批量将图片插入word(二)

背景

D:\路径\图片文件夹中有3子文件夹,每个子文件夹中有多张图片,如图:
请添加图片描述
请添加图片描述
D:\路径\文档文件夹中有3个word文档,文档名与D:\路径\图片的子文件夹名称对应,如图:
请添加图片描述
现在需要将第n个图片文件夹中所有图片插入第n个文档的表格中,如下图所示。
请添加图片描述

代码介绍

查找特定表格

allTables = document.Tables;
targetText = '迪迦'; % 查找带有“迪迦”字符的表格
appendixE = [];
for tableIndex = allTables.Count:-1:1 % 倒着找
    currentTable = allTables.Item(tableIndex);
    if ~isempty(strfind(currentTable.Range.Text, targetText))
        break;
    end
end
appendixE = allTables.Item(tableIndex);

插入图片到word表格中

% 插入图片
appendixE.Cell(row, col).Range.InlineShapes.AddPicture(imagePath);

调整图片尺寸

% 调整尺寸
width = 425.25;  % 设置宽度(单位:磅=厘米✖28.35)
height = 174.64; % 设置高度(单位:磅)
appendixE.Cell(row, col).Range.InlineShapes.Item(appendixE.Cell(row, col).Range.InlineShapes.Count).Width = width;
appendixE.Cell(row, col).Range.InlineShapes.Item(appendixE.Cell(row, col).Range.InlineShapes.Count).Height = height;

完整代码

%% 插入图片
[filename_in, pathname] = uigetfile({'*.doc;*.docx;*.docm','Word Files (*.doc,*.docx,*.docm)';'*.*', 'All Files (*.*)'}, 'MultiSelect','on');

tic
word = actxserver('Word.Application');
word.Visible = 0;
word.DisplayAlerts = 0;

imagePathname = 'D:\路径\图片';
for DocIndex = 1:length(filename_in)

    document = word.Documents.Open(fullfile(pathname,filename_in{DocIndex}));
    allTables = document.Tables;
    
    targetText = '迪迦';
    appendixE = [];
    for tableIndex = allTables.Count:-1:1 % 倒着找
        currentTable = allTables.Item(tableIndex);
        if ~isempty(strfind(currentTable.Range.Text, targetText))
            break;
        end
    end
    appendixE = allTables.Item(tableIndex);

    % 用文档名对应图片文件夹路径
    [~, BaseName, ~] = fileparts(filename_in{DocIndex});
    imageFilespath = fullfile(imagePathname, BaseName, '\*.png'); 
    imageFiles = dir(imageFilespath);

    % 根据图片数量,增加表格长度
    pngnum = length(imageFiles);
    for i = 1:pngnum*2-2
        appendixE.Rows.Add;
    end

    % 开始插入
    for i = 1:length(imageFiles)
        imagePath = fullfile(imagePathname, BaseName, imageFiles(i).name);
        
        % 设置图片的长宽
        width = 425.25;  % 设置宽度(单位:磅=厘米✖28.3515
        height = 174.64; % 设置高度(单位:磅)6.16
        
        % 插入图片
        appendixE.Cell(2*i-1, 1).Range.InlineShapes.AddPicture(imagePath);
        appendixE.Cell(2*i-1, 1).Range.InlineShapes.Item(appendixE.Cell(2*i-1, 1).Range.InlineShapes.Count).Width = width;
        appendixE.Cell(2*i-1, 1).Range.InlineShapes.Item(appendixE.Cell(2*i-1, 1).Range.InlineShapes.Count).Height = height;
        % 插入图片名称
        appendixE.Cell(2*i,1).Range.Text = strrep(imageFiles(i).name, '.png', ''); % 去掉.png后缀
    end

    document.SaveAs2(cell2mat(fullfile(pathname,'已改\',filename_in(DocIndex))));
    document.Close ();
end
word.Quit ();
delete(word);
toc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值