uses ComObj, WordXp
读取
var wordapp, WordDoc, PageRange: Variant;
sContext: string;
i, nPageCounts, nStart, nEnd : Integer;
dlgopen1: TOpenDialog;
begin
dlgopen1 := TOpenDialog.Create(Self);
wordapp := CreateOleObject('Word.Application');
try
wordapp.Visible := False;
if dlgOpen1.Execute = False then Exit;
WordDoc := wordapp.Documents.Open(dlgOPen1.FileName);
//文档总页数
nPageCounts := wordapp.Selection.Information[wdNumberOfPagesInDocument];
//如果只有一页 那么全选就OK了
if nPageCounts = 1 then
begin
wordapp.Selection.WholeStory;
mmo1.Lines.Add('=============第'+IntToStr(nPageCounts)+'页内容:===================');
mmo1.Lines.Add(wordapp.Selection.Text);
Exit;
end;
nStart := -1;
nEnd := -1;
//循环获取文档页中的内容
for i := 1 to nPageCounts do
begin
//定位到第i页
PageRange := wordapp.Selection.GoTo(wdGoToPage, wdGoToNext, IntToStr(i));
//如果第i页是最后一页 那么直接将光标移动到最后 并输出内容
if i = nPageCounts then
begin
wordapp.Selection.EndKey(wdStory,wdExtend);
sContext := WordApp.Selection.Range.Text;
mmo1.Lines.Add('=============第'+IntToStr(i)+'页内容:===================');
mmo1.Lines.Add(sContext);
Exit;
end;
//取第i页的页首位置作为开始位置
nStart := wordapp.Selection.Start;
//定位到i+1页
PageRange := wordapp.Selection.GoTo(wdGoToPage, wdGoToNext, IntToStr(i+1));
//取第i+1页的页首位置作为结束位置
nEnd := wordapp.Selection.Start;
//根据开始位置和结束位置确定文档选中的内容(第i页的内容)
WordDoc.Range(nStart,nEnd).Select;
sContext := WordDoc.Range.Text;
//输出内容
mmo1.Lines.Add('=============第'+IntToStr(i)+'页内容:===================');
mmo1.Lines.Add(sContext);
nStart := -1;
nEnd := -1;
end;
finally
wordapp.Quit;
end;
end;
预览(转换成rtf文件加载到richedit)
var docapp1, WDoc, PageRange: Variant;
dlgopen1: TOpenDialog;
begin
docapp1 := CreateOleObject('Word.Application');
dlgopen1 := TOpenDialog.Create(Self);
if dlgopen1.Execute then
wdoc := docapp1.Documents.Open(dlgOPen1.FileName);
wDoc.SaveAs(ExtractFilePath(Paramstr(0)) + '\2.rtf', wdFormatRTF);
wDoc.close;
RzRichEdit1.Lines.LoadFromFile(ExtractFilePath(Paramstr(0)) + '\2.rtf');
end;
ps:非原创,找不到原创链接了无法发布为转载