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