none
How to save the entire contents of datagridview into the word document using office.word.interop.dll instead of Spire.Doc.dll ? RRS feed

  • Question

  • How to implement the logic of the below code using Microsoft.Office.Interop.Word.dll?
    Now iam using third party dll(Spire.Doc.dll), instead of Spire.Doc.dll. i want to use Microsoft.Office.Interop.Word.dll .
    Please help me to implement this logic using office word dll. Thanks

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.License;
    using Spire.Doc.Fields;

    namespace Export_Datagridview
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            public string filename;
            public string Reportfile_path;
            private void Form1_Load(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("1");
                dt.Columns.Add("2");
                dt.Columns.Add("3");
                dt.Columns.Add("4");
                dt.Columns.Add("5");
                dt.Columns.Add("6");
                dt.Columns.Add("7");
                dt.Columns.Add("8");
                dt.Columns.Add("9");
                dt.Columns.Add("10");
                dt.Columns.Add("11");
                dt.Columns.Add("12");
                dt.Columns.Add("13");
                dt.Columns.Add("14");
                dt.Columns.Add("15");
                dt.Columns.Add("16");
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });

                dataGridView1.DataSource = dt;
            }
          
            private void button1_Click(object sender, EventArgs e)
            {
                export_datagridview();
            }
            private void export_datagridview()
            {
                string time = DateTime.Now.ToString("HH:mm:ss");
                string date = DateTime.Today.ToShortDateString();  
                filename = Reportfile_path + "sample" + ".doc";
                Document document = new Document();
                try
                {
                    document.LoadFromFile(filename, FileFormat.Doc);
                }
                catch
                {

                }
                int xx = 0, yy = 0, section_number = 0;
                Section section = new Section(document);
                Paragraph paragraph = section.AddParagraph();
                paragraph = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();
                yy = document.Sections.Count;
                if (yy == 0)
                {
                    section_number = yy;
                    section = document.AddSection();
                    section = document.Sections[section_number];
                }
                else
                {
                    section_number = yy - 1;
                    section = document.Sections[section_number];
                }
                xx = section.Tables.Count;

                if (xx == 5)
                {
                    section_number++;
                    section = document.AddSection();
                    section = document.Sections[section_number];
                }
                else
                {
                    section = document.Sections[section_number];
                }
                paragraph = section.AddParagraph();
                paragraph.AppendText("\t\t SOMETHING");
                paragraph = section.AddParagraph();
                paragraph = section.AddParagraph();
                paragraph.AppendText("Something\t\t:\tsomething");
                paragraph = section.AddParagraph();
                paragraph.AppendText("something\t\t:\tsomething");
                Add_Table(dataGridView1, filename, section);
                document.SaveToFile(filename, FileFormat.Doc);
            }
            private void Add_Table(DataGridView dGV, string filename, Section section)
            {
                Spire.Doc.Table table = section.AddTable();
                table.ResetCells(dGV.RowCount, dGV.ColumnCount);
                table.ResetCells(dGV.RowCount + 1, dGV.ColumnCount);
                // first row
                TableRow row = table.Rows[0];
                row.IsHeader = true;
                row.Height = 22;
                row.HeightType = TableRowHeightType.Exactly;
                row.RowFormat.BackColor = Color.Gray;
                for (int i = 0; i < dGV.ColumnCount; i++)
                {
                    row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    Paragraph p = row.Cells[i].AddParagraph();
                    p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                    TextRange txtRange = p.AppendText(Convert.ToString(dGV.Columns[i].HeaderText));
                    txtRange.CharacterFormat.Bold = true;
                }
                for (int r = 0; r < dGV.RowCount; r++)
                {
                    TableRow dataRow = table.Rows[r + 1];
                    dataRow.Height = 22;
                    dataRow.HeightType = TableRowHeightType.Exactly;
                    dataRow.RowFormat.BackColor = Color.Empty;
                    for (int c = 0; c < dGV.ColumnCount; c++)
                    {
                        dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        row.Cells[c].Width = 80;
                        dataRow.Cells[c].Width = 80;
                        dataRow.Cells[c].AddParagraph().AppendText(Convert.ToString(dGV.Rows[r].Cells[c].Value));
                    }
                }
            }

        }
    }


    And this below code does not go well with the actual need . on button click event of more than once ( several times) all exported 
    datagridview  into word document are overlapping with each other so how 
    to avoid the overlapping and save all tables properly(table right below 
    the table) ? please guide me to implement the above code logic.
    All exported Datagridview content is getting merged in a single place (getting merged with each other) is there way to save them in a well organised way (recently exported table below the previously exported table) ?
    How to avoid overlapping? on button click event of more than once ( several times) all exported datagridview  into word document are overlapping with each other so how to avoid the overlapping and save all tables properly(table right below the table) ?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;

    namespace Save_DataGridView_As_Word_Doc
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            public string filename;
            public string filepath;

            private void Form1_Load(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("1");
                dt.Columns.Add("2");
                dt.Columns.Add("3");
                dt.Columns.Add("4");
                dt.Columns.Add("5");
                dt.Columns.Add("6");
                dt.Columns.Add("7");
                dt.Columns.Add("8");
                dt.Columns.Add("9");
                dt.Columns.Add("10");
                dt.Columns.Add("11");
                dt.Columns.Add("12");
                dt.Columns.Add("13");
                dt.Columns.Add("14");
                dt.Columns.Add("15");
                dt.Columns.Add("16");
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });

                dataGridView1.DataSource = dt;
            }

            private void button1_Click(object sender, EventArgs e)
            {
                save_datagridview(dataGridView1, filename);
            }

            public void save_datagridview(DataGridView DGV, string filename)
            {
                string time = DateTime.Now.ToString("HH:mm:ss");
                string date = DateTime.Today.ToShortDateString();
                filename = filepath + @"D:\datagridview" + ".docx";

                var application = new Microsoft.Office.Interop.Word.Application();

                Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();

                try
                {
                    var originalDocument = application.Documents.Open(filename);
                }
                catch
                {

                }

                if (DGV.Rows.Count != 0)
                {
                    int RowCount = DGV.Rows.Count;
                    int ColumnCount = DGV.Columns.Count;
                    Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
                    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;
                        }
                    }

                    application.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                    dynamic orange = application.ActiveDocument.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";
                        }
                    }

                    orange.Text = otemp;
                    object Separator = Microsoft.Office.Interop.Word.WdTableFieldSeparator.wdSeparateByTabs;
                    object ApplyBorders = true;
                    object AutoFit = true;
                    object AutoFitBehavior = Microsoft.Office.Interop.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();
                        application.ActiveDocument.Application.Selection.Tables[1].Select();
                        application.ActiveDocument.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                        application.ActiveDocument.Application.Selection.Tables[1].Rows.Alignment = 0;
                        application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
                        application.ActiveDocument.Application.Selection.InsertRowsAbove(1);
                        application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();

                        application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                        application.ActiveDocument.Application.Selection.Tables[1].Range.Font.Name = "Tahoma";
                        application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;
                    
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                       application.ActiveDocument.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataGridView1.Columns[c].HeaderText;
                    }
                    application.ActiveDocument.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5");
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
                    application.ActiveDocument.Application.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
               
                    foreach (Microsoft.Office.Interop.Word.Section section in application.ActiveDocument.Application.ActiveDocument.Sections)
                    {
                        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

                        headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);

                        headerRange.Text = "XYZ";
                        headerRange.Font.Size = 18;
                        headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }

                    //object start = 0, end = 0;
                    //Microsoft.Office.Interop.Word.Range rng1 = application.ActiveDocument.Range(ref start, ref end);
                    //Microsoft.Office.Interop.Word.Range rng2 = application.ActiveDocument.Range(ref start, ref end);
                    //rng1.SetRange(rng1.End, rng1.End);
                    //rng1.Text = "\t\t\t\t\t\t xyz\t :\t xyz ";
                    //rng2.SetRange(rng2.End, rng2.End);
                    //rng2.Text = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t zyz\t :\t xyz ";

                    application.ActiveDocument.Save();
                    application.Quit();
                    MessageBox.Show("Document created successfully !");

                }
            }
        }
    }


    Sunday, December 29, 2019 12:09 PM

