http://blog.sina.com.cn/s/blog_53013a8c01011d0b.html
Delphi中对word的逐行读取等操作的解决
(2011-12-02 15:37:47)关于delphi对word的逐行读取,逐页读取,逐段读取google百度了很久,很难达到满意的功能。整了2天,终于找到了解决办法,可以每一行读取,但美中不足的就是速度有点慢。为了也帮助广大码农朋友开发时的困扰,我将代码贴上来分享一下:
(其中用到了官方文档:http://msdn.microsoft.com/en-us/library/aa201615)
-
初始化
procedure TForm1.DBGrid1CellClick(Column: TColumn);
var
wordapp, WordDoc, PageRange, PgphContext, lineContext: Variant;
sContext: string;
i, nPageCounts, nLineCounts, nStart, nEnd : Integer;
WdUnit, WdCount, wdExtend: OleVariant;
begin
wordapp := CreateOleObject('Word.Application');
try
wordapp.Visible := True;
WordDoc := wordapp.Documents.Open('D:\文档\章老师\word-group\1003.docx');
二.Word文档总页数,总段数
//文档总页数
nPageCounts := wordapp.Selection.Information[wdNumberOfPagesInDocument];
edit1.Text := inttostr(nPageCounts);
//文档总段落数
edit3.Text := wordapp.ActiveDocument.Range.Paragraphs.Count;
-
Word文档的总行数,以及逐行读取
//该文档总行数
edit4.Text:=wordapp.ActiveDocument.BuiltInDocumentProperties[wdPropertyLines].Value;
nStart := -1;
nEnd := -1;
nLineCounts := strtoint(edit4.Text);
//循环获取文档页中的内容
for i := 1 to nLineCounts do
begin
//定位到第i页
PageRange := wordapp.Selection.GoTo(wdGoToLine, wdGoToAbsolute, IntToStr(i));
//取第i页的页首位置作为开始位置
nStart := wordapp.Selection.Start;
//定位到i+1行
PageRange := wordapp.Selection.GoTo(wdGoToLine, wdGoToAbsolute, IntToStr(i+1));
//取第i+1行的页首位置作为结束位置
nEnd := wordapp.Selection.Start;
//根据开始位置和结束位置确定文档选中的内容(第i页的内容)
WordDoc.Range(nStart,nEnd).Select;
//输出内容
memo3.Lines.Add(inttostr(wordapp.Selection.Words.Count) + '/=============第'+IntToStr(i)+'行内容:===================/' + wordapp.Selection.text);
nStart := -1;
nEnd := -1;