Come automatizzare Microsoft Word per creare un nuovo documento usando Visual C #

Per una versione di Microsoft Visual Basic .NET di questo articolo, vedere

Riepilogo

Questo articolo dettagliato descrive come creare un nuovo documento in Microsoft Word usando Automazione da Microsoft Visual C# 2005 o Microsoft Visual C# .NET.

Codice di esempio

Il codice di esempio in questo articolo illustra come eseguire le operazioni seguenti:

  • Inserire paragrafi con testo e formattazione.
  • Esplorare e modificare vari intervalli all'interno di un documento.
  • Inserire tabelle, formattare le tabelle e popolare le tabelle con i dati.
  • Aggiungere un grafico.

Per creare un nuovo documento di Word usando Automazione da Visual C# 2005 o Visual C# .NET, seguire questa procedura:

  1. Avviare Microsoft Visual Studio 2005 o Microsoft Visual Studio .NET.

  2. Scegliere Nuovo dal menu File e quindi fare clic su Progetto. In Tipi di progetto fare clic su Progetti Visual C# e quindi su Applicazione Windows in Modelli. Form1 viene creato per impostazione predefinita.

    Nota In Visual Studio 2005 fare clic su Visual C# anziché Su progetti Visual C#.

  3. Aggiungere un riferimento alla libreria di oggetti di Microsoft Word. A tal fine, attenersi alla seguente procedura:

    1. Scegliere Aggiungi riferimento dal menu Progetto.
    2. Nella scheda COM individuare Raccolta oggetti di Microsoft Word e quindi fare clic su Seleziona.

    Nota In Visual Studio 2005 non è necessario fare clic su Seleziona.

    Nota Microsoft Office 2003 include assembly di interoperabilità primari ( PIA). Microsoft Office XP non include FUNZIONALITÀ personali, ma può essere scaricato.

    1. Fare clic su OK nella finestra di dialogo Aggiungi riferimenti per accettare le selezioni. Se viene richiesto di generare wrapper per le librerie selezionate, fare clic su Sì.
  4. Nel menu Visualizza selezionare Casella degli strumenti per visualizzare la casella degli strumenti e quindi aggiungere un pulsante a Form1.

  5. Fare doppio clic su Button1. Viene visualizzata la finestra del codice per il modulo.

  6. Nella finestra del codice sostituire il codice seguente:

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

    Con:

    private void button1_Click(object sender, System.EventArgs e)
    {
    object oMissing = System.Reflection.Missing.Value;
    object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 
    
    //Start Word and create a new document.
    Word._Application oWord;
    Word._Document oDoc;
    oWord = new Word.Application();
    oWord.Visible = true;
    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
    ref oMissing, ref oMissing);
    
    //Insert a paragraph at the beginning of the document.
    Word.Paragraph oPara1;
    oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara1.Range.Text = "Heading 1";
    oPara1.Range.Font.Bold = 1;
    oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
    oPara1.Range.InsertParagraphAfter();
    
    //Insert a paragraph at the end of the document.
    Word.Paragraph oPara2;
    object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara2.Range.Text = "Heading 2";
    oPara2.Format.SpaceAfter = 6;
    oPara2.Range.InsertParagraphAfter();
    
    //Insert another paragraph.
    Word.Paragraph oPara3;
    oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
    oPara3.Range.Font.Bold = 0;
    oPara3.Format.SpaceAfter = 24;
    oPara3.Range.InsertParagraphAfter();
    
    //Insert a 3 x 5 table, fill it with data, and make the first row
    //bold and italic.
    Word.Table oTable;
    Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;
    int r, c;
    string strText;
    for(r = 1; r <= 3; r++)
    for(c = 1; c <= 5; c++)
    {
    strText = "r" + r + "c" + c;
    oTable.Cell(r, c).Range.Text = strText;
    }
    oTable.Rows[1].Range.Font.Bold = 1;
    oTable.Rows[1].Range.Font.Italic = 1;
    
    //Add some text after the table.
    Word.Paragraph oPara4;
    oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara4.Range.InsertParagraphBefore();
    oPara4.Range.Text = "And here's another table:";
    oPara4.Format.SpaceAfter = 24;
    oPara4.Range.InsertParagraphAfter();
    
    //Insert a 5 x 2 table, fill it with data, and change the column widths.
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;
    for(r = 1; r <= 5; r++)
    for(c = 1; c <= 2; c++)
    {
    strText = "r" + r + "c" + c;
    oTable.Cell(r, c).Range.Text = strText;
    }
    oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
    oTable.Columns[2].Width = oWord.InchesToPoints(3);
    
    //Keep inserting text. When you get to 7 inches from top of the
    //document, insert a hard page break.
    object oPos;
    double dPos = oWord.InchesToPoints(7);
    oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
    do
    {
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    wrdRng.ParagraphFormat.SpaceAfter = 6;
    wrdRng.InsertAfter("A line of text");
    wrdRng.InsertParagraphAfter();
    oPos = wrdRng.get_Information
                           (Word.WdInformation.wdVerticalPositionRelativeToPage);
    }
    while(dPos >= Convert.ToDouble(oPos));
    object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    object oPageBreak = Word.WdBreakType.wdPageBreak;
    wrdRng.Collapse(ref oCollapseEnd);
    wrdRng.InsertBreak(ref oPageBreak);
    wrdRng.Collapse(ref oCollapseEnd);
    wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
    wrdRng.InsertParagraphAfter();
    
    //Insert a chart.
    Word.InlineShape oShape;
    object oClassType = "MSGraph.Chart.8";
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, 
    ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing);
    
    //Demonstrate use of late bound oChart and oChartApp objects to
    //manipulate the chart object with MSGraph.
    object oChart;
    object oChartApp;
    oChart = oShape.OLEFormat.Object;
    oChartApp = oChart.GetType().InvokeMember("Application",
    BindingFlags.GetProperty, null, oChart, null);
    
    //Change the chart type to Line.
    object[] Parameters = new Object[1];
    Parameters[0] = 4; //xlLine = 4
    oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
    null, oChart, Parameters);
    
    //Update the chart image and quit MSGraph.
    oChartApp.GetType().InvokeMember("Update",
    BindingFlags.InvokeMethod, null, oChartApp, null);
    oChartApp.GetType().InvokeMember("Quit",
    BindingFlags.InvokeMethod, null, oChartApp, null);
    //... If desired, you can proceed from here using the Microsoft Graph 
    //Object model on the oChart and oChartApp objects to make additional
    //changes to the chart.
    
    //Set the width of the chart.
    oShape.Width = oWord.InchesToPoints(6.25f);
    oShape.Height = oWord.InchesToPoints(3.57f);
    
    //Add text after the chart.
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    wrdRng.InsertParagraphAfter();
    wrdRng.InsertAfter("THE END.");
    
    //Close this form.
    this.Close();
    }
    
  7. Scorrere fino alla parte superiore della finestra del codice. Aggiungere la riga seguente alla fine dell'elenco delle direttive using:

    using Word = Microsoft.Office.Interop.Word;
    using System.Reflection;
    
  8. Premere F5 per compilare ed eseguire il programma.

  9. Fare clic su Button1 per avviare Automazione word e per creare il documento.

