2

Getting a null reference exception and a break on t.SetColumnWidth(i, 0.83);. I want to insert a Table at a specified point and set the column widths. What's wrong with my code, I'm using the DOCX API?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Novacode;
using System.Diagnostics;

namespace ConsoleApplicationSample
{
    class CreateDocument
    {
        public void CreateSampleDocument()
        {

            string fileName = @"C:\Users\Daniel\Documents\DocXExample.docx";

            var doc = DocX.Load(fileName);
            Table t = doc.AddTable(4, 4);

            t.Alignment = Alignment.center;          
            for (int i = 1; i <= 4; i++)
            {
                t.SetColumnWidth(i, 0.83);
            }
            t.Rows[0].Cells[0].Paragraphs[0].Append("Daniel Taki");
            t.Rows[0].Cells[1].Paragraphs[0].Append("Mike Jones");

            foreach (var paragraph in doc.Paragraphs)
            {
                paragraph.FindAll("#TABLE#").ForEach(indexer => paragraph.InsertTableAfterSelf((t)));
            }

            doc.ReplaceText("#TABLE#", "");

            doc.Save();

            Process.Start("WINWORD.EXE", fileName);
        }
    }
}

EDIT

Instead of using SetColumnWidth I tried to use nested for loops to iterate through each cell in the table and set the cell width individually. This ended up with the resulting table, which is not what I wanted.

  var numberOfRows = t.RowCount;
  var numberOfColumns = t.ColumnCount;


            for(int row = 0; row < numberOfRows; row++)
            {
                for(int col = 0; col < numberOfColumns; col++)
                {
                    t.Rows[row].Cells[col].Width = 0.86;
                }

            }

enter image description here

4
  • stackoverflow.com/questions/23692439/… check this other wise consult with the novacode-docx documentation or do a google search on the following novacode docx SetColumnWidth
    – MethodMan
    Jan 13, 2016 at 17:54
  • Yeah that's the one I was looking at he said he you have iterate through every cell in the table and change the width, but I couldn't find a property to change cell width, until just right now haha. This may work, but why can't I set the column width with the method SetColumnWidth...shouldn't that work as well?
    – danny taki
    Jan 13, 2016 at 17:56
  • I am not sure in navacode-docx I use OpenXml assembly and ClosedXml assembly to create my docs
    – MethodMan
    Jan 13, 2016 at 17:57
  • I have tried this on server different occassions and get the same errors. I am wondering if this is an issue with the docX package?
    – Chuck
    Jun 9, 2016 at 12:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.