none
How to export the entire 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.

    Thank you

    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.AddRange(new DataColumn[6] { new DataColumn("x", typeof(int)), new DataColumn("y", typeof(string)), new DataColumn("z", typeof(string)),new DataColumn("x1", typeof(int)), new DataColumn("y1", typeof(string)), new DataColumn("z1", typeof(string)) }); dt.Rows.Add(1, "1", "1","1", "1","1"); dt.Rows.Add(2, "2", "2", "2", "2", "2"); dt.Rows.Add(3, "3", "3", "3", "3", "3"); dt.Rows.Add(4, "4", "4", "4", "4", "4"); dt.Rows.Add(1, "1", "1", "1", "1", "1"); dt.Rows.Add(2, "2", "2", "2", "2", "2"); dt.Rows.Add(3, "3", "3", "3", "3", "3"); dt.Rows.Add(4, "4", "4", "4", "4", "4"); dt.Rows.Add(1, "1", "1", "1", "1", "1"); dt.Rows.Add(2, "2", "2", "2", "2", "2"); dt.Rows.Add(3, "3", "3", "3", "3", "3"); dt.Rows.Add(4, "4", "4", "4", "4", "4"); dt.Rows.Add(1, "1", "1", "1", "1", "1"); dt.Rows.Add(2, "2", "2", "2", "2", "2"); dt.Rows.Add(3, "3", "3", "3", "3", "3"); dt.Rows.Add(4, "4", "4", "4", "4", "4"); dt.Rows.Add(1, "1", "1", "1", "1", "1"); dt.Rows.Add(2, "2", "2", "2", "2", "2"); dt.Rows.Add(3, "3", "3", "3", "3", "3"); dt.Rows.Add(4, "4", "4", "4", "4", "4"); this.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 thje above code logic. 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 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 !");

                }
            }
        }
    }

    • Edited by The Techie here Thursday, December 26, 2019 5:13 AM
    • Moved by CoolDadTx Thursday, December 26, 2019 2:44 PM Office related
    Thursday, December 26, 2019 5:05 AM

All replies

  • Hello,

    I don't have an example to start off with. What I would recommend looking at is using OpenXml for Word.

    The following link seems to have most topics covered except for tables. In the following project on GitHub I've pretty much have standalone code samples for common operations including creating and populating tables.

    The disadvantage of using Word automation is if there are breaking changes in a new version of Office this can break your code while with OpenXML there is almost zero chance of this happening although if you were to upgrade to a new version via NuGet this could break things but if you never change the version you are good to go.


    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

    Thursday, December 26, 2019 1:42 PM
  • All exported Datagridview contenet 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 !");

                }
            }
        }
    }

    Thursday, December 26, 2019 6:52 PM