2008-11-12 13 views
3

J'ai une application C# où je veux implémenter une logique pour un programme qui va ouvrir le document Word et aller à un certain endroit dans la page et créer une table et mettre des valeurs dans cette. Quelqu'un peut-il me dire comment mettre en œuvre cela. J'utilise Visual Studio 2005Création de tables dynamiques dans Word par C# .NET

+1

(re votre commentaire à moi) Je déteste vous dire ceci, mais Word n'est pas une application gérée. Donc, pour utiliser l'application Word elle-même, vous devrez utiliser l'API COM ... l'alternative est d'utiliser un outil tiers pour écrire des fichiers Word directement (plus facile avec .docx qu'avec .doc). –

Répondre

3

Recherchez "Word Automation".

Par exemple, KB316384, qui couvre:

L'exemple de code dans cet article montre comment effectuer les opérations suivantes:

  • Insérer les paragraphes avec le texte et la mise en forme.
  • Parcourir et modifier différentes plages d'un document.
  • Insérez des tables, formatez des tables et remplissez les tables avec des données.
  • Ajouter un graphique.
+0

Merci.Mais je suis à la recherche d'une solution qui utilise .NET référence au lieu de référence COM.Recherche beaucoup.Mais impossible de trouver .Can un? –

0

Si vous ne souhaitez pas utiliser Word Automation, par ex. vous n'avez pas Word installé sur l'ordinateur exécutant votre programme, vous devriez jeter un oeil à Aspose.Words.

Le seul problème est que ce n'est pas gratuit.

0

Word ouvrira très heureusement un fichier au format HTML avec l'extension .Doc. Vous pouvez avoir tout le formatage souhaité en utilisant une feuille de style interne. Une question similaire est venu ici:

Export to Word Document in C#

4

Voici le code à copier datagridview à une table de mots:

Référence est Microsoft.Office.Interop.Word C: \ Program Files (x86) \ Microsoft Visual studio 10.0 \ Visual studio Tools pour office \ PIA \ Office12 \ Microsoft.Office.Interop.Word.dll

using word = Microsoft.Office.Interop.Word;  
public static void ExportToWord(DataGridView dgv) 
       { 
        SendMessage("Opening Word"); 

        word.ApplicationClass word = null; 



     word.Document doc = null; 
      object oMissing = System.Reflection.Missing.Value; 
      object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 
      try 
      { 
       word = new word.ApplicationClass(); 
       word.Visible = true; 
       doc = word.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing); 
      } 
      catch (Exception ex) 
      { 
       ErrorLog(ex); 
      } 
      finally 
      { 
      } 
      if (word != null && doc != null) 
      { 
       word.Table newTable; 
       word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
       newTable = doc.Tables.Add(wrdRng, 1, dgv.Columns.Count-1, ref oMissing, ref oMissing); 
       newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; 
       newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; 
       newTable.AllowAutoFit = true; 

       foreach (DataGridViewCell cell in dgv.Rows[0].Cells) 
       { 
        newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = dgv.Columns[cell.ColumnIndex].Name; 

       } 
       newTable.Rows.Add(); 

       foreach (DataGridViewRow row in dgv.Rows) 
       { 
        foreach (DataGridViewCell cell in row.Cells) 
        { 
         newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = cell.Value.ToString();      
        } 
        newTable.Rows.Add(); 
       }            
      } 

     } 
0

Vous pouvez essayer ma méthode pour exporter des données vers Word (* .docx), il est facile utiliser et travailler à 100% avec n'importe quel DataGr idView, il suffit d'ajouter Microsoft.Office.Interop.Word référence et copiez le code suivant:

using Word = Microsoft.Office.Interop.Word; 

    public void Export_Data_To_Word(DataGridView DGV, string filename) 
    { 
    if (DGV.Rows.Count != 0) 
    { 
     int RowCount = DGV.Rows.Count; 
     int ColumnCount = DGV.Columns.Count; 
     Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; 

     //add rows 
     int r = 0; 
     for (int c = 0; c <= ColumnCount - 1; c++) 
     { 
      for (r = 0; r <= RowCount - 1; r++) 
      { 
       DataArray[r, c] = DGV.Rows[r].Cells[c].Value; 
      } //end row loop 
     } //end column loop 

     Word.Document oDoc = new Word.Document(); 
     oDoc.Application.Visible = true; 

     //page orintation 
     oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; 


     dynamic oRange = oDoc.Content.Application.Selection.Range; 
     string oTemp = ""; 
     for (r = 0; r <= RowCount - 1; r++) 
     { 
      for (int c = 0; c <= ColumnCount - 1; c++) 
      { 
       oTemp = oTemp + DataArray[r, c] + "\t"; 

      } 
     } 

     //table format 
     oRange.Text = oTemp; 

     object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; 
     object ApplyBorders = true; 
     object AutoFit = true; 
     object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; 

     oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, 
           Type.Missing, Type.Missing, ref ApplyBorders, 
           Type.Missing, Type.Missing, Type.Missing, 
           Type.Missing, Type.Missing, Type.Missing, 
           Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); 

     oRange.Select(); 

     oDoc.Application.Selection.Tables[1].Select(); 
     oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; 
     oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; 
     oDoc.Application.Selection.Tables[1].Rows[1].Select(); 
     oDoc.Application.Selection.InsertRowsAbove(1); 
     oDoc.Application.Selection.Tables[1].Rows[1].Select(); 

     //header row style 
     oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; 
     oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma"; 
     oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14; 

     //add header row manually 
     for (int c = 0; c <= ColumnCount - 1; c++) 
     { 
      oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText; 
     } 

     //table style 
     oDoc.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5"); 
     oDoc.Application.Selection.Tables[1].Rows[1].Select(); 
     oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; 

     //header text 
     foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) 
     { 
      Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; 
      headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); 
      headerRange.Text = "your header text"; 
      headerRange.Font.Size = 16; 
      headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; 
     } 

     //save the file 
     oDoc.SaveAs2(filename); 

     //NASSIM LOUCHANI 
    } 
    } 




    private void button_Click(object sender, EventArgs e) 
    { 
    SaveFileDialog sfd = new SaveFileDialog(); 

    sfd.Filter = "Word Documents (*.docx)|*.docx"; 

    sfd.FileName = "export.docx"; 

    if (sfd.ShowDialog() == DialogResult.OK) 
    { 

     Export_Data_To_Word(dataGridView1, sfd.FileName); 
    } 
    } 

Merci.

Questions connexes