matlab:批量将excel中的图片填入word特定表格中
步骤:
1、将excel中的图片提取出来保存在一个文件夹中;
2、把图片插入word特定表格。
将excel中的图片提取出来保存在一个文件夹中
思路:把.xlsx文件改为.zip文件再解压,图片在xl\media\
目录下:
%% 把.xlsx文件改为.zip文件
[Files, Path] = uigetfile({'*.xls;*.xlsx','Excel Files (*.xls;*.xlsx)';'*.*', 'All Files (*.*)'}, 'MultiSelect','on');
for i = 1:length(Files)
oldFileName = fullfile(Path, Files{i});
newFileName = fullfile(Path, [erase(Files{i}, '.xlsx'), '.zip']);
movefile(oldFileName, newFileName);
end
%% 解压缩
[zipFiles, zipFolder] = uigetfile({'*.zip','Zip Files (*.zip)';'*.*', 'All Files (*.*)'}, 'MultiSelect','on'); % 选择文件
Index = 1;
for Index = 1:length(zipFiles)
% ZIP文件路径
zipFilePath = fullfile(zipFolder, zipFiles{Index});
% 结果路径
targetFolder = fullfile(zipFolder, '已解压',zipFiles{Index});
if ~exist(targetFolder, 'dir')
mkdir(targetFolder);
end
% 解压缩
unzip(zipFilePath, targetFolder);
end
把图片插入word特定表格
%% 把图片插入word特定表格
[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;
Index = 1;
for Index = 1:length(filename_in)
doc = word.Documents.Open(fullfile(pathname,filename_in{Index}));
allTables = doc.Tables;
% table1 = allTables.Item(1);
targetText = '查找文本';
table1 = [];
for i = 1:allTables.Count
currentTable = allTables.Item(i);
if ~isempty(strfind(currentTable.Range.Text, targetText))
table1 = currentTable;
break;
end
end
table1Selection = word.Selection;
% 图片列表
[~, BaseName, ~] = fileparts(filename_in{Index});
imageFilespath = fullfile('D:\路径\图片',BaseName,'xl\media\*.jpeg');
imageFiles = dir(imageFilespath);
if length(imageFiles) < 2
disp(filename_in{Index})
end
% 遍历图片文件并插入表格
for i = 1:length(imageFiles)
imagePath = fullfile('D:\路径\图片',BaseName,'xl\media', imageFiles(i).name);
% 设置图片的长宽
width = 224.8; % 设置宽度(单位:磅)
height = 169.8; % 设置高度(单位:磅)
% 插入图片(倒数第二行,第i列)
table1.Cell(table1.Rows.Count-1, i).Range.InlineShapes.AddPicture(imagePath);
table1.Cell(table1.Rows.Count-1, i).Range.InlineShapes.Item(table1.Cell(table1.Rows.Count-1, i).Range.InlineShapes.Count).Width = width;
table1.Cell(table1.Rows.Count-1, i).Range.InlineShapes.Item(table1.Cell(table1.Rows.Count-1, i).Range.InlineShapes.Count).Height = height;
end
doc.SaveAs2(cell2mat(fullfile(pathname,'已改\',filename_in(Index))));
doc.Close ();
end
word.Quit ();
delete(word);
toc