Comment automatiser Microsoft Word pour effectuer une fusion et publipostage à partir de Visual C #

Pour obtenir une version microsoft Visual Basic .NET de cet article, consultez 301656.

Résumé

Cet article montre comment automatiser Microsoft Word pour créer un document fusionné par courrier électronique à l’aide de Microsoft Visual C# 2005 ou Microsoft Visual C# .NET.

Informations supplémentaires

Automation est un processus qui permet aux applications écrites dans des langages tels que Visual C# 2005 ou Visual C# .NET de contrôler par programmation d’autres applications. L’automatisation de Word vous permet d’effectuer des actions telles que la création de nouveaux documents, l’ajout de texte à des documents et la mise en forme des documents. Avec Word et d’autres applications Microsoft Office, pratiquement toutes les actions que vous pouvez effectuer manuellement via l’interface utilisateur peuvent également être effectuées par programmation à l’aide d’Automation.

Word expose cette fonctionnalité de programmation par le biais d’un modèle objet. Le modèle objet est une collection de classes et de méthodes qui servent d’équivalents aux composants logiques de Word. Par exemple, il existe un objet Application, un objet Document et un objet Paragraph, chacun contenant les fonctionnalités de ces composants dans Word. Pour accéder au modèle objet à partir de Visual C# 2005 ou Visual C# .NET, vous pouvez définir une référence de projet à la bibliothèque de types.

Cet article montre comment définir la référence de projet appropriée à la bibliothèque de types Word pour Visual C# .NET et fournit un exemple de code pour automatiser Word.

