OpenXmlUtil 书签

using System.Collections.Generic;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using AA = DocumentFormat.OpenXml.Drawing;
using V = DocumentFormat.OpenXml.Vml;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using System.Linq;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
namespace Wisdombud.Report
{
public static partial class OpenXmlUtil
{

    /// 
    /// 按书签替换图片
    /// 
    /// 
    /// 
    /// 
    /// 宽度厘米
    /// 高度厘米
    /// 
    public static void ReplaceBMPicture(string filePath, string picPath, string bm)
    {
        RemoveBookMarkContent(filePath, bm);
        InsertBMPicture(filePath, picPath, bm);
    }
    /// 
    /// 修改单元格内容
    /// 
    /// 
    /// 
    public static void ModifyCell(TableCell cell, string content)
    {
        Paragraph pa = cell.Elements().FirstOrDefault();
        if (pa == null)
        {
            pa = new Paragraph();
            cell.Append(pa);
        }

        List paraList = new List();
        foreach (var inst in cell.Elements())
        {
            if (inst == pa)
            {
                continue;
            }
            paraList.Add(inst);
        }
        foreach (var inst in paraList)
        {
            inst.Remove();
        }

        ModifyParagraph(pa, content);
    }

    /// 
    /// 按书签替换图片
    /// 
    /// 
    /// 
    /// 
    /// 宽度厘米
    /// 高度厘米
    /// 
    public static void ReplaceBMPicture(string filePath, string picPath, string bm, long x, ImagePartType type)
    {
        RemoveBookMarkContent(filePath, bm);
        InsertBMPicture(filePath, picPath, bm, x, type);
    }
    /// 
    /// 按书签替换图片
    /// 
    /// 
    /// 
    /// 
    /// 宽度厘米
    /// 高度厘米
    /// 
    public static void ReplaceBMPicture(string filePath, string picPath, string bm, long x, long y, ImagePartType type)
    {
        RemoveBookMarkContent(filePath, bm);
        InsertBMPicture(filePath, picPath, bm, x, y, type);
    }
    public static void ReplaceBMPicture(WordprocessingDocument doc, string picPath, string bm, long x, long y, ImagePartType type)
    {
        RemoveBookMarkContent(doc, bm);
        InsertBMPicture(doc, picPath, bm, x, y, type);
    }
    /// 
    /// 按书签插入图片
    /// 
    /// 
    /// 
    /// 
    /// 宽度厘米
    /// 高度厘米
    /// 
    public static void InsertBMPicture(string filePath, string picPath, string bm, long x, ImagePartType type)
    {
        long y = 0;
        using (System.Drawing.Bitmap objPic = new System.Drawing.Bitmap(picPath))
        {
            y = (x * objPic.Height) / objPic.Width;
        }
        InsertBMPicture(filePath, picPath, bm, x, y, type);
    }

    /// 
    /// 按书签插入图片
    /// 
    /// 
    /// 
    /// 
    /// 宽度厘米
    /// 高度厘米
    /// 
    public static void InsertBMPicture(string filePath, string picPath, string bm, long x, long y, ImagePartType type)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            MainDocumentPart mainPart = doc.MainDocumentPart;