Answers

  • Hi,

    Thank you for posting here.

    The format of the table is incorrect because every time a new table is inserted, the table is inserted at the beginning of the document, which is the first item in the previous table.

    So just add a blank line at the beginning of the document to solve this problem.

    using Microsoft.Office.Interop.Word;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace DataGridViewToWord
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                save_datagridview(dataGridView1, @"D:\test\docx\datagridview1.docx");
            }
            System.Data.DataTable dt = new System.Data.DataTable("T1");
            private void Form1_Load(object sender, EventArgs e)
            {
                #region
    
                dt.Columns.Add("1");
                dt.Columns.Add("2");
                dt.Columns.Add("3");
                dt.Columns.Add("4");
                dt.Columns.Add("5");
                dt.Columns.Add("6");
                dt.Columns.Add("7");
                dt.Columns.Add("8");
                dt.Columns.Add("9");
                dt.Columns.Add("10");
                dt.Columns.Add("11");
                dt.Columns.Add("12");
                dt.Columns.Add("13");
                dt.Columns.Add("14");
                dt.Columns.Add("15");
                dt.Columns.Add("16");
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                #endregion
                dataGridView1.DataSource = dt;
            }
    
            public void save_datagridview(DataGridView DGV, string filename)
            {
                string time = DateTime.Now.ToString("HH:mm:ss");
                string date = DateTime.Today.ToShortDateString();
    
                var application = new Microsoft.Office.Interop.Word.Application();
                try
                {
                    var originalDocument = application.Documents.Open(filename);
    
                    //Add 5 lines code here.
                    Object Nothing = System.Reflection.Missing.Value;
                    object count = 0;
                    object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                    application.Selection.MoveDown(ref WdLine, ref count, ref Nothing);
                    application.Selection.TypeParagraph();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (DGV.Rows.Count != 0)
                {
                    int RowCount = DGV.Rows.Count;
                    int ColumnCount = DGV.Columns.Count;
                    Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
                    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;
                        }
                    }
    
                    application.ActiveDocument.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
                    dynamic orange = application.ActiveDocument.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";
                        }
                    }
    
                    orange.Text = otemp;
                    object Separator = Microsoft.Office.Interop.Word.WdTableFieldSeparator.wdSeparateByTabs;
                    object ApplyBorders = true;
                    object AutoFit = true;
                    object AutoFitBehavior = 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();
    
                    application.ActiveDocument.Application.Selection.Tables[1].Select();
                    application.ActiveDocument.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                    application.ActiveDocument.Application.Selection.Tables[1].Rows.Alignment = 0;
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
                    application.ActiveDocument.Application.Selection.InsertRowsAbove(1);
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
    
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                    application.ActiveDocument.Application.Selection.Tables[1].Range.Font.Name = "Tahoma";
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;
    
    
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        application.ActiveDocument.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataGridView1.Columns[c].HeaderText;
                    }
                    application.ActiveDocument.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5");
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
                    application.ActiveDocument.Application.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    foreach (Microsoft.Office.Interop.Word.Section section in application.ActiveDocument.Application.ActiveDocument.Sections)
                    {
                        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    
                        headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
    
                        headerRange.Text = "XYZ";
                        headerRange.Font.Size = 18;
                        headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
    
                    application.ActiveDocument.Save();
                    application.Quit();
                    MessageBox.Show("Document created successfully !");
    
                }
            }
        }
    }
    

    Result:

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 31, 2019 9:06 AM

