2

获取空引用异常和中断t.SetColumnWidth(i, 0.83);。我想在指定点插入表格并设置列宽。我的代码有什么问题,我使用的是 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);
        }
    }
}

编辑

我没有尝试使用SetColumnWidth嵌套的 for 循环来遍历表中的每个单元格并单独设置单元格宽度。这最终得到了结果表,这不是我想要的。

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

            }

在此处输入图像描述

4

0 回答 0