如何检查空文件?

时间:2017-02-24 09:25:36

标签: office-js

我需要检测文档是否为空,如果是,则使用Word加载项向用户显示提示。

有没有办法从OfficeJS Word加载项或通过API检测空文档?

2 个答案:

答案 0 :(得分:1)

您应该能够获取文档的ParagraphCollection并使用它执行检查,如下所示:

=Cluster=
SPEC PRD000681;PRIDE_Exp_Complete_Ac_22491.xml;spectrum=1074 true
SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=2950 true

=Cluster=
SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=1876 true
SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3479 true
SPEC PRD000681;PRIDE_Exp_Complete_Ac_22498.xml;spectrum=3785 true

=Cluster=
SPEC PRD000681;PRIDE_Exp_Complete_Ac_22493.xml;spectrum=473 true

这适用于完全空白的文档。如果您希望更严格,则需要针对每个Word.run(function (context) { var paragraphs = context.document.body.paragraphs; context.load(paragraphs, 'text'); return context.sync().then(function () { if (paragraphs.items.length === 0) { // Empty document! } }); }); 对象paragraphs.items[]属性添加其他检查。

Source

答案 1 :(得分:0)

Word.run(function(context) {
                    var body = context.document.body;
                    body.load();
                    return context.sync().then(function() {
                        if(body.text.trim().length) {
                           //Document is not Empty. Add your code here you want to run in this case.
                        }
                        else
                            //Empty Document
                    });
                });

body.text.trim()。length 返回文档中的字符数。如果空文档长度为 0 ,则条件将评估为false,否则将执行部分。

相关问题