Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files from any .NET platform (C#, VB.NET, ASP.NET, .NET Core) and Java applications (J2SE and J2EE) with fast and high quality performance.

Wed Apr 29, 2020 3:53 am

Hi,

I can't find an instruction on how to add a column to a table.

I attach my word file just in case you want to make an example.
sample to iceblue.zip


Thank you,
Quan
You do not have the required permissions to view the files attached to this post.

MicroGenDX
 
Posts: 2
Joined: Fri Mar 22, 2019 9:46 pm

Wed Apr 29, 2020 7:08 am

Hello,

Thanks for your inquiry.
The following code demonstrates how to add a new column to an existing table. If you have further questions, please feel free to write back.
Code: Select all
    static void Main(string[] args)
    {
        Document doc = new Document();
        doc.LoadFromFile("sample to iceblue.docx");
        Section section = doc.Sections[0];
        Table table = section.Tables[0] as Table;

        //Set the column index
        int columnIndex = 4;       
        if (columnIndex <= table.Rows[0].Cells.Count)
        {
            //Add a new column
            AddColumn(table, columnIndex);
        }
        else
        {
            Console.WriteLine("Index is out of range");
        }           
        string output = "out.docx";
        doc.SaveToFile(output, FileFormat.Docx2013);
    }

    public static void AddColumn(Table table, int columnIndex)
    {
        //Get the total grid span
        int gridSpan = 0;
        for (int i = 0; i < columnIndex; i++)
        {
                gridSpan += table.Rows[0].Cells[i].GridSpan;
        }           
        for (int r = 0; r < table.Rows.Count; r++)
        {               
            //Add a new cell
            TableCell addCell = new TableCell(table.Document);
            int currentGridSpan = 0;
            for (int i = 0; i < table.Rows[r].Cells.Count; i++)
            {
                //Calculate the current total grid span
                currentGridSpan += table.Rows[r].Cells[i].GridSpan;
                if (currentGridSpan == gridSpan)
                {
                    table.Rows[r].Cells.Insert(i + 1, addCell);
                    break;
                }
                if (currentGridSpan > gridSpan)
                {
                    table.Rows[r].Cells.Insert(i, addCell);
                    break;
                }
            }                             
        }
    }


Sincerely,
Rachel
E-iceblue support team
User avatar

rachel.lei
 
Posts: 1408
Joined: Tue Jul 09, 2019 2:22 am

Tue Jun 02, 2020 8:56 am

Hello,

Hope you are doing well.
Has your issue been resolved? Could you please give us some feedback at your convenience?
Thanks in advance.

Sincerely,
Rachel
E-iceblue support team
User avatar

rachel.lei
 
Posts: 1408
Joined: Tue Jul 09, 2019 2:22 am

Return to Spire.Doc