Création de l’exemple Automation

  1. Démarrez Microsoft Visual Studio 2005 ou Microsoft Visual Studio .NET.

  2. Dans le menu Fichier, cliquez sur Nouveau, puis sur Projet. Sélectionnez Application Windows dans les types de projet Visual C#. Form1 est créé par défaut.

  3. Ajoutez une référence à la bibliothèque d’objets Microsoft Word 11.0 dans Visual Studio 2005 ou à la bibliothèque d’objets Microsoft Word dans Visual Studio .NET. Pour cela, procédez comme suit :

    1. Dans le menu Projet, cliquez sur Ajouter une référence.

    2. Sous l’onglet COM, recherchez la bibliothèque d’objets Microsoft Word, puis cliquez sur Sélectionner.

      Dans Visual Studio 2005, recherchez la bibliothèque d’objets Microsoft Word 11.0 sous l’onglet COM .

      Note Microsoft Office 2003 inclut des assemblys PIA (Primary Interop Assemblies). Microsoft Office XP n’inclut pas de codes confidentiels, mais ils peuvent être téléchargés.

    3. Cliquez sur OK dans la boîte de dialogue Ajouter des références pour accepter vos sélections.

  4. Dans le menu Affichage, sélectionnez Boîte à outils pour afficher la boîte à outils, puis ajoutez un bouton à Form1.

  5. Double-cliquez sur Button1. La fenêtre de code du formulaire s’affiche.

  6. Dans la fenêtre de code, remplacez le code suivant

      private void button1_Click(object sender, System.EventArgs e)
      {
      }
    
    

    avec :

    Word.Application wrdApp;
    Word._Document wrdDoc;
    Object oMissing = System.Reflection.Missing.Value;
    Object oFalse = false;
    
    private void InsertLines(int LineNum)
    {
    int iCount;
    
    // Insert "LineNum" blank lines.
    for(iCount = 1; iCount<=LineNum; iCount++) 
    {
    wrdApp.Selection.TypeParagraph();
    }
    }
    
    private void FillRow(Word._Document oDoc, int Row, string Text1,
    string Text2, string Text3, string Text4)
    {
    // Insert the data into the specific cell.
    oDoc.Tables[1].Cell(Row,1).Range.InsertAfter(Text1);
    oDoc.Tables[1].Cell(Row,2).Range.InsertAfter(Text2);
    oDoc.Tables[1].Cell(Row,3).Range.InsertAfter(Text3);
    oDoc.Tables[1].Cell(Row,4).Range.InsertAfter(Text4);
    }
    
    private void CreateMailMergeDataFile()
    {
    Word._Document oDataDoc;
    int iCount;
    
    Object oName = "C:\\DataDoc.doc";
    Object oHeader = "FirstName, LastName, Address, CityStateZip";
    wrdDoc.MailMerge.CreateDataSource(ref oName,ref oMissing, 
    ref oMissing,ref oHeader, ref oMissing, ref oMissing, 
    ref oMissing, ref oMissing, ref oMissing);
    
    // Open the file to insert data.
    oDataDoc = wrdApp.Documents.Open(ref oName,ref oMissing,
    ref oMissing, ref oMissing,ref oMissing,ref oMissing,
    ref oMissing,ref oMissing,ref oMissing,ref oMissing,
    ref oMissing,ref oMissing,ref oMissing,ref oMissing,
    ref oMissing/*, ref oMissing */);
    
    for (iCount=1; iCount<=2; iCount++)
    {
    oDataDoc.Tables[1].Rows.Add(ref oMissing);
    }
    // Fill in the data.
    FillRow(oDataDoc, 2, "Steve", "DeBroux", 
    "4567 Main Street", "Buffalo, NY  98052");
    FillRow(oDataDoc, 3, "Jan", "Miksovsky", 
    "1234 5th Street", "Charlotte, NC  98765");
    FillRow(oDataDoc, 4, "Brian", "Valentine", 
    "12348 78th Street  Apt. 214", 
    "Lubbock, TX  25874");
    // Save and close the file.
    oDataDoc.Save();
    oDataDoc.Close(ref oFalse, ref oMissing, ref oMissing);
    }
    
    private void button1_Click(object sender, System.EventArgs e)
    {
    Word.Selection wrdSelection;
    Word.MailMerge wrdMailMerge;
    Word.MailMergeFields wrdMergeFields;
    Word.Table wrdTable;
    string StrToAdd;
    
    // Create an instance of Word  and make it visible.
    wrdApp = new Word.Application();
    wrdApp.Visible = true;
    
    // Add a new document.
    wrdDoc = wrdApp.Documents.Add(ref oMissing,ref oMissing,
    ref oMissing,ref oMissing);
    wrdDoc.Select();
    
    wrdSelection = wrdApp.Selection;
    wrdMailMerge = wrdDoc.MailMerge;
    
    // Create a MailMerge Data file.
    CreateMailMergeDataFile();
    
    // Create a string and insert it into the document.
    StrToAdd = "State University\r\nElectrical Engineering Department";
    wrdSelection.ParagraphFormat.Alignment  = 
    Word.WdParagraphAlignment.wdAlignParagraphCenter;
    wrdSelection.TypeText(StrToAdd);
    
    InsertLines(4);
    
    // Insert merge data.
    wrdSelection.ParagraphFormat.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphLeft;
    wrdMergeFields = wrdMailMerge.Fields;
    wrdMergeFields.Add(wrdSelection.Range, "FirstName");
    wrdSelection.TypeText(" ");
    wrdMergeFields.Add(wrdSelection.Range, "LastName");
    wrdSelection.TypeParagraph();
    
    wrdMergeFields.Add(wrdSelection.Range, "Address");
    wrdSelection.TypeParagraph();
    wrdMergeFields.Add(wrdSelection.Range, "CityStateZip");
    
    InsertLines(2);
    
    // Right justify the line and insert a date field
    // with the current date.
    wrdSelection.ParagraphFormat.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphRight;
    
    Object objDate = "dddd, MMMM dd, yyyy";
    wrdSelection.InsertDateTime(ref objDate,ref oFalse,ref oMissing, 
    ref oMissing, ref oMissing);
    
    InsertLines(2);
    
    // Justify the rest of the document.
    wrdSelection.ParagraphFormat.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphJustify;    
    
    wrdSelection.TypeText("Dear ");
    wrdMergeFields.Add(wrdSelection.Range, "FirstName");
    wrdSelection.TypeText(",");
    InsertLines(2);
    
    // Create a string and insert it into the document.
    StrToAdd = "Thank you for your recent request for next " +
    "semester's class schedule for the Electrical " +
    "Engineering Department. Enclosed with this " +
    "letter is a booklet containing all the classes " +
    "offered next semester at State University.  " +
    "Several new classes will be offered in the " +
    "Electrical Engineering Department next semester.  " +
    "These classes are listed below.";
    wrdSelection.TypeText(StrToAdd);
    
    InsertLines(2);
    
    // Insert a new table with 9 rows and 4 columns.
    wrdTable = wrdDoc.Tables.Add(wrdSelection.Range,9,4, 
    ref oMissing, ref oMissing);
    // Set the column widths.
    wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone);
    wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone);
    wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
    wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone);
    // Set the shading on the first row to light gray.
    wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex = 
    Word.WdColorIndex.wdGray25;
    // Bold the first row.
    wrdTable.Rows[1].Range.Bold = 1;
    // Center the text in Cell (1,1).
    wrdTable.Cell(1, 1).Range.Paragraphs.Alignment = 
    Word.WdParagraphAlignment.wdAlignParagraphCenter;
    
    // Fill each row of the table with data.
    FillRow(wrdDoc, 1, "Class Number", "Class Name", 
    "Class Time", "Instructor");
    FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II", 
    "1:00-2:00 M,W,F", "Dr. Jensen");
    FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I", 
    "10:00-11:30 T,T", "Dr. Crump");
    FillRow( wrdDoc, 4, "EE300", "Feedback Control Systems", 
    "9:00-10:00 M,W,F", "Dr. Murdy");
    FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design", 
    "9:00-10:30 T,T", "Dr. Alley");
    FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems", 
    "9:00-10:30 T,T", "Dr. Taylor");
    FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory", 
    "1:00-2:30 T,T", "Dr. Lee");
    FillRow(wrdDoc, 8, "EE450", "Plasma Theory",
    "1:00-2:00 M,W,F", "Dr. Davis");
    FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design", 
    "3:00-4:00 M,W,F", "Dr. Ellison");
    
    // Go to the end of the document.
    Object oConst1 = Word.WdGoToItem.wdGoToLine;
    Object oConst2 = Word.WdGoToDirection.wdGoToLast;
    wrdApp.Selection.GoTo(ref oConst1,ref oConst2,ref oMissing,ref oMissing);
    InsertLines(2);
    
    // Create a string and insert it into the document.
    StrToAdd = "For additional information regarding the " +
    "Department of Electrical Engineering, " +
    "you can visit our Web site at ";
    wrdSelection.TypeText(StrToAdd);
    // Insert a hyperlink to the Web page.
    Object oAddress = "http://www.ee.stateu.tld";
    Object oRange = wrdSelection.Range;
    wrdSelection.Hyperlinks.Add(oRange, ref oAddress,ref oMissing,
    ref oMissing, ref oMissing, ref oMissing);
    // Create a string and insert it into the document
    StrToAdd = ".  Thank you for your interest in the classes " +
    "offered in the Department of Electrical " +
    "Engineering.  If you have any other questions, " +
    "please feel free to give us a call at " +
    "555-1212.\r\n\r\n"  +
    "Sincerely,\r\n\r\n" +
    "Kathryn M. Hinsch\r\n" +
    "Department of Electrical Engineering \r\n";
    wrdSelection.TypeText(StrToAdd);
    
    // Perform mail merge.
    wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
    wrdMailMerge.Execute(ref oFalse);
    
    // Close the original form document.
    wrdDoc.Saved = true;
    wrdDoc.Close(ref oFalse,ref oMissing,ref oMissing);
    
    // Release References.
    wrdSelection = null;
    wrdMailMerge = null;
    wrdMergeFields = null;
    wrdDoc = null;
    wrdApp = null;
    
    // Clean up temp file.
    System.IO.File.Delete("C:\\DataDoc.doc");
    } 
    
    

    Note Vous devez modifier le code dans Visual Studio 2005. Par défaut, Visual C# ajoute un formulaire au projet lorsque vous créez un projet Windows Forms. Le formulaire est nommé Form1. Les deux fichiers qui représentent le formulaire sont nommés Form1.cs et Form1.designer.cs. Vous écrivez le code dans Form1.cs. Le fichier Form1.designer.cs est l’endroit où le concepteur Windows Forms écrit le code qui implémente toutes les actions que vous avez effectuées en faisant glisser et en supprimant des contrôles de la boîte à outils.

    Pour plus d’informations sur le concepteur Windows Forms dans Visual C# 2005, visitez le site web Microsoft Developer Network (MSDN) suivant : création d’un projet (Visual C#)Remarque Microsoft Office Word 2003 contient un argument supplémentaire pour la méthode Open du document. Si vous utilisez l’assembly PIA Word 2003, supprimez la notation de commentaire pour le paramètre supplémentaire de la méthode Open.

  7. Ajoutez ce qui suit en haut de Form1.cs :

    using Word = Microsoft.Office.Interop.Word;
    
    
  8. Appuyez sur F5 pour générer et exécuter le programme.

  9. Cliquez sur Button1 pour démarrer Word Automation et effectuer le publipostage.

References

Pour plus d’informations, visitez le site web Microsoft Developer Network (MSDN) suivant : Développement Microsoft Office avec Visual Studio Microsoft Office Development avec Visual Studio

Pour plus d’informations, cliquez sur le numéro d’article suivant pour afficher l’article dans la Base de connaissances Microsoft :

285332 Comment automatiser Word 2002 avec Visual Basic pour créer une fusion et publipostage