export datagridview using office.word.interop.dll instead of Spire.Doc.dll ?

The Techie

Member
Joined
Nov 26, 2019
Messages
6
Programming Experience
Beginner
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
C#:
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));
                }
            }
        }

    }
}[/I][/I][/I]
// 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

C#:
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 !");



            }

        }
[I][I][I]    }
}[/I][/I][/I]
 
Last edited by a moderator:
C#:
using Microsoft.Office.Interop.Word;
create document and table
C#:
var app = new Microsoft.Office.Interop.Word.Application();
var doc = app.Documents.Add();
Table tbl = doc.Tables.Add(doc.Content, DGV.RowCount + 1, DGV.ColumnCount); //+1 for header row
In the following code the only key element is to set tbl.Cell(row, col).Range.Text in loop.

add headers
C#:
for (var col = 0; col < DGV.ColumnCount; col++)
{
    tbl.Cell(1, col).Range.Text = DGV.Columns[col].HeaderText;
}
add values
C#:
for (var row = 0; row < DGV.RowCount; row++) {
    for (var col = 0; col< DGV.ColumnCount; col++)
    {
        tbl.Cell(row + 2, col + 1).Range.Text = DGV.Rows[row].Cells[col].FormattedValue.ToString();
    }
}
For example set a style, save and quit.
C#:
tbl.set_Style(WdBuiltinStyle.wdStyleTableLightListAccent1);
doc.SaveAs2(filename);
app.Quit();
 
Last edited:

Latest posts

Back
Top Bottom