            BookmarkStart bmStart = findBookMarkStart(doc, bm);
            if (bmStart == null)
            {
                return;
            }
            ImagePart imagePart = mainPart.AddImagePart(type);
            using (FileStream stream = new FileStream(picPath, FileMode.Open, FileAccess.Read))
            {
                imagePart.FeedData(stream);
            }
            long cx = 360000L * x;//360000L = 1厘米
            long cy = 360000L * y;
            Run r = AddImage(doc, mainPart.GetIdOfPart(imagePart), cx, cy);
            bmStart.Parent.InsertAfter(r, bmStart);
            mainPart.Document.Save();
        }
    }
    public static void InsertBMPicture(WordprocessingDocument doc, string picPath, string bm, long x, long y, ImagePartType type)
    {
        MainDocumentPart mainPart = doc.MainDocumentPart;
        BookmarkStart bmStart = findBookMarkStart(doc, bm);
        if (bmStart == null)
        {
            return;
        }
        ImagePart imagePart = mainPart.AddImagePart(type);
        using (FileStream stream = new FileStream(picPath, FileMode.Open, FileAccess.Read))
        {
            imagePart.FeedData(stream);
        }
        long cx = 360000L * x;//360000L = 1厘米
        long cy = 360000L * y;
        Run r = AddImage(doc, mainPart.GetIdOfPart(imagePart), cx, cy);
        bmStart.Parent.InsertAfter(r, bmStart);
        mainPart.Document.Save();
    }
    /// 
    /// 查找表格
    /// 
    /// 
    /// 
    /// 
    public static Table FindTableByInnerTextStart(WordprocessingDocument doc, string start)
    {
        Body b = doc.MainDocumentPart.Document.Body;
        foreach (var table in b.Descendants())
        {
            if (table.InnerText.StartsWith(start))
            {
                return table;
            }
        }

        return null;
    }
    /// 
    /// 按书签插入图片。默认15厘米,JPG
    /// 
    /// 
    /// 
    /// 
    public static void InsertBMPicture(string filePath, string picPath, string bm)
    {
        InsertBMPicture(filePath, picPath, bm, 15, 15, ImagePartType.Jpeg);
    }
    /// 
    /// 查找书签
    /// 
    /// 
    /// 
    /// 
    public static BookmarkStart findBookMarkStart(WordprocessingDocument doc, string bmName)
    {
        foreach (var footer in doc.MainDocumentPart.FooterParts)
        {
            foreach (var inst in footer.Footer.Descendants())
            {
                if (inst.Name == bmName)
                {
                    return inst;
                }
            }
        }
        foreach (var header in doc.MainDocumentPart.HeaderParts)
        {
            foreach (var inst in header.Header.Descendants())
            {
                if (inst.Name == bmName)
                {
                    return inst;
                }
            }
        }
        foreach (var inst in doc.MainDocumentPart.RootElement.Descendants())
        {
            if (inst is BookmarkStart)
            {
                if (inst.Name == bmName)
                {
                    return inst;
                }
            }
        }

        return null;
    }

    /// 
    /// 查找书签
    /// 
    /// 
    /// 
    /// 
    public static List findAllBookMarkStart(WordprocessingDocument doc)
    {
        List ret = new List();
        foreach (var footer in doc.MainDocumentPart.FooterParts)
        {
            ret.AddRange(footer.Footer.Descendants());
        }
        foreach (var header in doc.MainDocumentPart.HeaderParts)
        {
            ret.AddRange(header.Header.Descendants());
        }
        ret.AddRange(doc.MainDocumentPart.RootElement.Descendants());
        return ret;
    }
    /// 
    /// 查找书签
    /// 
    /// 
    /// 
    /// 
    public static List findAllBookMarkEnd(WordprocessingDocument doc)
    {
        List ret = new List();
        foreach (var footer in doc.MainDocumentPart.FooterParts)
        {
            ret.AddRange(footer.Footer.Descendants());
        }
        foreach (var header in doc.MainDocumentPart.HeaderParts)
        {
            ret.AddRange(header.Header.Descendants());
        }
        ret.AddRange(doc.MainDocumentPart.RootElement.Descendants());
        return ret;
    }


    /// 
    /// 查找书签END
    /// 
    /// 
    /// 
    /// 
    public static BookmarkEnd findBookMarkEnd(WordprocessingDocument doc, string id)
    {
        foreach (var footer in doc.MainDocumentPart.FooterParts)
        {
            foreach (var inst in footer.Footer.Descendants())
            {
                if (inst.Id == id)
                {
                    return inst;
                }
            }
        }

        foreach (var header in doc.MainDocumentPart.HeaderParts)
        {
            foreach (var inst in header.Header.Descendants())
            {
                if (inst.Id == id)
                {
                    return inst;
                }
            }
        }
        foreach (var inst in doc.MainDocumentPart.RootElement.Descendants())
        {
            if (inst.Id == id)
            {
                return inst;
            }

        }

        return null;
    }

    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static void GetNewPicRun(WordprocessingDocument doc, string picPath, out MainDocumentPart mainPart, out Run r)
    {
        mainPart = doc.MainDocumentPart;
        ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);

        long cx;
        long cy;

        long x = 4;
        long y = 0;
        using (System.Drawing.Bitmap objPic = new System.Drawing.Bitmap(picPath))
        {
            y = (x * objPic.Height) / objPic.Width;
        }
        using (FileStream stream = new FileStream(picPath, FileMode.Open, FileAccess.Read))
        {
            imagePart.FeedData(stream);
        }
        cx = 360000L * x;//360000L = 1厘米
        cy = 360000L * y;

        r = OpenXmlUtil.AddImage(doc, mainPart.GetIdOfPart(imagePart), cx, cy);
    }
    private static Run AddImage(WordprocessingDocument wordDoc, string relationshipId, long cx, long cy)
    {
        return new Run(new Drawing(
                 new DW.Inline(
                     new DW.Extent() { Cx = cx, Cy = cy },
                     new DW.EffectExtent()
                     {
                         LeftEdge = 0L,
                         TopEdge = 0L,
                         RightEdge = 0L,
                         BottomEdge = 0L
                     },
                     new DW.DocProperties()
                     {
                         Id = (UInt32Value)1U,
                         Name = "Picture 1"
                     },
                     new DW.NonVisualGraphicFrameDrawingProperties(
                         new AA.GraphicFrameLocks() { NoChangeAspect = true }),
                     new AA.Graphic(
                         new AA.GraphicData(
                             new PIC.Picture(
                                 new PIC.NonVisualPictureProperties(
                                     new PIC.NonVisualDrawingProperties()
                                     {
                                         Id = (UInt32Value)0U,
                                         Name = "New Bitmap Image.jpg"
                                     },
                                     new PIC.NonVisualPictureDrawingProperties()),
                                 new PIC.BlipFill(
                                     new AA.Blip(
                                         new AA.BlipExtensionList(
                                             new AA.BlipExtension()
                                             {
                                                 Uri =
                                                   "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                             })
                                     )
                                     {
                                         Embed = relationshipId,
                                         CompressionState =
                                         AA.BlipCompressionValues.Print
                                     },
                                     new AA.Stretch(
                                         new AA.FillRectangle())),
                                 new PIC.ShapeProperties(
                                     new AA.Transform2D(
                                         new AA.Offset() { X = 0L, Y = 0L },
                                         new AA.Extents() { Cx = 952500L, Cy = 571500L }),
                                     new AA.PresetGeometry(
                                         new AA.AdjustValueList()
                                     ) { Preset = AA.ShapeTypeValues.Rectangle }))
                         ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                 )
                 {
                     DistanceFromTop = (UInt32Value)0U,
                     DistanceFromBottom = (UInt32Value)0U,
                     DistanceFromLeft = (UInt32Value)0U,
                     DistanceFromRight = (UInt32Value)0U,

                 }));

    }
    /// 
    /// 删除某一段文本
    /// 1 标记1结束到标记2开始;2 标记1结束到标记2结束;3 标记1开始到标记2结束; 4 标记1开始到标记2开始;
    /// 
    /// 
    /// 
    /// 
    /// 
    public static void DeleteRange(string filePath, string stringStart, string stringStop, int way)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            List deleteList = new List();
            bool flag = false;
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (way == 1)
                {
                    if (inst.InnerText.Contains(stringStop))
                    {
                        flag = false;
                    }
                    if (flag)
                    {
                        deleteList.Add(inst);
                    }
                    if (inst.InnerText.Contains(stringStart))
                    {
                        flag = true;
                    }
                }
                else if (way == 2)
                {

                    if (flag)
                    {
                        deleteList.Add(inst);
                    }
                    if (inst.InnerText.Contains(stringStart))
                    {
                        flag = true;
                    }
                    if (inst.InnerText.Contains(stringStop))
                    {
                        flag = false;
                    }
                }
                else if (way == 3)
                {
                    if (inst.InnerText.Contains(stringStart))
                    {
                        flag = true;
                    }
                    if (flag)
                    {
                        deleteList.Add(inst);
                    }

                    if (inst.InnerText.Contains(stringStop))
                    {
                        flag = false;
                    }
                }
                else if (way == 4)
                {
                    if (inst.InnerText.Contains(stringStart))
                    {
                        flag = true;
                    }
                    if (inst.InnerText.Contains(stringStop))
                    {
                        flag = false;
                    }
                    if (flag)
                    {
                        deleteList.Add(inst);
                    }

                }

            }
            foreach (var inst in deleteList)
            {
                inst.Remove();
            }
        }

    }
    /// 
    /// 删除某一段文本(从第二个符合的Elements开始)
    /// 标记1开始到标记2开始;
    /// 
    /// 
    /// 
    /// 
    public static void DeleteRangeByJieTu(string filePath, string stringStart, string stringStop)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            List deleteList = new List();
            bool flag = false;
            int i = 0;
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (inst.InnerText.Contains(stringStart))
                {
                    if (i == 1)
                    {
                        flag = true;
                    }
                    i++;
                }
                if (inst.InnerText.Contains(stringStop))
                {
                    flag = false;
                }
                if (flag)
                {
                    deleteList.Add(inst);
                }
            }
            foreach (var inst in deleteList)
            {
                inst.Remove();
            }
        }

    }
    /// 
    /// 从stringStart 开始删除到最后
    /// 
    /// 
    /// 
    /// 
    /// 
    public static void DeleteRange(string filePath, string stringStart)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            List deleteList = new List();
            bool flag = false;

            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (inst.InnerText.Contains(stringStart))
                {

                    flag = true;
                }
                if (flag)
                {
                    deleteList.Add(inst);
                }
            }
            foreach (var inst in deleteList)
            {
                inst.Remove();
            }
        }

    }
    /// 
    /// 从stringStart结束删除到最后,跳过第一个符合stringStart的Elements
    /// 2018-10-16
    /// 
    /// 
    /// 
    public static void DeleteRangeByJieTu(string filePath, string stringStart)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            List deleteList = new List();
            bool flag = false;
            int i = 0;
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (flag)
                {
                    deleteList.Add(inst);
                }
                if (inst.InnerText.Contains(stringStart))
                {
                    if (i == 1)
                    {
                        flag = true;
                    }
                    i++;
                }
            }
            foreach (var inst in deleteList)
            {
                inst.Remove();
            }
        }
    }
    public static void DeleteRangeList(List> rangeList)
    {
        foreach (var range in rangeList)
        {
            foreach (var element in range)
            {
                element.Remove();
            }
        }
    }
    public static void DeleteRangeList(string filePath, string stringStart, string stringStop, int way)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            List> rangeList = new List>();
            List temp = null;
            bool add = false;
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (way == 1)
                {
                    if (inst.InnerText.Contains(stringStop))
                    {
                        add = false;
                        rangeList.Add(temp.ToList());
                    }
                    if (add)
                    {
                        temp.Add(inst);
                    }
                    if (inst.InnerText.Contains(stringStart))
                    {
                        add = true;
                        temp = new List();
                    }
                }
                else if (way == 2)
                {

                    if (add)
                    {
                        temp.Add(inst);
                    }
                    if (inst.InnerText.Contains(stringStart))
                    {
                        add = true;
                        temp = new List();
                    }
                    if (inst.InnerText.Contains(stringStop))
                    {
                        add = false;
                        rangeList.Add(temp);
                    }
                }
                else if (way == 3)
                {
                    if (inst.InnerText.Contains(stringStart))
                    {
                        add = true;
                        temp = new List();
                    }
                    if (add)
                    {
                        temp.Add(inst);
                    }

                    if (inst.InnerText.Contains(stringStop))
                    {
                        add = false;
                        rangeList.Add(temp);
                    }
                }
                else if (way == 4)
                {
                    if (inst.InnerText.Contains(stringStart))
                    {
                        add = true;
                        temp = new List();
                    }
                    if (inst.InnerText.Contains(stringStop))
                    {
                        add = false;
                        rangeList.Add(temp);
                    }
                    if (add)
                    {
                        temp.Add(inst);
                    }
                }
            }
            foreach (var range in rangeList)
            {
                foreach (var item in range)
                {
                    if (item.Parent != null)
                    {
                        item.Remove();
                    }

                }
            }
        }
    }
    /// 
    /// 
    /// 1:从字符开始到最后
    /// 2:从字符结束到最后
    /// 
    /// 
    /// 
    /// 
    public static List RangeFindCopy2End(string filePath, string findStr, int way)
    {
        List ret = new List();
        bool find = false;
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (way == 1)
                {
                    if (inst.InnerText.Contains(findStr))
                    {
                        find = true;
                    }
                    if (find)
                    {
                        ret.Add(inst.CloneNode(true));
                    }
                }
                else if (way == 2)
                {
                    if (find)
                    {
                        ret.Add(inst.CloneNode(true));
                    }
                    if (inst.InnerText.Contains(findStr))
                    {
                        find = true;
                    }
                }
            }
        }
        return ret;
    }
    public static List RangeFindCopy2End(WordprocessingDocument doc, string findStr, int way)
    {
        List ret = new List();
        bool find = false;
        foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
        {
            if (way == 1)
            {
                if (inst.InnerText.Contains(findStr))
                {
                    find = true;
                }
                if (find)
                {
                    ret.Add(inst.CloneNode(true));
                }
            }
            else if (way == 2)
            {
                if (find)
                {
                    ret.Add(inst.CloneNode(true));
                }
                if (inst.InnerText.Contains(findStr))
                {
                    find = true;
                }
            }
        }
        return ret;
    }
    /// 
    /// 此方法get date 后,insert document(原始记录)页眉消失,未修改
    /// 
    /// 
    /// 
    public static List FindWholeDoc(string filePath)
    {
        List ret = new List();
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                ret.Add(inst.CloneNode(true));
            }
        }
        return ret;
    }
    /// 
    /// 1 标记1结束到标记2开始;2 标记1结束到标记2结束;3 标记1开始到标记2结束; 4 标记1开始到标记2开始;
    /// 
    /// 
    /// 
    /// 
    public static List RangeFind(string filePath, string stringStart, string stringStop, int way)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            return RangeFind(doc, stringStart, stringStop, way);
        }

    }
    /// 
    /// 1 标记1结束到标记2开始;2 标记1结束到标记2结束;3 标记1开始到标记2结束; 4 标记1开始到标记2开始;
    /// 
    /// 
    /// 
    /// 
    public static List RangeFind(WordprocessingDocument doc, string stringStart, string stringStop, int way)
    {
        List ret = new List();
        bool add = false;
        foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
        {
            if (way == 1)
            {
                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                }
                if (add)
                {
                    //if (inst is Paragraph && inst.InnerXml.Contains("w:pict"))
                    //{
                    //    continue;
                    //}
                    ret.Add(inst.CloneNode(true));
                }
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                }
            }
            else if (way == 2)
            {

                if (add)
                {
                    ret.Add(inst.CloneNode(true));
                }
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                }
                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                }
            }
            else if (way == 3)
            {
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                }
                if (add)
                {
                    ret.Add(inst.CloneNode(true));
                }

                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                }
            }
            else if (way == 4)
            {
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                }
                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                }
                if (add)
                {
                    ret.Add(inst.CloneNode(true));
                }
            }
        }
        return ret;
    }
    /// 
    /// 1 标记1结束到标记2开始;2 标记1结束到标记2结束;3 标记1开始到标记2结束; 4 标记1开始到标记2开始;
    /// 
    /// 
    /// 
    /// 
    public static List RangeFindAll(string filePath)
    {
        List ret = new List();
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                ret.Add(inst.CloneNode(true));
            }
        }
        return ret;
    }

    public static List> RangeListFind(WordprocessingDocument doc, string stringStart, string stringStop, int way)
    {
        List> ret = new List>();
        List temp = null;
        bool add = false;
        foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
        {
            if (way == 1)
            {
                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                    ret.Add(temp.ToList());
                }
                if (add)
                {
                    temp.Add(inst.CloneNode(true));
                }
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                    temp = new List();
                }
            }
            else if (way == 2)
            {

                if (add)
                {
                    temp.Add(inst.CloneNode(true));
                }
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                    temp = new List();
                }
                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                    ret.Add(temp);
                }
            }
            else if (way == 3)
            {
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                    temp = new List();
                }
                if (add)
                {
                    temp.Add(inst.CloneNode(true));
                }

                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                    ret.Add(temp);
                }
            }
            else if (way == 4)
            {
                if (inst.InnerText.Contains(stringStart))
                {
                    add = true;
                    temp = new List();
                }
                if (inst.InnerText.Contains(stringStop))
                {
                    add = false;
                    ret.Add(temp);
                }
                if (add)
                {
                    temp.Add(inst.CloneNode(true));
                }
            }
        }
        return ret;
    }
    /// 
    /// 不包含开始和结束
    /// 遇见第一个字符串结束循环
    /// 
    /// 
    /// 
    /// 
    /// 
    public static List> RangeListFind(WordprocessingDocument doc, string stringStart, string stringStop)
    {
        List> ret = new List>();
        List temp = null;
        bool add = false;
        foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
        {
            if (inst.InnerText.Contains(stringStop))
            {
                add = false;
                ret.Add(temp.ToList());
                //break;
            }
            if (add)
            {
                temp.Add(inst.CloneNode(true));
            }
            if (inst.InnerText.Contains(stringStart) && !add)
            {
                add = true;
                temp = new List();
            }
        }
        return ret;
    }


    /// 
    /// 修改书签
    /// 
    /// word文档
    /// 书签名字
    /// 替换的文本
    public static void SetBMTxt(string filePath, string bmName, string text)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            SetBMTxt(doc, bmName, text);
        }
    }


    public static void SetBMTxt(WordprocessingDocument doc, string bmName, string text)
    {
        BookmarkStart bs = findBookMarkStart(doc, bmName);

        if (bs != null)
        {
            OpenXmlElement elem = bs.NextSibling();

            while (elem != null && !(elem is BookmarkEnd))
            {
                OpenXmlElement nextElem = elem.NextSibling();
                elem.Remove();
                elem = nextElem;
            }

            bs.Parent.InsertAfter(new Run(new Text(text)), bs);
        }

    }
    /// 
    /// 删除书签内容(目前适用于书签内无表格)
    /// 
    /// 
    public static void DeleteBookMarkAndContent(string filePath, string bmName)
    {
        RemoveBookMarkContent(filePath, bmName);
        RemoveBookMark(filePath, bmName);
    }
    public static void DeleteBookMarkAndContent(WordprocessingDocument doc, string bmName)
    {
        RemoveBookMarkContent(doc, bmName);
        RemoveBookMark(doc, bmName);
    }
    /// 
    /// 
    /// 1:文档开始到字符开始
    /// 2:文档开始到字符结束
    /// true:包括回车
    /// 
    /// 
    /// 
    /// 
    public static List RangeFindCopyFromStart(string filePath, string findStr, int way)
    {
        List ret = new List();
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            foreach (var inst in doc.MainDocumentPart.Document.Body.Elements())
            {
                if (way == 1)
                {
                    if (inst.InnerText.Contains(findStr))
                    {
                        break;
                    }
                    ret.Add(inst.CloneNode(true));
                }
                else if (way == 2)
                {
                    ret.Add(inst.CloneNode(true));
                    if (inst.InnerText.Contains(findStr))
                    {
                        break;
                    }
                }
            }
        }
        return ret;
    }

    /// 
    /// 把elements复制到文件的最后面
    /// 
    /// 
    /// 
    public static void PasteDocumentEnd(string filePath, List elements)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            PasteDocumentEnd(doc, elements);
        }
    }
    public static void PasteDocumentEnd(WordprocessingDocument doc, List elements)
    {
        Body b = doc.MainDocumentPart.Document.Body;
        OpenXmlElement flag = b.Elements().LastOrDefault();
        if (flag == null)
        {
            return;
        }
        foreach (var inst in elements)
        {
            b.InsertBefore(inst, flag);
        }
    }
    /// 
    /// 删除书签内容(目前适用于书签内无表格)
    /// 
    /// 
    public static void RemoveBookMarkContent(string filePath, string bmName)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            RemoveBookMarkContent(doc, bmName);
        }
    }
    /// 
    /// 删除书签内容(目前适用于书签内无表格)
    /// 
    /// 
    /// 
    public static void RemoveBookMarkContent(WordprocessingDocument doc, string bmName)
    {

        BookmarkStart bmStart = findBookMarkStart(doc, bmName);
        BookmarkEnd bmEnd = findBookMarkEnd(doc, bmStart.Id);
        while (true)
        {
            var run = bmStart.NextSibling();
            if (run == null)
            {
                break;
            }
            if (run is BookmarkEnd && (BookmarkEnd)run == bmEnd)
            {
                break;
            }
            run.Remove();
        }
    }
    /// 
    /// 重命名书签,在书签前面加前缀
    /// 
    /// 
    /// 前缀
    public static void PrefixBookMark(string filePath, string prefix)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            foreach (var inst in findAllBookMarkStart(doc))
            {
                inst.Name = prefix + inst.Name;
            }
        }
    }

    /// 
    /// 重命名书签
    /// 
    /// 
    /// 
    /// 
    public static void RenameBookMark(string filePath, string oldName, string newName)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            var bm = findBookMarkStart(doc, oldName);
            bm.Name = newName;
        }
    }

    /// 
    /// 重命名书签
    /// 
    /// 
    /// 
    /// 
    public static void RenameBookMark(WordprocessingDocument doc, string oldName, string newName)
    {
        var bm = findBookMarkStart(doc, oldName);
        bm.Name = newName;
    }
    /// 
    /// 删除书签
    /// 
    /// 
    public static void RemoveBookMark(string filePath, string bmName)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            RemoveBookMark(doc, bmName);
        }
    }
    /// 
    /// 删除书签
    /// 
    /// 
    /// 
    public static void RemoveBookMark(WordprocessingDocument doc, string bmName)
    {

        var bmStart = findBookMarkStart(doc, bmName);
        if (bmStart == null)
        {
            return;
        }
        var bmEnd = findBookMarkEnd(doc, bmStart.Id);
        bmStart.Remove();
        bmEnd.Remove();
    }
    /// 
    /// 删除书签所在的Paragraph:
    /// 
    /// 
    /// 
    public static void RemoveBookMarkAndParagraph(string filePath, string bmName)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            var bmStart = findBookMarkStart(doc, bmName);
            if (bmStart == null)
            {
                return;
            }
            bmStart.Parent.Remove();
        }
    }

    public static void InsertBefore(string filePath, string findStr, List datas)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();
            foreach (var inst in b.Elements())
            {
                if (inst.InnerText.Contains(findStr))
                {
                    flag = inst;
                    break;
                }
            }
            foreach (var inst in datas)
            {
                b.InsertBefore(inst, flag);
            }
        }
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    /// start 0
    /// 
    public static void InsertBefore(string filePath, string findStr, int findStrIndex, List datas)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
            if (findStrIndex >= flagList.Count)
            {
                return;
            }
            flag = flagList[findStrIndex];

            foreach (var inst in datas)
            {
                var newOpenXmlElement = inst.CloneNode(true);
                b.InsertBefore(newOpenXmlElement, flag);
            }
        }
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    /// start 0
    /// 
    public static void InsertBefore(WordprocessingDocument doc, string findStr, int findStrIndex, List datas)
    {

        Body b = doc.MainDocumentPart.Document.Body;
        OpenXmlElement flag = b.Elements().FirstOrDefault();

        var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
        if (findStrIndex >= flagList.Count)
        {
            return;
        }
        flag = flagList[findStrIndex];

        foreach (var inst in datas)
        {
            var newOpenXmlElement = inst.CloneNode(true);
            b.InsertBefore(newOpenXmlElement, flag);
        }
    }
    /// 
    /// 杀进程
    /// 
    public static void KillWinWordProcess()
    {
        Process[] processes = Process.GetProcesses();
        foreach (Process pr in processes)
        {
            if (pr.ProcessName.ToLower().Contains("winword"))
            {
                pr.Kill();
            }
        }
        Thread.Sleep(1000);
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    /// start 0
    /// 
    public static void InsertBefore(string filePath, string findStr, int findStrIndex, List datas)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
            if (findStrIndex >= flagList.Count)
            {
                return;
            }
            flag = flagList[findStrIndex];

            foreach (var inst in datas)
            {
                var newOpenXmlElement = inst.CloneNode(true);
                b.InsertBefore(newOpenXmlElement, flag);
            }
        }
    }
    public static void InsertAfter(string filePath, string findStr, int findStrIndex, List datas)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
            if (findStrIndex >= flagList.Count)
            {
                return;
            }
            flag = flagList[findStrIndex];
            datas.Reverse();
            foreach (var inst in datas)
            {
                b.InsertAfter(inst, flag);
            }
        }
    }

    public static void InsertAfter(WordprocessingDocument doc, string findStr, int findStrIndex, List datas)
    {
        Body b = doc.MainDocumentPart.Document.Body;
        OpenXmlElement flag = b.Elements().FirstOrDefault();

        var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
        if (findStrIndex >= flagList.Count)
        {
            return;
        }
        flag = flagList[findStrIndex];
        datas.Reverse();
        foreach (var inst in datas)
        {
            b.InsertAfter(inst, flag);
        }
    }
    /// 
    ///在findStr下插入内容 paragraph必须等于findStr才可以插入,包含不会插入
    /// 
    /// 
    /// 
    /// 
    /// 

    public static void InsertAfterByEquelsFindStr(string filePath, string findStr, int findStrIndex, List datas)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            var flagList = b.Elements().Where(p => p.InnerText.Equals(findStr)).ToList();
            if (findStrIndex >= flagList.Count)
            {
                return;
            }
            flag = flagList[findStrIndex];
            datas.Reverse();
            foreach (var inst in datas)
            {
                b.InsertAfter(inst, flag);
            }
        }
    }
    public static void InsertBefore(string filePath, string findStr, OpenXmlElement data)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();
            foreach (var inst in b.Elements())
            {
                if (inst.InnerText.Contains(findStr))
                {
                    flag = inst;
                    break;
                }
            }
            flag.InsertBeforeSelf(data);

        }
    }

    public static void InsertBreakAfter(string filePath, string findStr)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();
            foreach (var inst in b.Elements())
            {
                if (inst.InnerText.Contains(findStr))
                {
                    flag = inst;
                    break;
                }
            }
            Break break1 = new Break() { Type = BreakValues.Page };
            Run run2 = new Run();
            run2.Append(break1);
            Paragraph p1 = new Paragraph();
            p1.Append(run2);
            flag.Append(p1);
        }
    }
    public static void InsertBreakAfter(string filePath, string findStr, int findStrIndex)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
            if (findStrIndex >= flagList.Count)
            {
                return;
            }
            flag = flagList[findStrIndex];


            Break break1 = new Break() { Type = BreakValues.Page };
            Run run2 = new Run();
            run2.Append(break1);
            Paragraph p1 = new Paragraph();
            p1.Append(run2);
            flag.Append(p1);
        }
    }
    public static void InsertBreakBefore(string filePath, string findStr, int findStrIndex)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
            if (findStrIndex >= flagList.Count)
            {
                return;
            }
            flag = flagList[findStrIndex];


            Break break1 = new Break() { Type = BreakValues.Page };
            Run run2 = new Run();
            run2.Append(break1);
            Paragraph p1 = new Paragraph();
            p1.Append(run2);
            flag.InsertBeforeSelf(p1);
        }
    }
    public static void InsertBreakBefore(string filePath, string findStr)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;

            var flagList = b.Elements().Where(p => p.InnerText.Contains(findStr)).ToList();
            foreach (var flag in flagList)
            {
                Break break1 = new Break() { Type = BreakValues.Page };
                Run run2 = new Run();
                run2.Append(break1);
                Paragraph p1 = new Paragraph();
                p1.Append(run2);
                flag.InsertBeforeSelf(p1);
            }
        }
    }
    /// 
    /// 在文档最后插入一个分页符
    /// 
    /// 
    public static void InsertBreakEnd(string filePath)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            InsertBreakEnd(doc);
        }
    }
    public static void InsertBreakEnd(WordprocessingDocument doc)
    {
        Body b = doc.MainDocumentPart.Document.Body;
        OpenXmlElement flag = b.Elements().LastOrDefault();

        Break break1 = new Break() { Type = BreakValues.Page };
        Run run2 = new Run();
        run2.Append(break1);
        Paragraph p1 = new Paragraph();
        p1.Append(run2);
        flag.InsertAfterSelf(p1);
    }
    /// 
    /// 在文档开头插入一个分页符
    /// 
    /// 
    public static void InsertBreakStart(string filePath)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
        {
            Body b = doc.MainDocumentPart.Document.Body;
            OpenXmlElement flag = b.Elements().FirstOrDefault();

            Paragraph p1 = new Paragraph();

            Break break1 = new Break() { Type = BreakValues.Page };
            Run run1 = new Run();
            run1.Append(break1);
            p1.Append(run1);
            b.InsertBefore(p1, flag);
        }
    }
    /// 
    /// 在paragraph之前插入分页符
    /// 
    /// 
    public static void InsertBreakByPragraph(Paragraph paragraph)
    {
        Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00F221A5", RsidRunAdditionDefault = "00F221A5" };

        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        WidowControl widowControl1 = new WidowControl();
        Justification justification1 = new Justification() { Val = JustificationValues.Left };

        paragraphProperties1.Append(widowControl1);
        paragraphProperties1.Append(justification1);

        Run run1 = new Run();
        Break break1 = new Break() { Type = BreakValues.Page };

        run1.Append(break1);

        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
        paragraph.InsertBeforeSelf(paragraph1);
    }

    /// 
    /// 
    /// 
    /// 
    /// 要修改的TableCell里的Paragraph的Text
    /// 
    /// 
    /// 
    public static void ModifyTableFreRange(string wordPath, string keyWords, string innerText)
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true))
        {
            var paras = doc.MainDocumentPart.Document.Body.Descendants().Where(p => p.InnerText.Contains("被测设备主要技术参数描述"));
            if (paras != null && paras.Count() != 0)
            {
                var tableRows = paras.First().NextSibling
().Where(p => p.InnerText.Contains(keyWords)); if (tableRows != null && tableRows.Count() != 0) { var para = ((TableRow)tableRows.First()).Descendants().Where(p => p.InnerText.Contains(keyWords)); if (para != null && para.Count() != 0) { ModifyParagraph(para.First(), innerText); } } } } } #region Oper Table /// /// innerTxt唯一则表唯一,List
count=1 /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith /// public static List
FindTableByInnerText(WordprocessingDocument doc, string innerTxt, int condition) { List
list = new List
(); Body b = doc.MainDocumentPart.Document.Body; foreach (Table inst in b.Descendants
()) { Table table = null; if (condition == 0) { if (inst.InnerText.StartsWith(innerTxt)) { table = inst; } } else if (condition == 1) { if (inst.InnerText.Contains(innerTxt)) { table = inst; } } else if (condition == 2) { if (inst.InnerText.EndsWith(innerTxt)) { table = inst; } } if (table != null) { list.Add(table); } } return list; } /// /// /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith public static void DeleteTablesByInnerText(string filePath, string innerTxt, int condition) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { var tables = FindTableByInnerText(doc, innerTxt, condition); if (tables != null) { foreach (var inst in tables) { inst.Remove(); } } } } /// /// /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith private static void DeleteTableRowByInnerText(Table table, string rowInnerTxt, int rowCondition) { if (table != null) { TableRow row = null; foreach (TableRow inst in table.Descendants()) { switch (rowCondition) { case 0: if (inst.InnerText.StartsWith(rowInnerTxt)) { row = inst; } break; case 1: if (inst.InnerText.Contains(rowInnerTxt)) { row = inst; } break; case 2: if (inst.InnerText.EndsWith(rowInnerTxt)) { row = inst; } break; default: row = null; break; } } if (row != null) { row.Remove(); } } } /// /// 删除FDD杂散发射部分 /// /// /// /// /// /// public static void DeleteFDDZaSanByInnerText(string filePath, string tableInnerTxt, int tableCondition, string rowInnerTxt, int rowCondition) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { var table = OpenXmlUtil.FindTableByInnerText(doc, tableInnerTxt, tableCondition).FirstOrDefault(); if (table != null) { List rList = new List(); DocumentFormat.OpenXml.Wordprocessing.TableRow row = null; foreach (DocumentFormat.OpenXml.Wordprocessing.TableRow inst in table.Descendants()) { switch (rowCondition) { case 0: if (inst.InnerText.StartsWith(rowInnerTxt)) { row = inst; } break; case 1: if (inst.InnerText.Contains(rowInnerTxt)) { row = inst; } break; case 2: if (inst.InnerText.EndsWith(rowInnerTxt)) { row = inst; } break; default: row = null; break; } // if (row != null) { var firstCell = inst.GetFirstChild(); //if (row != inst && !string.IsNullOrEmpty(firstCell.InnerText)) //{ // break; //} if (row != inst && firstCell.TableCellProperties.VerticalMerge.Val != null && firstCell.TableCellProperties.VerticalMerge.Val == MergedCellValues.Restart) { break; } rList.Add(inst); } } if (rList != null) { foreach (var inst in rList) { inst.Remove(); } } } } } /// /// /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith /// /// 0:StartsWith,1:Contains,2:EndsWith public static void DeleteTableRowByInnerText(string filePath, string tableInnerTxt, int tableCondition, string rowInnerTxt, int rowCondition) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { var tables = FindTableByInnerText(doc, tableInnerTxt, tableCondition); if (tables != null) { foreach (var inst in tables) { DeleteTableRowByInnerText(inst, rowInnerTxt, rowCondition); } } } } #endregion public static void ModifyParagraph(Paragraph pa, string content) { Run run = new Run(); if (pa.Elements().Count() > 0) { run = (Run)pa.Elements().FirstOrDefault().CloneNode(true); pa.RemoveAllChildren(); run.RemoveAllChildren(); } else { run = new Run(); } Text t = new Text(content); run.Append(t); pa.Append(run); } /// /// /// /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith public static void ModifyParagraph(string filePath, string content, string phInnerTxt, int condition) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { List phList = FindParaByInnerTxt(doc, phInnerTxt, condition); foreach (var inst in phList) { ModifyParagraph(inst, content); } } } private static void FindAllParaRecursive(OpenXmlElement element, List paragraphList) { if (element is Paragraph) { paragraphList.Add((Paragraph)element); } foreach (var inst in element.Elements()) { FindAllParaRecursive(inst, paragraphList); } } /// /// 查找所有书签 /// /// /// public static List FindAllBookmark(WordprocessingDocument doc) { var retList = new List(); foreach (var footer in doc.MainDocumentPart.FooterParts) { foreach (var inst in footer.Footer.Descendants()) { retList.Add(inst.Name); } } foreach (var header in doc.MainDocumentPart.HeaderParts) { foreach (var inst in header.Header.Descendants()) { retList.Add(inst.Name); } } foreach (var inst in doc.MainDocumentPart.RootElement.Descendants()) { if (inst is BookmarkStart) { retList.Add(inst.Name); } } return retList; } /// ///得到书签内容 /// /// /// public static string GetTheBookMarkText(BookmarkStart bookmark) { string str = string.Empty; if (bookmark == null) { return str; } //紧邻元素 OpenXmlElement elem = bookmark.NextSibling(); while (elem != null && !(elem is BookmarkEnd)) { if (elem is Run) { str += elem.InnerText; } elem = elem.NextSibling(); } return str; } public static List FindAllPara(WordprocessingDocument doc) { List paragraphList = new List(); Body b = doc.MainDocumentPart.Document.Body; foreach (var inst in b.Elements()) { FindAllParaRecursive(inst, paragraphList); } return paragraphList; } /// /// /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith /// public static List FindParaByInnerTxt(WordprocessingDocument doc, string innerTxt, int condition) { Paragraph ph = null; List phList = new List(); List allPhList = FindAllPara(doc); foreach (var inst in allPhList) { if (inst == null || string.IsNullOrEmpty(inst.InnerText)) { continue; } if (condition == 0) { if (inst.InnerText.StartsWith(innerTxt)) { ph = inst; } else { ph = null; } } else if (condition == 1) { if (inst.InnerText.Contains(innerTxt)) { ph = inst; } else { ph = null; } } else if (condition == 2) { if (inst.InnerText.EndsWith(innerTxt)) { ph = inst; } else { ph = null; } } if (ph != null) { phList.Add(ph); } } return phList; } /// /// 获得整机辐射模块名称 /// /// /// public static string GetModelNameByOpenXml(string filePath) { string modelName = string.Empty; using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); foreach (var para in paras) { if (para.InnerText.Contains("模块") && para.InnerText.EndsWith("部分")) { string[] modelNames = para.InnerText.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); modelName = modelNames[modelNames.Count() - 1]; break; } } return modelName; } } /// /// 获得整机辐射模块名称 /// /// /// public static List GetModelNamesByOpenXml(string filePath) { List modelNameList = new List(); using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); foreach (var para in paras) { if (para.InnerText.Contains("模块") && para.InnerText.EndsWith("部分")) { string[] modelNames = para.InnerText.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); modelNameList.Add(modelNames[modelNames.Count() - 1]); } } return modelNameList; } } /// /// 得到正文中numId /// /// /// public static int GetNumId(string wordPath) { bool flag = false; using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); int index = 0; if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("附件:检测数据及被测设备照片")) { if (index == 1) { flag = true; } index++; continue; } if (flag) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { return id.NumberingId.Val; } } } } } } return -1; } public static int GetPicNumId(string wordPath) { bool flag = false; using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("附件:检测截图")) { flag = true; continue; } if (flag) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { return id.NumberingId.Val; } } } } } } return -1; } public static int GetAbstractNumId(string wordPath, string numId) { int abstractNumId = -1; using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { Numbering numbering = doc.MainDocumentPart.NumberingDefinitionsPart.Numbering; var numInstances = numbering.Elements().Where(p => p.NumberID == numId); if (numInstances != null && numInstances.Count() != 0) { abstractNumId = ((NumberingInstance)numInstances.First()).AbstractNumId.Val; } } return abstractNumId; } public static int AddNumberingInstance(string wordPath) { int id = -1; int numId = GetNumId(wordPath); if (numId == -1) { return id; } int abstractNumId = GetAbstractNumId(wordPath, numId.ToString()); if (abstractNumId == -1) { return id; } using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { Numbering numbering = doc.MainDocumentPart.NumberingDefinitionsPart.Numbering; NumberingInstance instance = new NumberingInstance() { NumberID = numbering.Elements().Count() + 1 }; instance.AppendChild(new AbstractNumId() { Val = abstractNumId }); CreateLevel(instance); numbering.AppendChild(instance); id = instance.NumberID; } return id; } public static int AddNumberingInstancePic(string wordPath) { int id = -1; int numId = GetPicNumId(wordPath); if (numId == -1) { return id; } int abstractNumId = GetAbstractNumId(wordPath, numId.ToString()); if (abstractNumId == -1) { return id; } using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { Numbering numbering = doc.MainDocumentPart.NumberingDefinitionsPart.Numbering; NumberingInstance instance = new NumberingInstance() { NumberID = numbering.Elements().Count() + 1 }; instance.AppendChild(new AbstractNumId() { Val = abstractNumId }); CreateLevel(instance); numbering.AppendChild(instance); id = instance.NumberID; } return id; } public static void CreateLevel(NumberingInstance instance) { string str = string.Empty; for (int i = 1; i <= 9; i++) { str = i == 1 ? "%" + i : str + "." + "%" + i; CreateLevelOverRide(instance, i - 1, 1, str); } } public static void CreateLevelOverRide(NumberingInstance instance, int levelIndex, int start, string levelText) { LevelOverride levelOverRide = new LevelOverride() { LevelIndex = levelIndex }; Level lev = new Level( new StartOverrideNumberingValue() { Val = start }, new NumberingFormat() { Val = NumberFormatValues.Decimal }, new LevelSuffix() { Val = LevelSuffixValues.Space }, new LevelText() { Val = levelText }, new LevelJustification() { Val = LevelJustificationValues.Left }, new PreviousParagraphProperties( new Indentation() { Left = "0" }), new NumberingSymbolRunProperties( new RunFonts() { Hint = FontTypeHintValues.EastAsia }) ) { LevelIndex = levelIndex }; levelOverRide.Append(lev); instance.Append(levelOverRide); } #region 合并同Band刷序号 public static void ModifyBandNumId(string wordPath, int sortWordPathListCount) { List numsId = new List(); for (int i = 0; i < sortWordPathListCount; i++) { int id = AddBandNumberingInstance(wordPath); if (id == -1)//id==-1,则说明未找到numId. { return; } numsId.Add(id); } ModifyBandNumId(wordPath, numsId); } public static int AddBandNumberingInstance(string wordPath) { int id = -1; int numId = GetBandNumId(wordPath); if (numId == -1) { return id; } int abstractNumId = GetAbstractNumId(wordPath, numId.ToString()); if (abstractNumId == -1) { return id; } using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { Numbering numbering = doc.MainDocumentPart.NumberingDefinitionsPart.Numbering; NumberingInstance instance = new NumberingInstance() { NumberID = numbering.Elements().Count() + 1 }; instance.AppendChild(new AbstractNumId() { Val = abstractNumId }); CreateLevel(instance); numbering.AppendChild(instance); id = instance.NumberID; } return id; } public static int GetBandNumId(string wordPath) { bool flag = false; using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("原始记录")) { flag = true; continue; } if (flag) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { return id.NumberingId.Val; } } } } } } return -1; } private static void ModifyBandNumId(string wordPath, List numsId) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); bool flag = false; int index = 0; if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("原始记录")) { flag = true; index = 2; continue; } if (flag == true) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { if (index - 2 < numsId.Count) { id.NumberingId.Val = numsId[index - 2]; } } } } } } } } #endregion /// /// 修改编号 /// /// /// word数量 public static void ModifyNumId(string wordPath, int sortWordPathListCount) { List numsId = new List(); for (int i = 0; i < sortWordPathListCount; i++) { int id = AddNumberingInstance(wordPath); if (id == -1)//id==-1,则说明未找到numId. { return; } numsId.Add(id); } ModifyNumId(wordPath, numsId); } public static void ModifyPicNumId(string wordPath, int sortWordPathListCount) { List numsId = new List(); for (int i = 0; i < sortWordPathListCount; i++) { int id = AddNumberingInstancePic(wordPath); if (id == -1)//id==-1,则说明未找到numId. { return; } numsId.Add(id); } ModifyPicNumId(wordPath, numsId); } private static void ModifyPicNumId(string wordPath, List numsId) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); bool flag = false; int index = 0; if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("检测截图*")) { flag = true; index = 2; continue; } if (flag == true) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { if (index - 2 < numsId.Count) { id.NumberingId.Val = numsId[index - 2]; } } } if (para.InnerText.EndsWith("检测仪表及附件")) { index++; } } } } } } private static void ModifyNumId(string wordPath, List numsId) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); bool flag = false; int index = 0; if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("附件:检测数据及被测设备照片")) { if (index == 1) { flag = true; } index++; continue; } if (flag == true) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { if (index - 2 < numsId.Count) { id.NumberingId.Val = numsId[index - 2]; } } } if (para.InnerText.EndsWith("检测仪表及附件")) { index++; } } } } } } #region 本地大报告刷序号 public static void ModifyLocalReportNumId(string wordPath, int sortWordPathListCount) { List numsId = new List(); for (int i = 0; i < sortWordPathListCount; i++) { int id = AddLocalReportNumberingInstance(wordPath); if (id == -1)//id==-1,则说明未找到numId. { return; } numsId.Add(id); } ModifyLocalReportNumId(wordPath, numsId); } public static int AddLocalReportNumberingInstance(string wordPath) { int id = -1; int numId = GetLocalReportNumId(wordPath); if (numId == -1) { return id; } int abstractNumId = GetAbstractNumId(wordPath, numId.ToString()); if (abstractNumId == -1) { return id; } using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { Numbering numbering = doc.MainDocumentPart.NumberingDefinitionsPart.Numbering; NumberingInstance instance = new NumberingInstance() { NumberID = numbering.Elements().Count() + 1 }; instance.AppendChild(new AbstractNumId() { Val = abstractNumId }); CreateLevel(instance); numbering.AppendChild(instance); id = instance.NumberID; } return id; } public static int GetLocalReportNumId(string wordPath) { bool flag = false; using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("本地大报告")) { flag = true; continue; } if (flag) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { return id.NumberingId.Val; } } } } } } return -1; } private static void ModifyLocalReportNumId(string wordPath, List numsId) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); bool flag = false; int index = 0; if (paras != null) { foreach (Paragraph para in paras.ToList()) { if (para.InnerText.StartsWith("本地大报告")) { flag = true; index = 2; continue; } if (flag == true) { if (para.ParagraphProperties != null) { foreach (NumberingProperties id in para.ParagraphProperties.Elements()) { if (index - 2 < numsId.Count) { id.NumberingId.Val = numsId[index - 2]; } } } } } } } } #endregion /// /// 如果检测项包含整机辐射模块,则再进行编号; /// 但非整机辐射模块也适用 /// /// /// public static void ModifyFuJianIndex(string finalReport, List fuLuNumbers) { using (WordprocessingDocument doc = WordprocessingDocument.Open(finalReport, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements().Where(p => p.InnerText.StartsWith("附件")); List lstPara = new List(); bool flag = false; int count = 0; foreach (var inst in paras) { if (inst.InnerText.Contains("附件:检测数据及被测设备照片")) { if (count == 1) { flag = true; continue; } count++; } if (flag == true) { if (inst.InnerText.StartsWith("附件")) { lstPara.Add(inst); } } } int num = 0; foreach (var inst in lstPara) { foreach (var item in paras) { if (inst == item) { string str = string.Empty; if (item.InnerText.Contains(":") || item.InnerText.Contains(":")) { //Console.WriteLine(item.InnerText); string[] strArray = item.InnerText.Split(new Char[] { ':', ':' }, StringSplitOptions.RemoveEmptyEntries); if (strArray.Length > 1) { str = strArray[1]; } } ModifyParagraph(item, "附件" + fuLuNumbers[num] + ":" + str); //Console.WriteLine(num); break; } } num++; } } } public static void ModifyBaseInfo(string wordPath) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { var paras = doc.MainDocumentPart.Document.Body.Elements(); if (paras == null) { return; } bool flag = false; bool flag2 = true; int index = 0; int index2 = 0; foreach (Paragraph para in paras.ToList()) { if (para.InnerText.Contains("报告编号")) { flag2 = false; } if (flag2 == true) { if (para.InnerText.Contains("无线电发射设备")) { ModifyPara4(para, " 无 线 电 发 射 设 备 ", "48"); } if (para.InnerText.Contains("检测报告")) { ModifyPara4(para, "检 测 报 告", "48"); } } if (para.InnerText.Contains("检测单位信息")) { if (index == 1) { flag = true; } index++; } if (para.InnerText.Contains("检测结果概述及检测人员签字")) { if (index2 == 1) { return; } index2++; } if (flag) { ModifyPara(para); } } } } private static void ModifyPara(Paragraph para) { if (para.InnerText.StartsWith("电话")) { ModifyPara(para, "电 话"); } if (para.InnerText.StartsWith("传真")) { ModifyPara(para, "传 真"); } if (para.InnerText.StartsWith("网址")) { ModifyPara(para, "网 址"); } if (para.InnerText.StartsWith("联系人")) { ModifyPara(para, "联 系 人"); } if (para.InnerText.StartsWith("(检测报告专用章)")) { ModifyPara3(para, "(检测报告专用章)", "21"); } if (para.InnerText.StartsWith("签发日期:")) { ModifyPara3(para, "签发日期: 年 月 日", "24"); } if (para.InnerText.StartsWith("审核:")) { ModifyPara2(para, "审 核:", "28"); } if (para.InnerText.StartsWith("批准:")) { ModifyPara2(para, "批 准:", "28"); } } public static void ModifyPara4(Paragraph para, string str, string fontSize) { para.RemoveAllChildren(); para.Append(new Run( new RunProperties(new FontSize() { Val = fontSize }, new RunFonts() { Hint = FontTypeHintValues.EastAsia, EastAsia = "黑体" }, new Bold()), new Text(str))); } public static void ModifyPara3(Paragraph para, string str, string fontSize) { para.RemoveAllChildren(); if (str.Contains("检测报告专用章)")) { para.Append(new Run(new Text(" ") { Space = SpaceProcessingModeValues.Preserve })); } else { para.Append(new Run(new Text(" ") { Space = SpaceProcessingModeValues.Preserve })); } para.Append(new Run( new RunProperties(new FontSize() { Val = fontSize }, new RunFonts() { Hint = FontTypeHintValues.EastAsia, EastAsia = "黑体" }), new Text(str))); } public static void ModifyPara2(Paragraph para, string str, string fontSize) { para.RemoveAllChildren(); para.Append(new Run( new RunProperties(new FontSize() { Val = fontSize }, new RunFonts() { Hint = FontTypeHintValues.EastAsia, EastAsia = "黑体" }), new Text(str))); } public static void ModifyPara(Paragraph para, string str) { string[] strs = para.InnerText.Split(new char[] { ':', ':' }); para.RemoveAllChildren(); para.Append( new Run( new RunProperties(new FontSize() { Val = "24" }), new Text(str + ":" + strs[1])) ); } public static void InsertParagraphAtLast(string filePath, string innerText) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { Body b = doc.MainDocumentPart.Document.Body; b.AppendChild(CreateParagraph(innerText)); } } private static Paragraph CreateParagraph(string innerText) { return new Paragraph( new ParagraphProperties( new OutlineLevel() { Val = 0 }, new ParagraphMarkRunProperties( new RunFonts() { Ascii = "黑体", HighAnsi = "黑体", EastAsia = "黑体" }, new Bold(), new Color() { Val = "000000" }, new FontSize() { Val = "32" }, new FontSizeComplexScript() { Val = "32" })), CreateRun(innerText) ) { RsidParagraphMarkRevision = "002D4DE0", RsidParagraphAddition = "00B87079", RsidParagraphProperties = "002D4DE0", RsidRunAdditionDefault = "00037A5D" }; } private static Run CreateRun(string innerText) { return new Run( new RunProperties( new RunFonts() { Hint = FontTypeHintValues.EastAsia, Ascii = "黑体", HighAnsi = "黑体", EastAsia = "黑体" }, new Bold(), new Color() { Val = "000000" }, new FontSize() { Val = "32" }, new FontSizeComplexScript() { Val = "32" }), new Text(innerText)); } public static void RemoveParagraph(string filePath, string keyWords, int index) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { Body b = doc.MainDocumentPart.Document.Body; int count = 0; Paragraph para1 = null; foreach (Paragraph para in b.Elements()) { if (para.InnerText.Contains(keyWords)) { if (count == index) { para1 = para; break; } count++; } } if (para1 != null) { para1.Remove(); } } } public static void RemoveSectionInParagraph(string filePath, string keyWords, int index) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { int count = 0; Paragraph para1 = null; foreach (Paragraph para in doc.MainDocumentPart.Document.Body.Elements()) { if (para.InnerText.Contains(keyWords)) { if (count == index) { para1 = para; } count++; } } if (para1 != null) { IEnumerable runList = para1.Elements(); runList.Last().Remove(); } } } public static void RemoveOpenXmlElement(Paragraph para) { List elementList = new List(); bool flag = false; if (para == null) { return; } foreach (OpenXmlElement element in para.Elements()) { if (element is PermEnd) { flag = false; continue; } if (element is PermStart) { flag = true; continue; } if (flag) { elementList.Add(element); } } foreach (OpenXmlElement element in elementList) { if (element != null) { element.Remove(); } } } public static void InsertRunAfterPermStart(Paragraph para, params string[] innerTxtList) { List permStartList = new List(); if (para == null) { return; } RemoveOpenXmlElement(para); foreach (PermStart startElement in para.Elements()) { if (startElement != null) { permStartList.Add(startElement); } } int i = 0; foreach (PermStart permStart in permStartList) { if (i < innerTxtList.Length) { permStart.InsertAfterSelf(new Run(new Text(innerTxtList[i]))); } i++; } } public static List GetRunAfterPermStart(Paragraph para) { List list = new List(); if (para == null) { return null; } bool flag = false; List runList = new List(); foreach (OpenXmlElement startElement in para.Elements()) { if (startElement == null) { continue; } if (startElement is PermEnd) { string str = string.Empty; foreach (Run run in runList) { str += run.InnerText; } list.Add(str); flag = false; } if (flag && (startElement is Run)) { runList.Add((Run)startElement); } if (startElement is PermStart) { runList.Clear(); flag = true; } } return list; } /// /// 对齐方式 /// /// /// public static void JustificationWay(ParagraphProperties prop, JustificationValues enumVal) { if (prop != null) { var justifications = prop.Elements(); if (justifications != null) { Justification just = justifications.FirstOrDefault(); if (just != null) { just.Val = enumVal; } } else { Justification just = new Justification() { Val = enumVal }; prop.Append(just); } } } /// /// 得到startVals->结尾 的OpenXmlElement /// /// /// 开始关键字 ///第几个startVals,从0开始 /// 0:包含startVals; 1:不包含startVals /// 0:返回拷贝的数据; 1:返回原数据 /// public static List FindOpenXmlElement(string wordPath, string startVals, int startNum, int way, int copyOrRemove) { List elementList = new List(); using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { elementList = FindOpenXmlElement(startVals, startNum, way, copyOrRemove, doc); } return elementList; } public static List FindOpenXmlElement(string startVals, int startNum, int way, int copyOrRemove, WordprocessingDocument doc) { List elementList = new List(); Body b = doc.MainDocumentPart.Document.Body; bool flag = false; int count = 0; foreach (OpenXmlElement element in b.Elements()) { if (element.InnerText.EndsWith(startVals)) { if (count == startNum) { flag = true; if (way == 1) { count++; continue; } } count++; } if (element is SectionProperties) { continue; } if (flag) { if (copyOrRemove == 0) { elementList.Add(element.CloneNode(true)); } else if (copyOrRemove == 1) { elementList.Add(element); } } } return elementList; } /// /// 得到startVals->endVals之间 的OpenXmlElement /// /// /// 开始关键字 /// 第几个startVals,从0开始 /// 结束关键字 /// 第几个endVals,从0开始 /// 0:包含startVals,包含endVals; 1:不包含startVals,不包含endVals;2:只包含startVals;3:只包含endVals /// 0:返回拷贝的数据; 1:返回原数据 /// public static List FindOpenXmlElement(string wordPath, string startVals, int startNum, string endVals, int endNum, int way, int copyOrRemove) { List elementList = new List(); using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { elementList = FindOpenXmlElement(startVals, startNum, endVals, endNum, way, copyOrRemove, doc); } return elementList; } public static List FindOpenXmlElement(string startVals, int startNum, string endVals, int endNum, int way, int copyOrRemove, WordprocessingDocument doc) { List elementList = new List(); Body b = doc.MainDocumentPart.Document.Body; bool flag = false; int startCount = 0; int endCount = 0; foreach (OpenXmlElement element in b.Elements()) { switch (way) { case 0: Step1(startVals, startNum, ref flag, ref startCount, element); Step2(elementList, flag, copyOrRemove, element); Step3(endVals, endNum, ref flag, ref endCount, element); break; case 1: Step3(endVals, endNum, ref flag, ref endCount, element); Step2(elementList, flag, copyOrRemove, element); Step1(startVals, startNum, ref flag, ref startCount, element); break; case 2: Step3(endVals, endNum, ref flag, ref endCount, element); Step1(startVals, startNum, ref flag, ref startCount, element); Step2(elementList, flag, copyOrRemove, element); break; case 3: Step2(elementList, flag, copyOrRemove, element); Step1(startVals, startNum, ref flag, ref startCount, element); Step3(endVals, endNum, ref flag, ref endCount, element); break; } } return elementList; } private static void Step3(string endVals, int endNum, ref bool flag, ref int endCount, OpenXmlElement element) { if (element.InnerText.EndsWith(endVals)) { if (endCount == endNum) { flag = false; } endCount++; } } private static void Step2(List elementList, bool flag, int copyOrRemove, OpenXmlElement element) { if (flag) { if (copyOrRemove == 0) { elementList.Add(element.CloneNode(true)); } else if (copyOrRemove == 1) { elementList.Add(element); } } } private static void Step1(string startVals, int startNum, ref bool flag, ref int startCount, OpenXmlElement element) { if (element.InnerText.EndsWith(startVals)) { if (startCount == startNum) { flag = true; } startCount++; } } /// /// srcPath中的openXmlList复制到dstPath中,需要把srcPath的ImagePart信息copy到dstPath中,重新关联id关系 /// 修改图片关联Id /// /// /// /// srcPath中的OpenXmlElementList public static void ModifyAssociatedIdOfPicture(string srcPath, string dstPath, List srcOpenXmlElementList) { Dictionary newAndOldId = new Dictionary(); using (WordprocessingDocument doc = WordprocessingDocument.Open(dstPath, true)) { using (WordprocessingDocument doc2 = WordprocessingDocument.Open(srcPath, true)) { foreach (ImagePart inst in doc2.MainDocumentPart.ImageParts) { ImagePart imagePart = doc.MainDocumentPart.AddPart(inst); newAndOldId.Add(doc2.MainDocumentPart.GetIdOfPart(inst), doc.MainDocumentPart.GetIdOfPart(imagePart)); } } foreach (OpenXmlElement element in srcOpenXmlElementList) { foreach (AA.Blip blip in element.Descendants()) { blip.Embed = newAndOldId[blip.Embed]; } foreach (V.ImageData imageData in element.Descendants()) { imageData.RelationshipId = newAndOldId[imageData.RelationshipId]; } } } } #region Insert SectionBreak /// /// /// /// /// /// 0:StartsWith,1:Contains,2:EndsWith public static void InsertSectionBreakByParagraphInnerTxt(string fileName, string innerTxt, int condition) { using (WordprocessingDocument wDoc = WordprocessingDocument.Open(fileName, true)) { Body b = wDoc.MainDocumentPart.Document.Body; var pFirst = OpenXmlUtil.FindParaByInnerTxt(wDoc, innerTxt, condition).FirstOrDefault(); if (pFirst == null) { return; } //In order to position the section break within a paragraph, there //actually needs to be a new paragraph that follows the section break. //Make a copy of the first paragraph, then break it into two parts (paras). Paragraph pNew1 = (Paragraph)pFirst.CloneNode(true); Paragraph pNew2 = new Paragraph(); pFirst.InsertAfterSelf(pNew2); //First para contains first run of original var runs = pNew1.Elements(); foreach (var inst in runs) { pNew2.Append(inst.CloneNode(true)); } //Add the section break to the first paragraph. ParagraphProperties pProps = pNew1.Elements().FirstOrDefault(); //old ParagraphProperties; //ParagraphProperties pPropsCloneNode = (ParagraphProperties)pProps.CloneNode(true); //CloneNode old ParagraphProperties; ParagraphProperties pPropsCloneNode = GenerateParagraphProperties(); if (pPropsCloneNode != null) { pNew2.InsertAt(pPropsCloneNode, 0); } //Second paragraph contains all but first run of original foreach (var inst in runs) { inst.RemoveAllChildren(); inst.Remove(); } //Remove the original paragraph at the end. pFirst.RemoveAllChildren(); pFirst.Remove(); } } public static void RemoveFooterAllChild(string wordPath) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { if (doc.MainDocumentPart.FooterParts != null) { List
footerLst = new List
(); foreach (FooterPart footerPart in doc.MainDocumentPart.FooterParts) { footerLst.Add(footerPart.Footer); } foreach (Footer footer in footerLst) { footer.RemoveAllChildren(); } } } } public static ParagraphProperties GenerateParagraphProperties() { ParagraphProperties paragraphProperties1 = new ParagraphProperties(); ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties(); RunFonts runFonts1 = new RunFonts() { Ascii = "Arial", HighAnsi = "Arial", ComplexScript = "Arial" }; Color color1 = new Color() { Val = "000000" }; FontSize fontSize1 = new FontSize() { Val = "24" }; FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "24" }; paragraphMarkRunProperties1.Append(runFonts1); paragraphMarkRunProperties1.Append(color1); paragraphMarkRunProperties1.Append(fontSize1); paragraphMarkRunProperties1.Append(fontSizeComplexScript1); SectionProperties sectionProperties1 = new SectionProperties() { RsidR = "00E04B20", RsidSect = "00D46C38" }; //HeaderReference headerReference1 = new HeaderReference() { Type = HeaderFooterValues.Default, Id = "rId9" }; PageSize pageSize1 = new PageSize() { Width = (UInt32Value)11906U, Height = (UInt32Value)16838U }; PageMargin pageMargin1 = new PageMargin() { Top = 1644, Right = (UInt32Value)1797U, Bottom = 1440, Left = (UInt32Value)1622U, Header = (UInt32Value)851U, Footer = (UInt32Value)992U, Gutter = (UInt32Value)0U }; PageNumberType pageNumberType1 = new PageNumberType() { Start = 1 }; Columns columns1 = new Columns() { Space = "720" }; DocGrid docGrid1 = new DocGrid() { Type = DocGridValues.Lines, LinePitch = 312 }; //sectionProperties1.Append(headerReference1); sectionProperties1.Append(pageSize1); sectionProperties1.Append(pageMargin1); sectionProperties1.Append(pageNumberType1); sectionProperties1.Append(columns1); sectionProperties1.Append(docGrid1); paragraphProperties1.Append(paragraphMarkRunProperties1); paragraphProperties1.Append(sectionProperties1); return paragraphProperties1; } #endregion [DllImport("kernel32.dll")] public static extern IntPtr _lopen(string lpPathName, int iReadWrite); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr hObject); public const int OF_READWRITE = 2; public const int OF_SHARE_DENY_NONE = 0x40; public static readonly IntPtr HFILE_ERROR = new IntPtr(-1); /// /// 判断文件是否被占用 /// /// /// public static bool IsInUse(string filePath) { IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR) { return true; } CloseHandle(vHandle); return false; } public static void RenameLEXuHao(string mergeSingeMxa20Paht) { using (WordprocessingDocument doc = WordprocessingDocument.Open(mergeSingeMxa20Paht, true)) { Body body = doc.MainDocumentPart.Document.Body; int num = 0; bool isLe = false; string sencondTitleStr = string.Empty; foreach (var paragraph in body.Elements()) { var oil = paragraph.Descendants().FirstOrDefault(); if (oil == null) { continue; } if (paragraph.InnerText.Contains("检测条件")) { num = 0; isLe = false; continue; } if (paragraph.InnerText.Contains("BR部分检测数据")) { num++; isLe = false; continue; } if (paragraph.InnerText.Contains("EDR部分检测数据")) { num++; isLe = false; continue; } if (paragraph.InnerText.Contains("LE部分检测数据")) { if (num != 0) { isLe = true; string xuHaoStr = "5." + ++num; sencondTitleStr = "5." + num + "."; string titleName = xuHaoStr + " LE部分检测数据"; OpenXmlUtil.ModifyParagraph(paragraph, titleName); continue; } } if (isLe) { var contentStr = paragraph.InnerText.Replace("5.1.", sencondTitleStr); OpenXmlUtil.ModifyParagraph(paragraph, contentStr); } } } } public static void InsertTestDataMxa20(string mergeSingeMxa20Paht, List> mergeSingeMxaOpenXmlElementLists) { using (WordprocessingDocument doc = WordprocessingDocument.Open(mergeSingeMxa20Paht, true)) { Body body = doc.MainDocumentPart.Document.Body; List openXmlElementList = body.Elements().Where(p => p.InnerText.Contains("检测仪表及附件")).ToList(); for (int i = 0; i < openXmlElementList.Count; i++) { if (i < mergeSingeMxaOpenXmlElementLists.Count) { foreach (var openXmlElement in mergeSingeMxaOpenXmlElementLists[i]) { var newOpenXmlElement = openXmlElement.CloneNode(true); openXmlElementList[i].InsertBeforeSelf(newOpenXmlElement); } } } } } public static void GenMergeSingleMxa40TestData(string mergeSingeMxa40Paht, List> mergeSingeMxaOpenXmlElementLists) { List mergeSingeMxaOpenXmlElementList = new List(); bool isFlag = false; using (WordprocessingDocument doc = WordprocessingDocument.Open(mergeSingeMxa40Paht, true)) { Body body = doc.MainDocumentPart.Document.Body; foreach (var openXmlElement in body.Elements()) { if (openXmlElement.InnerText.Contains("LE部分检测数据")) { mergeSingeMxaOpenXmlElementList = new List(); isFlag = true; } if (openXmlElement.InnerText.Contains("检测仪表及附件")) { isFlag = false; mergeSingeMxaOpenXmlElementLists.Add(mergeSingeMxaOpenXmlElementList); continue; } if (isFlag) { mergeSingeMxaOpenXmlElementList.Add(openXmlElement); } } } } public static List> RangList(string mergeSingeMxa40Path, string startContentStr, string endContentStr) { List> openXmlElementForJianCeList = new List>(); using (WordprocessingDocument doc = WordprocessingDocument.Open(mergeSingeMxa40Path, true)) { Body body = doc.MainDocumentPart.Document.Body; bool isFlag = false; List openXmlElementList = new List(); foreach (var openXmlElement in body.Elements()) { if (openXmlElement.InnerText.Contains(startContentStr)) { isFlag = true; openXmlElementList = new List(); continue; } if (openXmlElement.InnerText.Contains(endContentStr)) { isFlag = false; openXmlElementForJianCeList.Add(openXmlElementList); continue; } if (isFlag) { openXmlElementList.Add(openXmlElement); } } } return openXmlElementForJianCeList; } public static void ModefyPicNum(string biaoTiNum, string wordPath) { using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true)) { ModefyPicNum(biaoTiNum, doc); } } public static void ModefyPicNum(string biaoTiNum, WordprocessingDocument doc) { Body body = doc.MainDocumentPart.Document.Body; List openXmlParagraphList = new List(); openXmlParagraphList = body.Elements().Where(p => (p.InnerText.Contains("图") && p.InnerText.Contains("-")) && !p.InnerText.Contains("图5-")).ToList(); for (int i = 0; i < openXmlParagraphList.Count; i++) { OpenXmlUtil.ModifyParagraph(openXmlParagraphList[i], "图" + biaoTiNum + "-" + (i + 1)); } } /// /// 修改标题的缩进,左对齐Left=0 /// /// public static void SetIndentationInNumParagraph(string path) { using (WordprocessingDocument doc = WordprocessingDocument.Open(path, true)) { var body = doc.MainDocumentPart.Document.Body; List allNumPara = OpenXmlUtil.FindAllPara(doc).Where(p => p.Descendants().Count() > 0).ToList(); for (int i = 0; i < allNumPara.Count; i++) { var indents = allNumPara[i].Descendants(); foreach (var indent in indents) { indent.FirstLineChars = new DocumentFormat.OpenXml.Int32Value(0); indent.Left = new DocumentFormat.OpenXml.StringValue("0"); indent.FirstLine = new DocumentFormat.OpenXml.StringValue("0"); indent.Hanging = null; } } } } }

}

此方法需要引用DocumentFormat.OpenXml; 这个大家可以在网上一下。

你可能感兴趣的:(OpenXmlUtil)