Author: Mohammad Reza Lesani
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;
1 implementation
2
3 uses ComObj, ActiveX, AxCtrls, SysUtils, Classes;
4
5 function FindTextInFile(const FileName, TextToFind: WideString): boolean;
6 var
7 Root: IStorage;
8 EnumStat: IEnumStatStg;
9 Stat: TStatStg;
10 iStm: IStream;
11 Stream: TOleStream;
12 DocTextString: WideString;
13 begin
14 Result := False;
15
16 if not FileExists(FileName) then
17 Exit;
18
19 // Check to see if it's a structured storage file
20 if StgIsStorageFile(PWideChar(FileName)) <> S_OK then
21 Exit;
22
23 // Open the file
24 OleCheck(StgOpenStorage(PWideChar(FileName), nil,
25 STGM_READ or STGM_SHARE_EXCLUSIVE, nil, 0, Root));
26
27 // Enumerate the storage and stream objects contained within this file
28 OleCheck(Root.EnumElements(0, nil, 0, EnumStat));
29
30 // Check all objects in the storage
31 while EnumStat.Next(1, Stat, nil) = S_OK do
32
33 // Is it a stream with Word data
34 if Stat.pwcsName = 'WordDocument' then
35
36 // Try to get the stream "WordDocument"
37 if Succeeded(Root.OpenStream(Stat.pwcsName, nil,
38 STGM_READ or STGM_SHARE_EXCLUSIVE, 0, iStm)) then
39 begin
40 Stream := TOleStream.Create(iStm);
41 try
42 if Stream.Size > 0 then
43 begin
44 // Move text data to string variable
45 SetLength(DocTextString, Stream.Size);
46 Stream.Position := 0;
47 Stream.read(pChar(DocTextString)^, Stream.Size);
48
49 // Find a necessary text
50 Result := (Pos(TextToFind, DocTextString) > 0);
51 end;
52 finally
53 Stream.Free;
54 end;
55 Exit;
56 end;
57 end;
58
59 end.
|