Export (0) Print
Expand All

Walkthrough: Creating a Table in Word

Office 2003
 

Ken Getz
MCW Technologies, LLC

September 2003

Applies to:
    Microsoft® Visual Studio® Tools for the Microsoft Office System
    Microsoft Office Word 2003
    Microsoft Visual Studio .NET 2003

Summary: Programmatically creating a table in Word is simple, once you know the tricks. Using the provided styles, you can quickly lay out an attractive table. (9 printed pages)

Contents

Introduction
Prerequisites
Getting Started
Creating the Table
Filling the Table
Conclusion

Introduction

In this walkthrough, you'll first create a table within a Microsoft® Office Word 2003 document, and apply formatting to the table, and to individual columns within the table. Next, you'll load data from the file system, displaying a directory listing of all the files in your C:\ folder, along with formatted size and modification date values. When you're done, the document should look something like Figure 1 (with different file names, of course).

Figure 1. The completed document

Prerequisites

To complete this walkthrough, the following software and components must be installed on the development computer:

  • Microsoft Visual Studio® .NET 2003 or Microsoft Visual Basic® .NET Standard 2003
  • Microsoft Visual Studio Tools for the Microsoft Office System
  • Microsoft Office Professional Edition 2003
Tip   This demonstration assumes that if you're a Visual Basic .NET programmer, you've set the Option Strict setting in your project to On (or have added the Option Strict statement to each module in your project), although it is not required. Setting the Option Strict setting to On requires a bit more code, as you'll see, but it also ensures that you don't perform any unsafe type conversions. You can get by without it, but in the long run, the discipline required by taking advantage of this option far outweighs the difficulties it adds as you write code.

Getting Started

To get started, you need to create a Visual Studio .NET project that works with Microsoft Office Word 2003.

Create the Project

Use Visual Studio Tools for the Microsoft Office System to create a project in Visual Basic or Microsoft Visual C#® development tool.

To create a Word Document project

  1. Start Visual Studio .NET, and on the File menu, point to New, and click Project.
  2. In the Project Types pane, expand Microsoft Office System Projects, and then select Visual Basic Projects or Visual C# Projects.
  3. In the Templates pane, select Word Document.
  4. Name the project WordTableDemo, and store it in a convenient local path.
  5. Accept the defaults in the Microsoft Office Project Wizard, and click Finish to create the project.

    Visual Studio .NET opens the ThisDocument.vb or ThisDocument.cs file in the Code Editor for you.

Create the Header

Because you may want to run the demonstration multiple times, using the same document, it's important to delete the contents of the document before creating the directory listing. In addition, your document should include header information. In the following steps, you'll add these features to your document:

