本文介绍了如何使用JS API在MS Office Word加载项中以编程方式获取Word文档中的文本范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式(通过MS Office加载项)获取Word文档中文本的数值范围(例如:起点30,终点35),但是我找不到如何通过JS做到这一点.这是一个示例:

I need to get numerical range of the text(example: startpoint-30, endpoint-35) in word document programmatically (via MS Office add-in), but I can't find how to do that via JS.Here is an example:

因此,我需要获取我想要的任何单词的范围,并为未来的开发创建单词范围的数组.例如,如果我们谈论单词"Pete",则其范围应为(16,20),如果文本的开头为0.当我在Internet上进行研究时,我发现了一些信息,看来这是不可能的与JS API有关.

So, I need to get range of any word i want and create array of word`s ranges for future development. For example if we speak about word "Pete" the range of it should be (16,20), if the beginning of the text is 0. When I researched this on the Internet I've found some info that it seems to be impossible to do with JS API.

但是我在.NET文档中发现了这样的功能.链接在这里 https://docs.microsoft.com/zh-cn/visualstudio/vsto/how-to-programmatically-define-and-select-ranges-in-documents?view=vs-2019

But i found such functionality in .NET docs. Here is the linkhttps://docs.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-define-and-select-ranges-in-documents?view=vs-2019

最后一个问题.是否有可能(如果是,是否非常复杂,我该如何实现)执行上面使用JS API进行的上述功能,或者我应该切换到.NET,以免浪费时间.

So the final question. Is it possible(if yes, is it very complicated and how can I achieve that) to do such functionality that I've described above with JS API or I should switch to .NET not to waste my time.

推荐答案

我假设您的意思是从字面上获取一个范围的数字边界,而不是要使用您已经必须得到一个范围.因此,如果我了解您想要做什么,那么建议您尝试以下操作:

I'm assuming that you mean literally to get the numerical bounds of a range, not that you want to use numerical bounds that you already have to get a range. So if I understand what you want to do, then I recommend that you try the following:

获取对整个文本的引用,作为Range对象.然后使用 Range.split 方法以获取位于"Pete"之前的范围. 文本ranges集合的第一个成员a>是你好,我的朋友".该字符串的长度是您的起点.您的终点是起点和"Pete"的长度之和.

Get a reference to the entire text as a Range object. Then use the Range.split method to get the range that precedes the "Pete". The text of first member of the ranges collection that is returned is "Hello my friend ". The length of this string is your start point. Your end point is the sum of the start point and the length of "Pete".

var target = "Pete";
var ranges = myRange.split([target], true, true, false);
var precedingRange = ranges.getFirst();
var startPoint = precedingRange.text.length;
var endPoint = starPoint + target.length;

这篇关于如何使用JS API在MS Office Word加载项中以编程方式获取Word文档中的文本范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!