Delphi + Word解決方案參考這是我做專案過程中自己做的幾個函數,見到大家都在問Word的問題。現在拿出來跟大家共享。 (希望有朋友可以進一步添加新的功能,或者做成包或者lib等,更方便大家使用。我自己是沒有時間啦,呵呵)使用前,先根據需要建立一個空的WORD文件作為模板,在模板文件中設定好各種格式和文字。另外,其中的PRnWordTable的參數是TDBGridEh類型的控件,取自Ehlib2.6其中用到的shFileCopy函數(用於複製檔案)和guiInfo函數(用於顯示訊息框)也是自己寫的,程式碼也附後。示範程式碼如下:程式碼完成的功能: 1. 取代列印範本中的「#TITLE#」文字為「示範程式碼1」2. 並將DBGridEh1控制項目前顯示的內容插入到文件的結尾3. 在文件結尾插入一空行4.在文件末尾插入新的一行文字5. 將文件中的空白行去掉if PrnWordBegin('C:/列印範本.DOC','C:/目標檔案1.DOC') then begin PrnWordReplace('#TITLE#','示範程式碼1'); PrnWordTable(DBGridEh1); PrnWordInsert(''); PrnWordInsert('這是新的一行文字'); PrnWordReplace('^p^p','^p ',true); PrnWordSave; end;原始碼如下: //Word列印(宣告部分) wDoc,wApp:Variant; function PrnWordBegin(tempDoc,docName:String):boolean; function PrnWordReplace(docText,newText:String;bSimpleReplace:boolean=false):boolean; function PrnWordInsert(line:booString; boolean;overload; function PrnWordInsert(var imgInsert:TImage;sBookMark:String=''):boolean;overload; function PrnWordInsert(var chartInsert:TChart;sBookMark:String=''):boolean;overload; function PrnWordTable(var dbG:TDBGridEh;sBookMarkString='' ):boolean; procedure PrnWordSave; procedure PrnWordEnd; //Word列印(實作部分) {功能:基於範本檔案tempDoc新目標檔案docName並開啟檔案} function PrnWordBegin(tempDoc,docName:String):boolean;begin result:=false; //複製模版if tempDoc<>' ' then if not shFileCopy(tempDoc,docName) then exit; //連接Word try wApp:=CreateOleObject('Word.application'); except guiInfo('請先安裝Microsoft Word 。'); exit; end; try //開啟if tempDoc='' then begin //建立新文件wDoc:=wApp. Document.Add; wDoc.SaveAs(docName); end else begin //開啟模版wDoc:=wApp.Documents.Open(docName); end; except guiInfo('開啟模版失敗,請檢查模版是否正確。 '); wApp.Quit; exit; end; wApp.Visible:=true; result:=true;end; {功能:使用newText替換docText內容bSimpleReplace :true時只做簡單的替換,false時對新文本進行換行處理} function PrnWordReplace(docText,newText:String;bSimpleReplace:boolean=false):boolean;var i:Integer;begin if bSimpleReplace then begin //簡單處理,直接執行替換操作try wApp.Selection.Find.ClearFormatting; wApp.Selection.Find.Replacement.ClearFormatting; wApp.Selection.Find.Text := docText; wApp.Selection.Find.Replacement. Text :=newText; wApp.Selection.Find.Forward := True; wApp.Selection.Find.Wrap := wdFindContinue; wApp.Selection.Find.Format := False; wApp.Selection.Find.MatchCase := False; wApp.Selection.Find.MatchWholeWord := true; wApp.Selection.Find.MatchByte := True wAppApp. Selection.Find.MatchWildcards := False; wApp.Selection.Find.MatchSoundsLike := False; wApp.Selection.Find.MatchAllWordForms := False; wApp.Selection.Find.Execute(Replace:=wdReplaceAll); result:=true; except result:=false end; ; end; //自動分行reWord.Lines.Clear; reWord.Lines.Add(newText); try //定位到要取代的位置的後面wApp.Selection.Find.ClearFormatting; wApp.Selection.Find.Text := docText; wApp.Selection.Find.Replacement.Text := ''; wApp.Selection.Find.Forward := True; wApp.Selection.Find.Wrap := wdFindContinue; wApp.Selection.Find.Format := False; wApp.Selection.Find.MatchCase := False; wApp.Selection.Find.MatchWholeWord := False; wApp.Selection.Find.MatchByte :=; wApp.Selection.Find. MatchWildcards := False; wApp.Selection.Find.MatchSoundsLike := False; wApp.Selection.Find.MatchAllWordForms := False; wApp.Selection.Find.Execute; wApp.Selection.MoveRight(wdCharacter,1); //開始逐行插入for i:=0 to reWord.Lines. Count-1 Do begin //插入目前行wApp.Selection.InsertAfter(reWord.Lines[i]); //除最後一行外,自動加入新行if i<reWord.Lines.Count-1 then wApp.Selection.InsertAfter(#13); end; //刪除替換位標wApp.Selection.Find.ClearFormatting; wApp. Selection.Find.Replacement.ClearFormatting; wApp.Selection.Find.Text := docText; wApp.Selection.Find.Replacement.Text := ''; wApp.Selection.Find.Forward := True; wApp.Selection.Find.Wrap := wdFindContinue; wApp.Selection.Find.Format := False; wApp.Selection.Find.MatchCase := False; wApp.Selection .Find.MatchWholeWord := true; wApp.Selection.Find.MatchByte := True; wApp.Selection.Find.MatchWildcards := False; wApp.Selection.Find.MatchSoundsLike := False; wApp.Selection.Find.MatchAllWordForms := False; wApp.Selection.Find.Execute(Replace: wdReplaceAllplace); :=true; except result:=false; end;end; {功能:列印TDBGridEh目前顯示的內容是基於TDBGridEh控制項的格式和內容,自動在文件中的sBookMark書籤處產生Word表格目前能夠支援儲存格對齊、多行標題(兩行)、底部合計等特性sBookMark :Word中要插入表格的書籤名稱} function PrnWordTable(var dbG:TDBGridEh;sBookMark:String=''):boolean;var iCol,iLine,i,j,k:Integer; wTable,wRange:Variant; iRangeEnd:longint; iGridLine,iTitleLine:Integer; getTextText:String;getTextDisplay:boolean; titleList:TlitString? Integer;lastTitle:String;begin result:=false; try //計算表格的列數(不包含隱藏的欄位) iTitleLine:=1; //總是預設為1 iCol:=0; for i:=0 to dbG.Columns.Count-1 Do begin if dbG.Columns[i].Visible then begin iCol:=iCol+1; end; end; //計算表格的行數(不包括隱藏的欄位) if dbG.DataSource.DataSet.Active then iLine:=dbG.DataSource.DataSet.RecordCount else iLine:=0; iGridLine:=iLine+iTitleLine+dbG.FooterRowCount; //定位插入點if sBookMark='' then begin //在文件結尾iRangeEnd:=wDoc.Range.End-1; if iRangeEnd<0 then iRangeEnd:=0; wRange:=wDoc.Range(iRangeEnd,iRangeEnd); end else begin //在書籤處wRange:=wDoc.Range.Goto(wdGoToBookmark,,,sBookMark); end; wTableTable:=wD.Tables. Add(wRange,iGridLine,iCol); wTable.Columns.AutoFit; //標題行k:=1; for j:=1 to dbG.Columns.Count Do begin if dbG.Columns[j-1].Visible then begin if dbG.UseMultiTitle then begin titleList:= strSplit(dbG.Columns[j-1].Title.Caption,'|'); wTable.Cell(1,k).Range.InsertAfter(titleList.Strings[0]); end else wTable.Cell(1,k).Range.InsertAfter(dbG.Columns[j-1].Title.Caption); //設定單元格對齊方式if dbG.Columns[j-1].Title.Alignment=taCenter then wTable.Cell(1,k).Range.ParagraphFormat.Alignment:=wdAlignParagraphCenter else if dbG.Columns[j-1].Title.Alignment=taRightJustify then wTable.Cell(1,k).Range.ParagraphFormat.Alignment: wdAlignParagraphRight else if dbG.Columns[j-1].Title.Alignment=taLeftJustify then wTable.Cell(1,k).Range.ParagraphFormat.Alignment:=wdAlignParagraphJustify; k:=k+1; end; end; //填寫每一行if iLine>0 then begin dbG.DataSource.dataset.DisableControls; dbG.DataSource.DataSet.First; for i:=1 to iLine Do begin k:=1; for j:=1 to dbG.Columns.Count Do begin if dbG.Columns[j-1].Visible then begin if dbG .Columns[j-1].FieldName<>'' then //避免因為空列而出錯begin //如果該列有自己的格式化顯示函數,則呼叫顯示函數取得顯示字串getTextText:=''; if Assigned(dbG.DataSource.DataSet.FieldByName(dbG.Columns[j-1].FieldName).OnGetText ) then begin dbG.DataSource.DataSet.FieldByName(dbG.Columns[j-1].FieldName).OnGetText(dbG.DataSource.DataSet.FieldByName(dbG.Columns[j-1].FieldName),getTextText,getTextDisplay); wTable.Cell (i+iTitleLine,k).Range.InsertAfter(getTextText); end else begin //使用資料庫內容顯示wTable.Cell(i+iTitleLine,k).Range.InsertAfter(dbG.DataSource.DataSet.FieldByName(dbG.Columns[j-1].FieldName).AsString); end; end;