To create a header in the document

  1. Within the OfficeCodeBehind class, add the following procedure:
    ' Visual Basic
    Private Sub CreateTable()
        ' Clear out any existing information.
        ThisDocument.Range.Delete()
    
        ' Set up the header information.
        Dim rng As Word.Range = ThisDocument.Range(0, 0)
        rng.InsertBefore("Directory Information from C:\")
        rng.Font.Name = "Verdana"
        rng.Font.Size = 16
        rng.InsertParagraphAfter()
        rng.InsertParagraphAfter()
    End Sub
    
    // C#
    private void CreateTable() 
    {
        // Clear out any existing information.
        Object start = Type.Missing;
        Object end = Type.Missing;
        Object unit = Type.Missing;
        Object count = Type.Missing;
        ThisDocument.Range(ref start, ref end).
            Delete(ref unit, ref count);
    
        // Set up the header information.
        start = 0;
        end = 0;
        Word.Range rng = ThisDocument.Range(ref start, ref end);
        rng.InsertBefore("Directory Information from C:\\");
        rng.Font.Name = "Verdana";
        rng.Font.Size = 16;
        rng.InsertParagraphAfter();
        rng.InsertParagraphAfter();
    }
    
    
  2. Modify the ThisDocument_Open procedure, adding the following code:
    ' Visual Basic
    CreateTable()
    
    // C#
    CreateTable();
    
    
  3. Select Save All on the File menu to save your project.
  4. Press F5 to run the project, verifying that the Word document contains the correct header information, as shown in Figure 1.

    Close Word and return to Visual Studio .NET.

Creating the Table

Now that you laid out the essentials of your document, you can add the table itself. At this point, you'll simply add a single row for the header information, formatting that one row:

To create a table in the document

  1. Find the CreateTable procedure, and add the following code:
    ' Visual Basic
    ' Move to the end.
    rng.SetRange(rng.End, rng.End)
    
    ' Add the table.
    ThisDocument.Tables.Add( _
        Range:=rng, _
        NumRows:=1, NumColumns:=3)
    
    // C#
    // Move to the end.
    rng.SetRange(rng.End, rng.End);
    
    // Add the table.
    Object defaultTableBehavior = Type.Missing;
    Object autoFitBehavior = Type.Missing;
    ThisDocument.Tables.Add(rng, 1, 3, 
        ref defaultTableBehavior, ref autoFitBehavior);
    
    
  2. Continue modifying the CreateTable procedure, adding the following code.

    This fragment adds formatting to the single row you created, using one of the styles provided by Word. In addition, the code sets table headings and paragraph formatting:

    ' Visual Basic
    Dim tbl As Word.Table = ThisDocument.Tables(1)
    tbl.Range.Font.Size = 8
    tbl.Range.Font.Name = "Verdana"
    tbl.Style = "Table Grid 8"
    tbl.ApplyStyleFirstColumn = False
    tbl.ApplyStyleLastColumn = False
    tbl.ApplyStyleLastRow = False
    
    ' Insert header text and format the columns.
    tbl.Cell(1, 1).Range.Text = "Name"
    
    Dim rngCell As Word.Range
    rngCell = tbl.Cell(1, 2).Range
    rngCell.Text = "Size"
    rngCell.ParagraphFormat.Alignment = _
        Word.WdParagraphAlignment.wdAlignParagraphRight
    
    rngCell = tbl.Cell(1, 3).Range
    rngCell.Text = "Modified"
    rngCell.ParagraphFormat.Alignment = _
        Word.WdParagraphAlignment.wdAlignParagraphRight
    
    // C#
    Word.Table tbl = ThisDocument.Tables[1];
    tbl.Range.Font.Size = 8;
    tbl.Range.Font.Name = "Verdana";
    
    Object style = "Table Grid 8";
    tbl.set_Style(ref style);
    tbl.ApplyStyleFirstColumn = false;
    tbl.ApplyStyleLastColumn = false;
    tbl.ApplyStyleLastRow = false;
    
    // Insert header text and format the columns.
    tbl.Cell(1, 1).Range.Text = "Name";
    
    Word.Range rngCell;
    rngCell = tbl.Cell(1, 2).Range;
    rngCell.Text = "Size";
    rngCell.ParagraphFormat.Alignment =  
        Word.WdParagraphAlignment.wdAlignParagraphRight;
    
    rngCell = tbl.Cell(1, 3).Range;
    rngCell.Text = "Modified";
    rngCell.ParagraphFormat.Alignment = 
        Word.WdParagraphAlignment.wdAlignParagraphRight;
    
    
  3. Press F5 to run the project, and verify that you've created the table header, and that you've formatted the Size and Modified columns so that they align to the right.

    Close Word and return to Visual Studio .NET.

Filling the Table

For the final step of this walkthrough, you'll fill the table you've created with information about the files in the C:\ folder. For these steps, you'll use the FileInfo and DirectoryInfo classes provided by the System.IO namespace:

To fill the table with data

  1. Scroll to the top of the module, and add the following statement:
    ' Visual Basic
    Imports System.IO
    
    // C#
    using System.IO;
    
    
  2. Add the following procedure to the OfficeCodeBehind class.

    This procedure loops through all the files in the C:\ folder, and for each FileInfo object, adds a new row to the table, and fills in the data:

    ' Visual Basic
    Private Sub FillTable()
        ' Fill the table with data.
        Dim tbl As Word.Table = ThisDocument.Tables(1)
        Dim fi As FileInfo
        Dim di As New DirectoryInfo("C:\")
    
        ' Start with row 2.
        Dim i As Integer = 2
    
        For Each fi In di.GetFiles()
            tbl.Rows.Add()
            tbl.Cell(i, 1).Range.Text = fi.Name
            tbl.Cell(i, 2).Range.Text = _
                String.Format("{0:N0}", fi.Length)
            tbl.Cell(i, 3).Range.Text = _
                String.Format("{0:g}", fi.LastWriteTime)
            i += 1
        Next
    End Sub
    
    // C#
    private void FillTable() 
    {
        // Fill the table with data.
        Word.Table tbl = ThisDocument.Tables[1];
        DirectoryInfo  di = new DirectoryInfo("C:\\");
    
        // Start with row 2.
        int i = 2;
    
        Object beforeRow = Type.Missing;
    
        foreach (FileInfo fi in di.GetFiles())
        {
            tbl.Rows.Add(ref beforeRow);
            tbl.Cell(i, 1).Range.Text = fi.Name;
            tbl.Cell(i, 2).Range.Text = 
              string .Format("{0:N0}", fi.Length);
            tbl.Cell(i, 3).Range.Text = 
                string .Format("{0:g}", fi.LastWriteTime);
            i++;
        } 
    }
    
    
  3. Modify the ThisDocument_Open procedure so that it calls the procedure you just created. The procedure's contents should look like the following:
    ' Visual Basic
    CreateTable()
    FillTable()
    
    // C#
    CreateTable();
    FillTable();
    
    
  4. Once again, run the project, and verify that the document contains information about all the files in your C:\ folder.

    Close Word, saving the document if you like, and return to Visual Studio .NET.

Conclusion

Using the styles provided, you can quickly create a table in Word. In this walkthrough, you got started with creating and formatting tables in Word 2003 documents using tools available in Visual Studio .NET.

Show:
© 2015 Microsoft