0
Reply

Creating a Table in word

Jim Gannon

Jim Gannon

Jan 20 2010 3:17 PM
6.2k
Below is the code. This is a program that creates a Table in Word. It says the name tbl does
not exist in the current context and the name beforeRow does not exist in the current context.

But if I add these, Word.Table tbl = Tables[1]; and object beforeRow = this.Tables[1].Rows[1];
It does then build and creates the Authors and Title heading and one row of the table consisting of Author: , Tilte and RoyltyPct. The build ends with Object reference not set to an instance of an object. I did try to resolve this with the creation of objects but I have not been successful. Any help woould be greatly appreciated..Thank you in advance...jmg

using System;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;

namespace SQLServerWordTable
{
    public partial class ThisDocument
    {
        private void CreateWordTable()
        {
            // Move to start of document
            Object start = 0;
            Object end = 0;
            Word.Range rng = Range(ref start, ref end);

            // Insert Title and paragraph marks
            rng.InsertBefore("Authors and Titles");
            rng.Font.Name = "Verdana";
            rng.Font.Size = 16;
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.SetRange(rng.End, rng.End);

            // Add the table
            Object defaultTableBehavior = Type;
            Object autoFitBehavior = Type;
            rng.Tables.Add(
                Paragraphs[2].Range,
                1, 3, ref defaultTableBehavior, ref autoFitBehavior);

            // Set object variable to point to new table
            Word.Table tbl = Tables[1];

            // Format the table
            tbl.Range.Font.Size = 12;
            tbl.Range.Font.Name = "Verdana";
            tbl.Borders.InsideLineStyle =
                Word.WdLineStyle.wdLineStyleSingle;
            tbl.Borders.OutsideLineStyle =
                Word.WdLineStyle.wdLineStyleDouble;

            // Set the column widths
            tbl.Columns[1].SetWidth(
                ThisApplication.InchesToPoints((float)1.5),
                Word.WdRulerStyle.wdAdjustNone);
            tbl.Columns[2].SetWidth(
                ThisApplication.InchesToPoints((float)3.25),
                Word.WdRulerStyle.wdAdjustNone);
            tbl.Columns[3].SetWidth(
            ThisApplication.InchesToPoints((float)1.25),
            Word.WdRulerStyle.wdAdjustNone);
            tbl.Cell(1, 1).Range.Text = "Author:";
            tbl.Cell(1, 2).Range.Text = "Title";

            // Right-align third column
            Word.Range rngCell = tbl.Cell(1, 3).Range;
            rngCell.Text = "Royalty Pct";
            rngCell.ParagraphFormat.Alignment =
            Word.WdParagraphAlignment.wdAlignParagraphRight;
        }
        
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            CreateWordTable();


              String strSQL =
    "SELECT au_lname, title, royaltyper " +
    " FROM authors INNER JOIN titleauthor " +
    " ON authors.au_id = titleauthor.au_id INNER JOIN titles " +
    " titleauthor.title_id = titles.title_id ORDER BY au_lname";

            SqlConnection cnn = null;
            SqlDataReader sdr = null;
            SqlCommand cmd = null;
            
            try
            {
                // Open the connection
                cnn = new SqlConnection(
                    "Data Source=(local)\\SQLEXPRESS;Database=pubs;Workstation ID=DLDw5hdc1;Integrated Security=True");
               
                
                cnn.Open();

                // Open the Command and execute the DataReader
                cmd = new SqlCommand(strSQL, cnn);
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sdr != null)
                {
                    sdr.Close();
                }
            }

            // Start on second row
            int intRow = 2;

           
           try
            
            // Retrieve the data and insert into new rows.
            {


               Word.Table tbl = Tables[1];
               object beforeRow = this.Tables[1].Rows[1];
               
               while(sdr.Read())

                   
                tbl.Rows.Add(ref beforeRow);
                tbl.Cell(intRow, 1).Range.Text = sdr[0].ToString();
                tbl.Cell(intRow, 2).Range.Text = sdr[1].ToString();
                tbl.Cell(intRow, 3).Range.Text = sdr[2].ToString();
                intRow += 1;
             }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (sdr != null)
                {
                    //sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                  sdr.Close();
                }
            }      
       }            
            //Bold the column heads. Note the use
            //of the integer value, 1, to turn
            //on bold
             
          ///   

        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisDocument_Startup);
            this.Shutdown += new System.EventHandler(ThisDocument_Shutdown);
        }

        #endregion


    }

}