A more complete example of a C # operation word document

This article mainly introduces a relatively complete C # operation word document example.This article summarizes my own project experience. This article also gives an example.This example includes some commonly used pictures, texts, tables, formulas for editing and typesetting. As well as the operation of page setting, header and page number, friends who need it can refer to

In the past two days, I have studied how to use VS2008 (C # language) to output Word documents. Here are a few summary:

1. Very simple.

2. Development and operating environment requirements. The operating system is: WindowsXP (installing .net framework2.0) / Vista / Win7; Word2003 must be installed in the operating system. It must be emphasized here that Word2003 is a fully installed version, because software development and operation requires a com component: Microsoft word 11.0 Object Library. If it is not the fully installed version of Word2003, you can download this com component and manually install this com component. The download address is: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20923 , the file is not large, only about 4M.

3. C # project settings. The engineering setting here is to add the com component. The steps are: "Add Reference"-> "com" tab in the Project Explorer-> select Microsoft word 11.0 Object Library in the drop-down list. Ok, looks like it is the same as adding a general dll, but actually vs2008 completes a series of complex operations about .net calling com components during this process, but fortunately we don't have to worry about this.

4. The next step is to write the code. Here, the com object using Word is very smooth like the normal non-com object. It seems that it doesn't matter what com is not com at all. In order to make the code more concise, you can add this statement at the top of the source code file: using Word = Microsoft.Office.Interop.Word;

5. It is best to have a certain understanding of the word image model, so that when writing code, it will not be so "confusing". There are several more important objects in the wore object model. They are Application, Document, Selection, Range, Bookmark, and other objects, such as: Paragraph, Section, Table level. When I first started learning, I felt that Selection, Range, and Bookmark were a bit confusing. Selection may be easy to understand. It means the current selection area. If there is no selection, it means the cursor position. Range and Bookmark are actually similar in many places, but there are some differences. I won't say much here, just google "word.Range".

6. In the process of writing code, I often want to implement some operations, but I don't know how to implement it with code because I am not familiar with the word object. For example, setting headers, adding page numbers and the like, if the manual operation in the Word program is of course very simple, but it is not easy for beginners to use code to achieve. In this case, there are generally two methods to choose from: one is the "Baidu / google method", the other is also the one I recommend is to use Word's "record macro" function to achieve After the operation is recorded as a macro, look at the code in the macro. The code in the macro is almost the code you want (only the syntax is slightly different).

7. An example is given below. This example includes some common graphics, text, table, formula editing and layout, as well as page settings, headers, and page number operations. There are comments in it, which are very clearly written.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices; 

namespace WindowsFormsApplication1
{
  public partial class Form1 :System.Windows.Forms. Form
  {

    [DllImport("shell32.dll ")]
    public static extern int ShellExecute(IntPtr hwnd, String lpszOp, String lpszFile, String lpszParams, String lpszDir, int FsShowCmd); 
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      // New document
      // Word.Application newapp = new Word.Application (); // You can also use this sentence to initialize
      Word.Application newapp = new Word.ApplicationClass();
      Word.Document newdoc;
      object nothing = System.Reflection.Missing.Value; // Used as the default parameter of the function
      newdoc = newapp.Documents.Add (ref nothing, ref nothing, ref nothing, ref nothing); // Generate a word document
      newapp.Visible = true; // Whether to display the word program interface

      //page settings
      //newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape ;
      //newdoc.PageSetup.PageWidth = newapp.CentimetersToPoints(21.0f);
      //newdoc.PageSetup.PageHeight = newapp.CentimetersToPoints(29.7f);
      newdoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;
      newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait;
      newdoc.PageSetup.TopMargin = 57.0f;
      newdoc.PageSetup.BottomMargin = 57.0f;
      newdoc.PageSetup.LeftMargin = 57.0f;
      newdoc.PageSetup.RightMargin = 57.0f;
      newdoc.PageSetup.HeaderDistance = 30.0f; // Header position

      // Set header
      newapp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView; // View style.
      newapp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader; // Enter the header setting, where the header margin is completed in the page setting
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      // Insert header image
      string headerfile = "d:\\header.jpg";
      this.outpicture(headerfile, Properties.Resources.header);
      Word.InlineShape shape1= newapp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref nothing, ref nothing, ref nothing);
      shape1.Height = 30;
      shape1.Width = 80;
      newapp.ActiveWindow.ActivePane.Selection.InsertAfter ("China Construction Northeast Hospital");
      // Remove the horizontal line from the header
      newapp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone;
      newapp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false;
      newapp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument; // Exit header settings

      // Add page number
      Word.PageNumbers pns= newapp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;
      pns.NumberStyle = Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
      pns.HeadingLevelForChapter = 0;
      pns.IncludeChapterNumber = false;
      pns.ChapterPageSeparator = Word.WdSeparatorType.wdSeparatorHyphen;
      pns.RestartNumberingAtSection = false;
      pns.StartingNumber = 0;
      object pagenmbetal = Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
      object first=true; 
      newapp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages ].PageNumbers.Add(ref pagenmbetal, ref first);

      // Text setting (Selection means the current selection set, if no object is currently selected, it means setting the cursor position)
      newapp.Selection.Font.Size = 14;
      newapp.Selection.Font.Bold = 0;
      newapp.Selection.Font.Color = Word.WdColor.wdColorBlack;
      newapp.Selection.Font.Name = "宋体";

      // paragraph settings
      newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
      newapp.Selection.ParagraphFormat.LineSpacing = 20;
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
      newapp.Selection.ParagraphFormat.FirstLineIndent = 30;
      newdoc.Content.InsertAfter( WindowsFormsApplication1.Properties.Resources.PreViewWords);
      
      

      // insert formula
      object oEndOfDoc="\\endofdoc";
      Word.Range rang1 = newdoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
      object fieldType = Word.WdFieldType.wdFieldEmpty;
      object formula = @"eq \i(a,b,ξxdx)";
      object presrveFormatting = false;
      rang1.Text = formula.ToString();
      rang1.Font.Size = 14;
      rang1.Font.Bold = 0;
      rang1.Font.Subscript = 0;
      rang1.Font.Color = Word.WdColor.wdColorBlue;
      rang1.Font.Name = "Song Dynasty";
      rang1.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
      rang1.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      newdoc.Fields.Add(rang1, ref fieldType, ref formula, ref presrveFormatting);

      // Replace the first three words of the document with "asdfasdf" and set its color to blue
      object start=0;
      object end=3;
      Word.Range rang2 = newdoc.Range(ref start, ref end);
      rang2.Font.Color = Word.WdColor.wdColorBlue;
      rang2.Text = "as签";

      // Replace "as" at the beginning of the document with "Yuan Bo"
      rang1.Start = 0;
      rank1.End = 2;
      rang1.Text = "This is one";
      rang1.InsertAfter("书");
      //rang1.Select();
      object codirection = Word.WdCollapseDirection.wdCollapseStart;
      rang1.Collapse (ref codirection); // Set the starting point and end point of rang1 to the starting point or end point

      // Bold the first three characters
      newdoc.Range(ref start, ref end).Bold = 1;
      object rang = rang2;
      newdoc.Bookmarks.Add("yb",ref rang);
      
      
      object unite = Word.WdUnits.wdStory;
      newapp.Selection.EndKey (ref unite, ref nothing); // Move the cursor to the end of the article
      newapp.Selection.Font.Size = 10;
      newapp.Selection.TypeText("...............................(式1)\n");


      // Insert picture
      newapp.Selection.EndKey (ref unite, ref nothing); // Move the cursor to the end of the article
      //newapp.Selection.HomeKey(ref unite, ref nothing); // Move the cursor to the beginning of the text
      newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      object LinkToFile = false;
      object SaveWithDocument = true;
      object Anchor = newapp.Selection.Range;
      string picname = "d:\\kk.jpg";
      this.outpicture(picname, Properties.Resources.IMG_2169);
      newdoc.InlineShapes.AddPicture(picname, ref LinkToFile, ref SaveWithDocument, ref Anchor);
      newdoc.InlineShapes[1].Height = 200;
      newdoc.InlineShapes[1].Width = 200;
      newdoc.Content.InsertAfter("\n");
      newapp.Selection.EndKey (ref unite, ref nothing); // Move the cursor to the end of the article
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.Font.Size = 10;
      newapp.Selection.TypeText ("Figure 1 Yuan Ye \ n");
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      newdoc.Content.InsertAfter("\n"); 
      newdoc.Content.InsertAfter("\n");

      // You can also insert formulas in this way, and this method is simpler
      newapp.Selection.Font.Size = 14;
      newapp.Selection.InsertFormula(ref formula, ref nothing);
      newapp.Selection.Font.Size = 10;
      newapp.Selection.TypeText("..............................(式2)\n");
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.TypeText ("Table 1 Electronic Products \ n");

      // insert table
      Word.Table table1 = newdoc.Tables.Add(newapp.Selection.Range, 4, 3, ref nothing, ref nothing);
      newdoc.Tables [1] .Cell (1, 1) .Range.Text = "Product \ nProject";
      newdoc.Tables [1] .Cell (1, 2) .Range.Text = "Computer";
      newdoc.Tables [1] .Cell (1, 3) .Range.Text = "Mobile";
      newdoc.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
      newdoc.Tables [1] .Cell (3, 1) .Range.Text = "Price (yuan)";
      newdoc.Tables [1] .Cell (4, 1) .Range.Text = "Common Information";
      newdoc.Tables[1].Cell(4, 2).Range.Text = "信息A";
      newdoc.Tables[1].Cell(4,3).Range.Text = "信息B";
      

      table1.Select();
      table1.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter; // The entire table is centered
      newapp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.Cells.HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
      newapp.Selection.Cells.Height = 40;
      table1.Rows[2].Height = 20;
      table1.Rows[3].Height = 20;
      table1.Rows[4].Height = 20;
      table1.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.Cells.Width=150;
      table1.Columns[1].Width = 75;
      table1.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

      
      

      // Header slash
      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown ].Visible = true;
      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Word.WdColor.wdColorGreen;
      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

      // Table border
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal ].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom ].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop ].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

      //Merge Cells
      newdoc.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));

      // Delete the picture
      this.delpictfile(headerfile);
      this.delpictfile(picname);


      // Save the document
      object name = "c:\\yb3.doc";
      newdoc.SaveAs(ref name, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
             ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
             ref nothing, ref nothing);
      
      // Close the document
      object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
      newdoc.Close(ref nothing , ref nothing, ref nothing);
      newapp.Application.Quit(ref saveOption, ref nothing, ref nothing);
      newdoc = null;
      newapp = null;
      ShellExecute(IntPtr.Zero, "open", "c:\\yb3.doc", "", "", 3);
    }

    private void outpicture(string filename,System.Drawing.Bitmap bmap)
    {
      bmap.Save(filename);
    }

    private void delpictfile(string filename)
    {
      System.IO.File.Delete(filename);
    }
   
  }

} 
Quoted at https://m.jb51.net/article/67314.htm

Guess you like

Origin www.cnblogs.com/tonychenhan/p/12755106.html