Question save exported datagridview in a well organised way?

The Techie

Member
Joined
Nov 26, 2019
Messages
6
Programming Experience
Beginner
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?

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

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

Attachments

  • Save_DataGridView_As_Word_Doc.zip
    31.8 KB · Views: 23
Last edited by a moderator:
Considering that you just mashed everything into a single string on lines 101-108, and just copied the string into Word on line 110, what were you expecting to happen? Consider that you took time to build up the table headers one at a time, why are you not building up the table the same way?
 
Considering that you just mashed everything into a single string on lines 101-108, and just copied the string into Word on line 110, what were you expecting to happen? Consider that you took time to build up the table headers one at a time, why are you not building up the table the same way?
hello, I tried but could not achieve it . could you please help me.
 
Post your new code where you are trying.
 
When I run the code the document looks like this, which it should?
1577055185171.png


The code is very wordy, use the objects and references available. You can import the namespace:
C#:
using Word = Microsoft.Office.Interop.Word;
For example declare the application variable app and document variable doc (the active document is one you opened last).
application.ActiveDocument.Application equals app
application.ActiveDocument equals doc
ConvertToTable method returns the Table object:
C#:
Table theTable = orange.ConvertToTable(...);
application.ActiveDocument.Application.Selection.Tables[1] equals theTable
 
Post your new code where you are trying.


This is the new code which i have dveloped recenlty(using Spire.Doc.dll) . now i would like to implemnet similar logic using Microsoft.Office.Interop.Word.dll , so please help me .

Thnaks

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.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p = row.Cells.AddParagraph();
p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
TextRange txtRange = p.AppendText(Convert.ToString(dGV.Columns.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));
}
}
}

}
}
 
Please edit your post and wrap your code in code tags [CODE=csharp] Your Code Here [/CODE]. Please do not post code on the forums without using code tags. How do you expect us to read that, when the indentation and such is non existent...

It would also help if you would explain what is wrong with your latest code.
 

Latest posts

Back
Top Bottom