通过 C#.NET 在 Word 中创建动态表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/283523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:34:12  来源:igfitidea点击:

Creating Dynamic Tables in Word by C#.NET

c#dynamicms-word

提问by

I have a C# application where i want to implement a logic for a programm which will open the word document and go to a certain place in the page and create a Table and put values in that. Can any one tell me how to implement this. I am using Visual studio 2005

我有一个 C# 应用程序,我想在其中实现一个程序逻辑,该程序将打开 word 文档并转到页面中的某个位置并创建一个表并将值放入其中。谁能告诉我如何实现这一点。我正在使用 Visual Studio 2005

回答by Marc Gravell

Look up "Word Automation".

查找“单词自动化”。

For example, KB316384, which covers:

例如,KB316384,它涵盖:

The sample code in this article demonstrates how to do the following:

本文中的示例代码演示了如何执行以下操作:

  • Insert paragraphs with text and formatting.
  • Browse and modify various ranges within a document.
  • Insert tables, format tables, and populate the tables with data.
  • Add a chart.
  • 插入带有文本和格式的段落。
  • 浏览和修改文档中的各种范围。
  • 插入表格、格式化表格并用数据填充表格。
  • 添加图表。

回答by Marc Gravell

If you don't want to use Word Automation, e.g. you don't have Word installed on the computer running your program, you should have a look at Aspose.Words.

如果您不想使用 Word Automation,例如您没有在运行程序的计算机上安装 Word,您应该查看Aspose.Words

The only problem is that it's not free.

唯一的问题是它不是免费的。

回答by Fionnuala

Word will quite happily open a file in HTML with the extension .Doc. You can have all the formatting you want by using an internal style sheet. A very similar question came up here:

Word 会很高兴地打开一个扩展名为 .Doc 的 HTML 文件。通过使用内部样式表,您可以拥有所需的所有格式。这里出现了一个非常相似的问题:

Export to Word Document in C#

在 C# 中导出到 Word 文档

回答by Gary Kindel

Here is code to copy datagridview to a word table:

这是将 datagridview 复制到单词表的代码:

Reference is Microsoft.Office.Interop.Word C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Word.dll

参考是 Microsoft.Office.Interop.Word C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for 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();
                }                                              
            }

        }

回答by nassimlouchani

You can try my method to export data to Word (*.docx) , it's easy to use and works 100% with any DataGridView , just add Microsoft.Office.Interop.Wordreference and copy the following code :

您可以尝试我的方法将数据导出到 Word (*.docx) ,它易于使用并且可以 100% 与任何 DataGridView 一起使用,只需添加Microsoft.Office.Interop.Word引用并复制以下代码:

    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); 
    }
   }

Thank you.

谢谢你。

回答by Osiel López

I have a code for insert table in to specific bookmark retreiving model in database, i hope helps community, i use mvc C#, microsoft office interop word for create a word file and add dynamic table from helper class

我有一个将表插入到数据库中特定书签检索模型的代码,我希望对社区有所帮助,我使用 mvc C#、microsoft office interop word 来创建 word 文件并从助手类添加动态表

public void tableFromDatabase(Document doc, Application word, string risk, string bookmarkName, TableTemplate table) {
        Table newTable;//Create a new table
        Range wrdRng = doc.Bookmarks.get_Item(bookmarkName).Range;//Get a bookmark Range
        doc.Bookmarks[bookmarkName].Select();
        newTable = word.Selection.Tables.Add(wrdRng,1,1);//Add new table to selected bookmark by default set 1 row, 1 column (need set interval 1-63)
        newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
        newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
        int a=0, b=0;//Set integer values for iterate in model arrays
        //Iterate model rows
        for (int i = 1; i <= table.Rows.Count; i++)//Set in 1 the value because in word tables the begin is (1,1)
        {
            //Only add rows if is after first row
            if (i > 1)
            {
                newTable.Rows.Add();
            }
            //Iterate model columns from rows
            for (int j = 1; j <= table.Rows[a].Columns.Count; j++)
            {
                //Only Add rows if is after first
                if (j == 1 && i == 1)
                {
                    newTable.Cell(i, j).Range.Font.Name = table.Rows[a].Columns[b].cellFontName;
                    newTable.Cell(i, j).Range.Font.Size = table.Rows[a].Columns[b].cellFontSize;
                    newTable.Cell(i, j).Width = float.Parse(table.Rows[a].Columns[b].cellWidth);
                }
                else
                {
                    //Add Cells to rows only if columns of the model is largen than table, this is for not exceed the interval
                    if (newTable.Rows[i].Cells.Count < table.Rows[a].Columns.Count)
                    {
                        newTable.Rows[i].Cells.Add();
                    }
                    //Set the values to new table
                    //The width must be float type
                    newTable.Cell(i, j).Range.Font.Name = table.Rows[a].Columns[b].cellFontName;
                    newTable.Cell(i, j).Range.Font.Size = table.Rows[a].Columns[b].cellFontSize;
                    newTable.Cell(i, j).Width = float.Parse(table.Rows[a].Columns[b].cellWidth);
                }
                b++;
                //Set 0 to reset cycle
                if (b == table.Rows[a].Columns.Count)
                {
                    b = 0;
                }
            }
            a++;
            //Set 0 to reset cycle
            if (a == table.Rows.Count)
            {
                a = 0;
            }
        }
        newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        newTable.AllowAutoFit = true;
        //Set gray color to borders
        newTable.Borders.InsideColor = (Microsoft.Office.Interop.Word.WdColor)12964311;
        newTable.Borders.OutsideColor = (Microsoft.Office.Interop.Word.WdColor)12964311;

    }