All replies

  • How is this question different from this question?

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, December 29, 2019 2:38 PM
    Moderator
  • Hi,

    Thank you for posting here.

    The format of the table is incorrect because every time a new table is inserted, the table is inserted at the beginning of the document, which is the first item in the previous table.

    So just add a blank line at the beginning of the document to solve this problem.

    using Microsoft.Office.Interop.Word;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace DataGridViewToWord
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                save_datagridview(dataGridView1, @"D:\test\docx\datagridview1.docx");
            }
            System.Data.DataTable dt = new System.Data.DataTable("T1");
            private void Form1_Load(object sender, EventArgs e)
            {
                #region
    
                dt.Columns.Add("1");
                dt.Columns.Add("2");
                dt.Columns.Add("3");
                dt.Columns.Add("4");
                dt.Columns.Add("5");
                dt.Columns.Add("6");
                dt.Columns.Add("7");
                dt.Columns.Add("8");
                dt.Columns.Add("9");
                dt.Columns.Add("10");
                dt.Columns.Add("11");
                dt.Columns.Add("12");
                dt.Columns.Add("13");
                dt.Columns.Add("14");
                dt.Columns.Add("15");
                dt.Columns.Add("16");
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                dt.Rows.Add(new object[] { "1", 2, "3", "4", "5", 6, "7", "8", "9", 10, "11", "12", "13", 14, "15", "16" });
                #endregion
                dataGridView1.DataSource = dt;
            }
    
            public void save_datagridview(DataGridView DGV, string filename)
            {
                string time = DateTime.Now.ToString("HH:mm:ss");
                string date = DateTime.Today.ToShortDateString();
    
                var application = new Microsoft.Office.Interop.Word.Application();
                try
                {
                    var originalDocument = application.Documents.Open(filename);
    
                    //Add 5 lines code here.
                    Object Nothing = System.Reflection.Missing.Value;
                    object count = 0;
                    object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                    application.Selection.MoveDown(ref WdLine, ref count, ref Nothing);
                    application.Selection.TypeParagraph();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (DGV.Rows.Count != 0)
                {
                    int RowCount = DGV.Rows.Count;
                    int ColumnCount = DGV.Columns.Count;
                    Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
                    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;
                        }
                    }
    
                    application.ActiveDocument.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
                    dynamic orange = application.ActiveDocument.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";
                        }
                    }
    
                    orange.Text = otemp;
                    object Separator = Microsoft.Office.Interop.Word.WdTableFieldSeparator.wdSeparateByTabs;
                    object ApplyBorders = true;
                    object AutoFit = true;
                    object AutoFitBehavior = 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();
    
                    application.ActiveDocument.Application.Selection.Tables[1].Select();
                    application.ActiveDocument.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                    application.ActiveDocument.Application.Selection.Tables[1].Rows.Alignment = 0;
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
                    application.ActiveDocument.Application.Selection.InsertRowsAbove(1);
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
    
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                    application.ActiveDocument.Application.Selection.Tables[1].Range.Font.Name = "Tahoma";
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;
    
    
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        application.ActiveDocument.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataGridView1.Columns[c].HeaderText;
                    }
                    application.ActiveDocument.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5");
                    application.ActiveDocument.Application.Selection.Tables[1].Rows[1].Select();
                    application.ActiveDocument.Application.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    foreach (Microsoft.Office.Interop.Word.Section section in application.ActiveDocument.Application.ActiveDocument.Sections)
                    {
                        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    
                        headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
    
                        headerRange.Text = "XYZ";
                        headerRange.Font.Size = 18;
                        headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
    
                    application.ActiveDocument.Save();
                    application.Quit();
                    MessageBox.Show("Document created successfully !");
    
                }
            }
        }
    }
    

    Result:

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 31, 2019 9:06 AM
  • Hi,

    Has your problem been solved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 4, 2020 9:38 AM