向SdtBlock中添加Table

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

namespace ConsoleApplication15
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "Word Document|*.docx";
            ofd.ShowDialog();
            string usepath =  AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "test.docx";
            File.Copy(ofd.FileName,usepath,true);
            using (WordprocessingDocument wpd = WordprocessingDocument.Open(usepath, true))
            {
                MainDocumentPart mdp = wpd.MainDocumentPart;
                Document dc = mdp.Document;
                SdtBlock target = null;
                foreach (SdtBlock sb in dc.Descendants<SdtBlock>())
                {
                    Tag tg = sb.Descendants<Tag>().Where(T => T.Val == "TestField").FirstOrDefault();
                    if (tg != null)
                    {
                        target = sb;
                        break;
                    }
                }
                if (target != null)
                {
                    SdtContentBlock scb = target.SdtContentBlock;
                    Table tb = new Table();
                    TableGrid tg = new TableGrid();
                    GridColumn gc = new GridColumn() { Width = "2840" };
                    GridColumn gc1 = new GridColumn() { Width = "2840" };
                    tg.Append(gc);
                    tg.Append(gc1);
                    tb.Append(tg);
                    TableRow tr = new TableRow();
                    TableCell tc = new TableCell();
                    Paragraph p = new Paragraph();
                    TableCell tc1 = new TableCell();
                    Paragraph p1 = new Paragraph();
                    tc.Append(p);
                    tc1.Append(p1);
                    tr.Append(tc);
                    tr.Append(tc1);
                    tb.Append(tr);
                    scb.Append(tb);
                }
                dc.Save();
            }
        }
    }
}


posted @ 2012-05-18 13:22  许阳 无锡  阅读(165)  评论(0编辑  收藏  举报