Al termine del codice, esaminare automaticamente il documento creato. Il documento contiene due pagine di paragrafi formattati, tabelle e un grafico.

Usare un modello

Se si usa Automazione per compilare documenti tutti in un formato comune, è possibile trarre vantaggio dall'avvio del processo con un nuovo documento basato su un modello preformattato. L'uso di un modello con il client di automazione di Word presenta due vantaggi significativi rispetto alla creazione di un documento dal nulla:

  • È possibile avere un maggiore controllo sulla formattazione e il posizionamento degli oggetti in tutti i documenti.
  • È possibile compilare i documenti con meno codice.

Usando un modello, è possibile ottimizzare il posizionamento di tabelle, paragrafi e altri oggetti all'interno del documento, nonché includere la formattazione su tali oggetti. Usando Automazione, è possibile creare un nuovo documento basato sul modello con codice simile al seguente:

object oTemplate = "c:\\MyTemplate.dot";
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
ref oMissing, ref oMissing);

Nel modello è possibile definire segnalibri in modo che il client di Automazione possa compilare testo variabile in una posizione specifica del documento, come indicato di seguito:

object oBookMark = "MyBookmark";
oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

Un altro vantaggio dell'uso di un modello è la possibilità di creare e archiviare gli stili di formattazione che si desidera applicare in fase di esecuzione, come indicato di seguito:

object oStyleName = "MyStyle";
oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

oppure

object oStyleName = "MyStyle";
oWord.Selection.set_Style(ref oStyleName);

Riferimenti

Per altre informazioni, vedere gli articoli della Microsoft Knowledge Base: