Mirror

Search in MS Word file without MS Word (Views: 300)


Problem/Question/Abstract:

How can i Search in MS Word File Without MS Word?

Answer:

You can use follow code in delphi and search in msword file without msword and office :

unit FindText;

interface

function FindTextInFile(const FileName, TextToFind: WideString): boolean;

implementation

uses ComObj, ActiveX, AxCtrls, SysUtils, Classes;

function FindTextInFile(const FileName, TextToFind: WideString): boolean;
var
  Root: IStorage;
  EnumStat: IEnumStatStg;
  Stat: TStatStg;
  iStm: IStream;
  Stream: TOleStream;
  DocTextString: WideString;
begin
  Result := False;

  if not FileExists(FileName) then
    Exit;

  // Check to see if it's a structured storage file
  if StgIsStorageFile(PWideChar(FileName)) <> S_OK then
    Exit;

  // Open the file
  OleCheck(StgOpenStorage(PWideChar(FileName), nil,
    STGM_READ or STGM_SHARE_EXCLUSIVE, nil, 0, Root));

  // Enumerate the storage and stream objects contained within this file
  OleCheck(Root.EnumElements(0, nil, 0, EnumStat));

  // Check all objects in the storage
  while EnumStat.Next(1, Stat, nil) = S_OK do

    // Is it a stream with Word data
    if Stat.pwcsName = 'WordDocument' then

      // Try to get the stream "WordDocument"
      if Succeeded(Root.OpenStream(Stat.pwcsName, nil,
        STGM_READ or STGM_SHARE_EXCLUSIVE, 0, iStm)) then
      begin
        Stream := TOleStream.Create(iStm);
        try
          if Stream.Size > 0 then
          begin
            // Move text data to string variable
            SetLength(DocTextString, Stream.Size);
            Stream.Position := 0;
            Stream.Read(pChar(DocTextString)^, Stream.Size);

            // Find a necessary text
            Result := (Pos(TextToFind, DocTextString) > 0);
          end;
        finally
          Stream.Free;
        end;
        Exit;
      end;
end;

end.

<< Back to main page