Servers 控件组 Wordapplication 表格 使用

    技术2022-05-11  51

    RE: 如何把一个grid中显示的数据直接输出到word文件(存储为word或txt文件)?100分 ID=1823976, 发贴富翁: yanghaijun, 发贴时间:2003-5-3 11:30:00下面是我写的一个比较完整的输出到WORD的过程,你可能需要稍微改一下以适合你的需要:procedure DBGridExportToWord(tempGrid: TObject);var  WordApplication: TWordApplication;  WordDocument: TWordDocument;  WordFont: TWordFont;  WordParagraphFormat: TWordParagraphFormat;

      Template,NewTemplate,ItemIndex:OleVariant;  v1,v2,v3: OleVariant;  coli,colii,rowi,i,j:integer;  ClientDataSet:TClientDataSet;

      tReportTitle: string;  tPageWidth,tPageHeight,tTopMargin,tBottomMargin,tLeftMargin,tRightMargin: Double;  tXHLen: Double;  tFX: integer;

      procedure setfont;    begin//      WordFont.ConnectTo(WordDocument.Sentences.Get_Last.Font);//      if ChkBoxUnderline.checked then WordFont.Underline := 2;//      if ChkBoxBold.checked then WordFont.Bold := 1;//      if ChkBoxItalic.Checked then WordFont.Italic := 1;//      if ChkBoxEmboss.Checked then WordFont.Emboss := 1;//      if ChkBoxEngrave.checked then WordFont.Engrave := 1;//      if ChkBoxShadow.checked then WordFont.shadow := 1;//      if ChkBoxDoublestrike.checked then WordFont.DoubleStrikeThrough := 1;//      if ChkBoxStrike.checked then WordFont.StrikeThrough := 1;//      WordFont.Size := StrToInt(Size.text);//      if Fonttype.Itemindex >= 0 then//         WordFont.Name := FontType.Items[FontType.Itemindex];    end;begin  //下面的这段是我编写的一段控制WORD页面参数的语句,你可以删除改成自己的  try    WordSetupForm:=TWordSetupForm.Create(nil);    WordSetupForm.ShowModal;    i:=WordSetupForm.ModalResult;    if i=mrOK then    begin      tReportTitle:=WordSetupForm.edtReportTitle.Text;      tPageWidth:=StrToFloat(WordSetupForm.edtPageWidth.Text);      tPageHeight:=StrToFloat(WordSetupForm.edtPageHeight.Text);      tTopMargin:=StrToFloat(WordSetupForm.edtTopMargin.Text);      tBottomMargin:=StrToFloat(WordSetupForm.edtBottomMargin.Text);      tLeftMargin:=StrToFloat(WordSetupForm.edtLeftMargin.Text);      tRightMargin:=StrToFloat(WordSetupForm.edtRightMargin.Text);      tFX:=WordSetupForm.rgFX.ItemIndex;      tXHLen:=StrToFloat(WordSetupForm.edtXHLen.Text);    end;  finally    WordSetupForm.Free;  end;  if i=mrCancel then exit;

      //下面正式进入表格打印...这是实际的代码  try    WordApplication:=TWordApplication.Create(nil);    WordDocument:=TWordDocument.Create(nil);    WordParagraphFormat:=TWordParagraphFormat.Create(nil);    WordFont:=TWordFont.Create(nil);

        Template := EmptyParam;  //这里若使用模板,则应使用模板的绝对路径名    NewTemplate := True;    ItemIndex := 1;    try      WordApplication.Disconnect;      Wordapplication.Connect;    except      MessageDlg('Word 可能还没有安装!', mtError, [mbOk], 0);      Abort;    end;

        Wordapplication.Visible := True;    WordApplication.Caption := tReportTitle;    Template := EmptyParam;    NewTemplate := False;    WordApplication.Documents.Add(Template, NewTemplate);    {Assign WordDocument component}    WordDocument.ConnectTo(WordApplication.Documents.Item(ItemIndex));    {Turn Spell checking of because it takes a long time if enabled and slows down Winword}    WordApplication.Options.CheckSpellingAsYouType := False;    WordApplication.Options.CheckGrammarAsYouType := False;

        WordApplication.Selection.ParagraphFormat.Alignment := wdAlignParagraphCenter;    WordApplication.Selection.Font.Bold := wdToggle;    WordApplication.Selection.Font.Size := 22;    WordApplication.Selection.TypeText(tReportTitle);    WordApplication.Selection.TypeParagraph;    WordApplication.Selection.Font.Bold := wdToggle;    WordApplication.Selection.Font.Size := 11;    WordApplication.Selection.ParagraphFormat.Alignment := wdAlignParagraphLeft;

       if tFX=0 then WordDocument.PageSetup.Orientation:=wdOrientPortrait      else WordDocument.PageSetup.Orientation:=wdOrientLandscape;    WordDocument.PageSetup.TopMargin:=WordApplication.MillimetersToPoints(tTopMargin);    WordDocument.PageSetup.BottomMargin:=WordApplication.MillimetersToPoints(tBottomMargin);    WordDocument.PageSetup.LeftMargin:=WordApplication.MillimetersToPoints(tLeftMargin);    WordDocument.PageSetup.RightMargin:=WordApplication.MillimetersToPoints(tRightMargin);    WordDocument.PageSetup.PageWidth:=WordApplication.MillimetersToPoints(tPageWidth);    WordDocument.PageSetup.PageHeight:=WordApplication.MillimetersToPoints(tPageHeight);

        //设置页脚    if WordDocument.ActiveWindow.View.SplitSpecial<>wdPaneNone then      WordDocument.ActiveWindow.Panes.Item(2).Close;    if (WordDocument.ActiveWindow.ActivePane.View.type_=wdNormalView)      or (WordDocument.ActiveWindow.ActivePane.View.type_=wdOutlineView) then        WordDocument.ActiveWindow.ActivePane.View.type_:=wdPrintPreview;    WordDocument.ActiveWindow.ActivePane.View.SeekView:=wdSeekCurrentPageHeader;    if WordApplication.Selection.HeaderFooter.IsHeader then        WordDocument.ActiveWindow.ActivePane.View.SeekView:= wdSeekCurrentPageFooter    else        WordDocument.ActiveWindow.ActivePane.View.SeekView:= wdSeekCurrentPageHeader;   WordApplication.Selection.ParagraphFormat.Alignment := wdAlignParagraphRight;   WordApplication.Selection.TypeText('第');   v1:=wdFieldPage;v2:=EmptyParam;v3:=EmptyParam;   WordApplication.Selection.Fields.Add(WordApplication.Selection.Range,v1,v2,v3);   WordApplication.Selection.TypeText('/');   v1:=wdFieldNumPages;v2:=EmptyParam;v3:=EmptyParam;   WordApplication.Selection.Fields.Add(WordApplication.Selection.Range,v1,v2,v3);   WordApplication.Selection.TypeText('页');   v1:=wdLine; v2:=EmptyParam;   WordApplication.Selection.HomeKey(v1,v2);   v1:=wdLine; v2:=wdExtend;   WordApplication.Selection.EndKey(v1,v2);   WordApplication.Selection.Borders.Item(wdBorderTop).LineStyle:=WordApplication.Options.DefaultBorderLineStyle;   WordApplication.Selection.Borders.Item(wdBorderTop).LineWidth:=wdLineWidth050pt;   WordApplication.Selection.Borders.Item(wdBorderTop).ColorIndex:=WordApplication.Options.DefaultBorderColorIndex;

       WordApplication.ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader;   v1:=wdLine; v2:=EmptyParam;   WordApplication.Selection.HomeKey(v1,v2);   v1:=wdLine; v2:=wdExtend;   WordApplication.Selection.EndKey(v1,v2);   WordApplication.Selection.Borders.Item(wdBorderTop).LineStyle := wdLineStyleNone;   WordApplication.Selection.Borders.Item(wdBorderLeft).LineStyle := wdLineStyleNone;   WordApplication.Selection.Borders.Item(wdBorderBottom).LineStyle := wdLineStyleNone;   WordApplication.Selection.Borders.Item(wdBorderRight).LineStyle := wdLineStyleNone;   WordDocument.ActiveWindow.ActivePane.View.SeekView := wdSeekMainDocument;

        with WordDocument do    begin      j:=0;      for coli:=0 to (tempGrid as TDBGrid).FieldCount-1 do        if not (tempGrid as TDBGrid).DataSource.DataSet.FieldByName((tempGrid as TDBGrid).Columns[coli].FieldName).Visible then Continue        else inc(j);      //创建表格      tables.Add(WordDocument.Words.Last,(tempGrid as TDBGrid).DataSource.DataSet.RecordCount+1,j+1); //考虑加一个序号

          //完成表头      tables.Item(1).Cell(1,1).Width :=WordApplication.MillimetersToPoints(tXHLen); //序号      tables.Item(1).Cell(1,1).Range.Text:='序号';      //下面完成其它的表头部分      j:=2;      for coli:=0 to  (tempGrid as TDBGrid).FieldCount-1 do      begin        if not (tempGrid as TDBGrid).DataSource.DataSet.FieldByName((tempGrid as TDBGrid).Columns[coli].FieldName).Visible then Continue;        begin          tables.Item(1).Cell(1, j).Width :=WordApplication.MillimetersToPoints(ScreenPixelToMM((tempGrid as TDBGrid).Columns[coli].Width));          tables.Item(1).Cell(1, j).Range.Text:=(tempGrid as TDBGrid).Columns[coli].FieldName;        end;        inc(j);      end;

          //表格居中      WordApplication.Selection.Tables.Item(1).Rows.Alignment := wdAlignRowCenter;      //不允许跨页断行      WordApplication.Selection.Tables.Item(1).Rows.AllowBreakAcrossPages := 0;      //将数据填入表格      for rowi:=0 to  (tempGrid as TDBGrid).DataSource.DataSet.RecordCount-1 do      begin        tables.Item(1).Cell(rowi+2,1).Range.Set_Text(IntToStr(rowi+1));        tables.Item(1).Cell(rowi+2,1).Width :=WordApplication.MillimetersToPoints(tXHLen); //序号        i:=1;        for coli:=0 to (tempGrid as TDBGrid).FieldCount-1 do        begin          if not (tempGrid as TDBGrid).DataSource.DataSet.FieldByName((tempGrid as TDBGrid).Columns[coli].FieldName).Visible then Continue;          inc(i);          if i>=j then Break;          tables.Item(1).Cell(rowi+2,i).Range.Set_Text((tempGrid as TDBGrid).DataSource.DataSet.FieldByName((tempGrid as TDBGrid).Columns[coli].FieldName).AsString);          tables.Item(1).Cell(rowi+2,i).Width :=WordApplication.MillimetersToPoints(ScreenPixelToMM((tempGrid as TDBGrid).Columns[coli].Width));        end;        (tempGrid as TDBGrid).DataSource.DataSet.Next;      end;      (tempGrid as TDBGrid).DataSource.DataSet.First;    end;   //表头格式设置   v1:=wdStory; v2:=EmptyParam;   WordApplication.Selection.HomeKey(v1,v2);   v1:=wdLine; v2:=1; v3:=EmptyParam;   WordApplication.Selection.MoveDown(v1,v2,v3);   //在各页顶端以表头形式出现,office 2000 适用//   WordApplication.Selection.Tables.Item(1).Rows.HeadingFormat:= wdToggle;

       WordApplication.Selection.SelectRow;   WordApplication.Selection.ParagraphFormat.Alignment := wdAlignParagraphCenter;     //表格线条设置    WordApplication.Selection.Tables.Item(1).Select;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderLeft).LineStyle := wdLineStyleSingle;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderLeft).LineWidth := wdLineWidth100pt;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderLeft).ColorIndex := wdAuto;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderRight).LineStyle := wdLineStyleSingle;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderRight).LineWidth := wdLineWidth100pt;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderRight).ColorIndex := wdAuto;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderTop).LineStyle := wdLineStyleSingle;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderTop).LineWidth := wdLineWidth100pt;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderTop).ColorIndex := wdAuto;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderBottom).LineStyle := wdLineStyleSingle;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderBottom).LineWidth := wdLineWidth100pt;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderBottom).ColorIndex := wdAuto;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderHorizontal).LineStyle := wdLineStyleSingle;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderHorizontal).LineWidth := wdLineWidth050pt;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderHorizontal).ColorIndex := wdAuto;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderVertical).LineStyle := wdLineStyleSingle;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderVertical).LineWidth := wdLineWidth050pt;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderVertical).ColorIndex := wdAuto;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderDiagonalDown).LineStyle := wdLineStyleNone;    WordApplication.Selection.Tables.Item(1).Borders.Item(wdBorderDiagonalUp).LineStyle := wdLineStyleNone;    WordApplication.Selection.Tables.Item(1).Borders.Shadow := False;    v1:=wdStory; v2:=EmptyParam;    WordApplication.Selection.HomeKey(v1,v2);  except    on E: Exception do    begin      ShowMessage(E.Message);    end;  end;  WordApplication.Disconnect;  WordFont.Free;  WordParagraphFormat.Free;  WordDocument.Free;  WordApplication.Free;end;

     

     

    /RE: 我在delphi利用server的控件,我将dbgrid生成表格,但是怎样修改word的页眉和页脚? ID=619754, 发贴富翁: dcsdcs, 发贴时间:2001-9-11 11:22:00以下是我写的部分控制表格和页眉、页脚的代码,欢迎大家参与讨论begin  try    Template := EmptyParam;    NewTemplate := false;    ItemIndex := 1;    try      Wordapplication.Connect;    except      MessageDlg('你没有安装WORD软件!', mtError, [mbOk], 0);      Abort;    end;    autoformat:=true;    Wordapplication.Visible := True;    WordApplication.Caption := '自动生成WORD文件表格';    Template := EmptyParam;    NewTemplate := False;    if ChkBoxNewDoc.Checked then    begin      WordApplication.Documents.Add(Template, NewTemplate);      WordDocument.ConnectTo(WordApplication.Documents.Item(ItemIndex));    end;//建立文档    WordApplication.Options.CheckSpellingAsYouType := False;    WordApplication.Options.CheckGrammarAsYouType := False;    pagew:=WordDocument.PageSetup.PageWidth-worddocument.PageSetup.Get_rightMargin-worddocument.PageSetup.Get_leftMargin;    //pagew是页面设置表格的总宽度        with WordDocument do        begintables.Add(WordDocument.Words.Last,self.DBGrid.DataSource.DataSet.RecordCount+1,self.DBGrid.DataSource.DataSet.FieldCount); //插入表格        gridw:=0;        for rowi:=0 to  dbgrid.Columns.Count-1 do //建立单元格宽度                begin                WordFont.ConnectTo(WordDocument.Sentences.Get_Last.Font);                WordFont.Bold := 1;                tables.Item(1).Cell(1,rowi+1).Range.Set_Text(DBGrid.Columns[rowi].Title.Caption);                gridw:=gridw+dbgrid.Columns[rowi].Width;                end;        for rowi:=0 to  dbgrid.Columns.Count-1 do            begin            grideveryw:=((dbgrid.Columns[rowi].Width-2) / gridw)*(pagew);            tables.Item(1).Columns.item(rowi+1).Set_Width(grideveryw);            end;        WordFont.ConnectTo(WordDocument.Sentences.Get_Last.Font);        WordFont.Bold := 0;        DBGrid.DataSource.DataSet.first;        for coli:=0 to  self.DBGrid.DataSource.DataSet.RecordCount-1 do            begin            for rowi:=0 to  dbgrid.Columns.Count-1 do                begin                try                    case DBGrid.Columns[rowi].Field.DataType of                    ftGraphic://如果是图                        begin                        DBImgFishImg.CopyToClipboard;                        tables.Item(1).Cell(coli+2,rowi+1).Range.Paste;                        end;                    ftMemo:                        begin                        tables.Item(1).Cell(coli+2,rowi+1).Range.Set_Text('简要介绍(略)');                        end;                    else                        tables.Item(1).Cell(coli+2,rowi+1).Range.Set_Text(DBGrid.DataSource.DataSet.Fields[rowi].AsString);                    end;                except                end;                end;            DBGrid.DataSource.DataSet.Next;            end;          end;    WordDocument.Range.PageSetup.Set_BottomMargin(100);    WordDocument.Range.InsertAfter('表格填写结束!');    worddocument.PageSetup.Set_Gutter(30);    worddocument.PageSetup.Set_GutterOnTop(true);    coli:=1;    with WordDocument do        begin            If ActiveWindow.View.SplitSpecial <> wdPaneNone Then                ActiveWindow.Panes.Item(2).Close;          //.Panes[2].Close;

            ActiveWindow.ActivePane.View.SeekView:=wdSeekCurrentPageHeader;//显示页眉        Application.Selection.ParagraphFormat.Alignment := wdAlignParagraphCenter;   //中间对齐        //wdAlignParagraphRight:右边对齐;        //wdAlignParagraphJustify:两边对齐;        //wdAlignParagraphLeft:左边对齐;        //wdAlignParagraphCenter:中间对齐;        Application.Selection.TypeText('dcsdcs初次开发的软件,设置页眉!酷吧!!!');        ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageFooter;//显示页脚        Application.Selection.ParagraphFormat.Alignment := wdAlignParagraphLeft;        Application.Selection.TypeText('dcsdcs初次开发的软件,设置页脚!酷吧!!!');        ActiveWindow.ActivePane.View.SeekView:=wdSeekMainDocument;        end;    BtnCloseWord.Enabled := True;    BtnPrint.Enabled := True;    BtnPreview.Enabled := True;  except    on E: Exception do    begin      ShowMessage(E.Message);      WordApplication.Disconnect;    end;  end;end;///RE: 如何在程序中生成一定格式的word文档? ID=453326, 发贴富翁: goah, 发贴时间:2001-2-11 1:18:00

    1.WORD OLE 服务器的连接:

    app_Word:TwordApplication;

     

      app_Word := TwordApplication.Create(self);

      app_Word.Connect;

        app_Word.Visible := true;

    2. WORD 文档的连结:

       doc_Word:TWordDocument;

     

       doc_Word:= TWordDocument.Create(self);

       app_Word.Documents.Add(EmptyParam,EmptyParam);

       doc_Word.Connect;

    3.WORD 字体的设置:

        app_Word.Selection.Font.Name :='黑体';

        app_Word.Selection.Font.Size := 16;

    4.WORD 对齐方式的设置:

    app_Word.Selection. ParagraphFormat. Alignment := wdAlignParagraphCenter;

    5.WORD 中输出文字:

        app_Word.Selection.TypeText(FPageHeader.Caption);

    6.WORD 中的换行:

       app_Word.Selection. TypeParagraph;

    7.WORD 中的表格的建立:

       tbl : Table;

      

    tbl := app_Word. ActiveDocument. Tables.Add(app_Word.Selection.Range,RowCount,ColCount);

    8.WORD 中光标的定位:

      app_Word.Selection.GoTo_(Var What,Which,Count,Name: OleVariant);

     

      What 取值:  (wdGoToBookmark,wdGoToSection,wdGoToPage,wdGoToTable,wdGoToLine,wdGoToFootnote,wdGoToEndnote,wdGoToComment,wdGoToField,wdGoToGraphic,wdGoToObject,wdGoToEquation,wdGoToHeading,wdGoToPercent,wdGoToSpellingError,wdGoToGrammaticalError,wdGoToProofreadingError)

     Which 取值:         (wdGoToFirst,wdGoToLast,,wdGoToNext,wdGoToRelative,wdGoToPrevious,wdGoToAbsolute)

     Count 取值:(1,2,3….)

     Name 取值:string;一般可以为’’;

    9.WORD 中光标的移动:

      app_Word.Selection.MoveRight(var Unit,Count,Extend: OleVariant);

     

      Unit 取值:      (wdCharacter,wdWord,wdSentence,wdParagraph,wdLine,wdStory,wdScreen,wdSection,wdColumn,wdRow,wdWindow,wdCell,wdCharacterFormatting,wdParagraphFormatting,wdTable,wdItem)

       Count 取值:(1,2,3…)

       Extend 取值:(wdMove,wdExtend)

     

    编程实例:

    unit Unit1;

     

    interface

     

    uses

      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

      StdCtrls,ComObj, Grids, OleServer, Word97;

     

    type

      TForm1 = class(TForm)

        Button1: TButton;

        grd_record: TStringGrid;

        app_Word: TWordApplication;

        doc_Word: TWordDocument;

        procedure Button1Click(Sender: TObject);

      private

        { Private declarations }

      public

        { Public declarations }

      end;

     

    var

      Form1: TForm1;

     

    implementation

     

    {$R *.DFM}

     

    procedure TForm1.Button1Click(Sender: TObject);

    var

       tbl : Table;

       i,j:integer;

       un_Var,ex_Var,cnt_Var:OleVariant;

    begin

      // 在Word中新建一个文档,并添加文本,然后设置粗体和字体大小

     

      app_Word.Connect;

      app_Word.Visible := True;

      app_Word.Documents.Add(EmptyParam,EmptyParam);

      doc_Word.Connect;

      app_word.ActiveWindow.View.Type_:= wdNormalView;

      app_Word.Selection.Font.Name :='黑体';

      app_Word.Selection.Font.Size := 16;

      app_Word.Selection.ParagraphFormat.Alignment := wdAlignParagraphCenter;

      app_Word.Selection.TypeText('常州市重点外商投资企业在建项目跟踪');

      app_Word.Selection.TypeParagraph;

      app_Word.Selection.TypeParagraph;

      app_Word.Selection.Font.Name :=  '宋体';

      app_Word.Selection.Font.Size :=12;

      app_Word.Selection.ParagraphFormat.Alignment := wdAlignParagraphRight;

      app_Word.Selection.TypeText('日期:2000年10月20日');

      app_Word.Selection.TypeParagraph;

      app_Word.Selection.TypeParagraph;

      app_Word.Selection.ParagraphFormat.Alignment := wdAlignParagraphLeft;

      tbl := app_Word.ActiveDocument.Tables.Add(app_Word.Selection.Range,grd_Record.RowCount,grd_Record.ColCount);

      un_Var:=wdCharacter;

      cnt_Var:=1;

      ex_Var:=wdMove;

      for i := 0 to grd_Record.RowCount-1 do    // Iterate

      begin

        for j := 0 to grd_Record.ColCount-1 do    // Iterate

        begin

          app_Word.Selection.TypeText(grd_Record.Cells[j,i]);

          app_Word.Selection.MoveRight(un_Var,cnt_Var,ex_Var);

        end;    // foror

        app_Word.Selection.MoveRight(un_Var,cnt_Var,ex_Var);

      end;    // foror

      app_Word.Selection.TypeText('制表人:');

      app_Word.Selection.TypeParagraph;

      self.Close;

    end;

     

    end./ 


    最新回复(0)