批量将图片插入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.35)15
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