Mehmet Fatih

Mehmet Fatih

  • 858
  • 939
  • 41.2k

Giving Row number to the word automatin table

Jun 25 2023 9:07 AM

I want to give line number to the word automation table via bookmarks. How can we do it? My codes are below.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

namespace Deneme
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private DataTable GetDataSource()
        {
            var dt = new DataTable();
            using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=gezievrak2541.mdb; Mode = ReadWrite"))
            {
                conn.Open();
                using (var adapter = new OleDbDataAdapter("SELECT sinifi, SUM(IIF(cinsiyet = 'Kiz', 1, 0)) as kiz,SUM(IIF(cinsiyet = 'Erkek', 1, 0)) as erkek, COUNT(*) as toplam  FROM gezilistemiz25  where sinifi IS NOT NULL GROUP BY  sinifi order BY Left(sinifi,1) desc,Left(sinifi,13) asc,Left(sinifi,12) asc", conn))
                {
                    adapter.Fill(dt);
                }
                return dt;
            }
        }

        private void Sabitbilgi()
        {
            DataTable dt = GetDataSource();

            object oMissing = Missing.Value;
            Word.Application oWord = new Word.Application();
            oWord.Visible = true;
            object oTemplatePath = Application.StartupPath + "\\Deneme.docx";
            Word.Document oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
            
            object Index = "sinifi";
            Word.Table tbl = oWordDoc.Bookmarks.get_Item(ref Index).Range.Tables[1];

     
            foreach (DataRow dr in dt.Rows)
            {
                Word.Row newRow = tbl.Rows.Add(ref oMissing);
                for (int j = 1; j <= dt.Columns.Count; j++)
                {
                    newRow.Cells[j].Range.Text = dr[j - 1].ToString();
                }
            }
           
            Marshal.ReleaseComObject(tbl);
            Marshal.ReleaseComObject(oWordDoc);
            Marshal.ReleaseComObject(oWord);
        }
   
        private void Form3_Load(object sender, EventArgs e)
        {
            Sabitbilgi();
        }
    }
}


Answers (3)