繁体   English   中英

如何在给定文档中查找字符串的位置或位置

[英]How to find the position or location of string in given document

如何找到给定document.string中的字符串的位置或位置。我有一个word文档,我想将其所有单词和单词位置存储在数据库中,因此这就是为什么我需要查找单词的位置的原因。

因此,请告诉我如何在给定文档中查找单词或字符串的位置或位置。

我打算将vb.net或c#用于.doc文档

嗯...我还没有找到一个更智能的解决方案:-/但这也许可以帮助您...我们将假设您的系统中已安装某些版本的MS Office。

首先,您必须在项目中将引用添加到名为“ Microsoft Word?*对象库”的Microsoft COM组件。

*? 它取决于您的MS Office版本

添加参考之后,可以测试以下代码:

using System;
using System.Collections.Generic;
using System.Text;
using Word;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {

            // Find the full path of our document

            System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);            
            object docFileName = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "document.doc");

            // Create the needed Word.Application and Word.Document objects

            object nullObject = System.Reflection.Missing.Value;
            Word.Application application = new Word.ApplicationClass();
            Word.Document document = application.Documents.Open(ref docFileName, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject);


            string wholeTextContent = document.Content.Text; 
            wholeTextContent = wholeTextContent.Replace('\r', ' '); // Delete lines between paragraphs
            string[] splittedTextContent = wholeTextContent.Split(' '); // Get the separate words

            int index = 1;
            foreach (string singleWord in splittedTextContent)
            {
                if (singleWord.Trim().Length > 0) // We don´t need to store white spaces
                {
                    Console.WriteLine("Word: " + singleWord + "(position: " + index.ToString() + ")");
                    index++;
                }
            }

            // Dispose Word.Application and Word.Document objects resources

            document.Close(ref nullObject, ref nullObject, ref nullObject);
            application.Quit(ref nullObject, ref nullObject, ref nullObject);
            document = null;
            application = null;

            Console.ReadLine(); 
        }
    }
}

我将对其进行测试,并且看起来它可以工作=)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM