MATLAB合并Word文档

功能:将多个word合并成一个word,按照文件名称进行分节。

实现步骤:建立新word作为合并文件,将需要合并的word打开,然后按文件夹中的顺序进行复制粘贴。

问题解决:针对参考链接2中存在的修改原有word进行了修改,存在只读word文档不允许修改保存问题,本文建立了新的word进行合并;

参考链接2会在原word中添加分页符,本文在复制粘贴后关闭原word,然后添加分页符。

应用:将类似的word进行合并,如测试报告,测试表格。

具体代码如下:

clear
clc
pwd = dir('D:\word_write\WordPath');%获取文件夹路径
pwd(1:2) = [];%删除前两个空值
FilePath = string(pwd(1).folder);%文件夹路径
for i=1:1:length(pwd)
%     FilePath(i) = string(strcat(pwd(i).folder,'\',pwd(i).name));
    FileName(i) = string(pwd(i).name);%文件名
end
%% 合并文件的文件名称
[file, path] = uiputfile('*.docx');%命名文件
if isequal(file,0) || isequal(path,0)
 
    errordlg('未命名文件','错误');%错误提示
    return
else
    filespec_user = strcat(path,file);% 设Word文件名和路径
end
if exist(filespec_user,'file')
    delete(filespec_user);
end
% 判断Word是否已经打开,若已打开,就在打开的Word中进行操作,否则就打开Word
try
    % 若Word服务器已经打开,返回其句柄Word
    word = actxGetRunningServer('Word.Application');
catch
    % 否则,创建一个Microsoft Word服务器,返回句柄Word
    word = actxserver('Word.Application');
end
word.Visible = 1; % 写入Word可视化,0则不可见
%% 先写合并文档标题
Document = word.Documents.Add;
Document.SaveAs2(filespec_user);
Document.PageSetup.Orientation=1;
Content = Document.Content;
Content.Text = "合并文档";
Content.Start =0;
Content.Paragraphs.Alignment='wdAlignParagraphCenter';%
Content.Font.Name = '宋体' ;
Content.Font.Size=20;
Document.Save; % 保存文档
Document.Close; % 关闭文档
mergedDoc = word.Documents.Open(filespec_user);%这里关闭之后再打开,直接可能会报错
%%
% 合并剩余文档
for DocIndex = 1:length(FileName)
    currentDoc = word.Documents.Open(fullfile(FilePath,FileName{DocIndex}));%打开需要合并的文档
    % 将当前文档复制到合并文档
    currentDocRange = currentDoc.Content;
    currentDocRange.Copy;
    %% %按照Word名称建立标题 这部分代码比较烂,待优化
    mergedDocRange = mergedDoc.Content;
    mergedDocRange.Start = mergedDocRange.End;
    mergedDocRange.Text = newline;%换行
    fileWord = char(FileName(DocIndex));
    mergedDocRange.Start = mergedDocRange.End;
    mergedDocRange.Text = fileWord(1:end-5);
    mergedDocRange.Start = mergedDocRange.End;
    mergedDocRange.Text = newline;
    mergedDocRange.Start = mergedDocRange.End;
    %% 粘贴至合并word
    mergedDocRange.Paste;
    currentDoc.Close;%关闭粘贴word后插入分页符   
    mergedDoc.Application.Selection.EndKey(6);%移动光标至文末
    mergedDoc.Application.Selection.InsertBreak(7);% 在当前文档末尾插入分页符
 
end
mergedDoc.Save; % 保存文档
mergedDoc.Close;
word.Quit;
delete(word);

参考资料:

Word Visual Basic for Applications (VBA) 参考 | Microsoft Learnicon-default.png?t=N7T8https://learn.microsoft.com/zh-cn/office/vba/api/overview/word合并多个word文档_matlab操作word-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/weixin_50976580/article/details/135003119

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值