簡體   English   中英

如何使用 openxml 在 ASP.NET MVC 項目中打開 docx 文件以覆蓋一些文本

[英]How to open docx file in ASP.NET MVC project using openxml for overwriting some text

我已經搜索了很多解決方案,但找不到任何解決方案。

我的 MVC 項目文件夾中有一個 .docx 文件,我想打開它來覆蓋一些文本,但我無法這樣做。

在我的項目文件夾中,我有一個Template文件夾,在這個文件夾中有一個我想要打開的genrated.docx文件。 這是我的代碼:

using (WordprocessingDocument doc = WordprocessingDocument.Open
    (@"~/Template/genrated.docx",true))
{
    var body = doc.MainDocumentPart.Document.Body;
    var paras = body.Elements<Paragraph>();

    foreach (var para in paras)
    {
        foreach (var run in para.Elements<Run>())
        {
            foreach (var text in run.Elements<Text>())
            {
                if (text.Text.Contains("to-replace"))
                {
                    text.Text = text.Text.Replace("to-replace", "replace-with");
                    run.AppendChild(new Break());
                }
            }
        }
    }
}

請在這件事上給予我幫助...

您替換文本的簡單方法僅適用於簡單情況。 不幸的是,一旦您使用 Microsoft Word 編輯模板,您的“要替換”文本可能會在多次運行中拆分。 這意味着如果您僅在單個Text實例中查找文本,則無法找到“要替換”的Text

下面的單元測試演示了通過創建一個包含兩個段落的文檔,一個段落有一個帶有“要替換”文本的單個Text實例,另一個是將相同的文本拆分為兩個RunText實例。

using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Xunit;

namespace CodeSnippets.Tests.OpenXml.Wordprocessing
{
    public class SimplisticTextReplacementTests
    {
        private const string ToReplace = "to-replace";
        private const string ReplaceWith = "replace-with";

        private static MemoryStream CreateWordprocessingDocument()
        {
            var stream = new MemoryStream();
            const WordprocessingDocumentType type = WordprocessingDocumentType.Document;

            using WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, type);
            MainDocumentPart mainDocumentPart = wordDocument.AddMainDocumentPart();
            mainDocumentPart.Document =
                new Document(
                    new Body(
                        new Paragraph(
                            new Run(
                                new Text(ToReplace))),
                        new Paragraph(
                            new Run(
                                new Text("to-")),
                            new Run(
                                new Text("replace")))));

            return stream;
        }

        private static void ReplaceText(MemoryStream stream)
        {
            using WordprocessingDocument doc = WordprocessingDocument.Open(stream, true);

            Body body = doc.MainDocumentPart.Document.Body;
            IEnumerable<Paragraph> paras = body.Elements<Paragraph>();

            foreach (Paragraph para in paras)
            {
                foreach (Run run in para.Elements<Run>())
                {
                    foreach (Text text in run.Elements<Text>())
                    {
                        if (text.Text.Contains(ToReplace))
                        {
                            text.Text = text.Text.Replace(ToReplace, ReplaceWith);
                            run.AppendChild(new Break());
                        }
                    }
                }
            }
        }

        [Fact]
        public void SimplisticTextReplacementOnlyWorksInSimpleCases()
        {
            // Arrange.
            using MemoryStream stream = CreateWordprocessingDocument();
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, false))
            {
                Document document = wordDocument.MainDocumentPart.Document;

                Paragraph firstParagraph = document.Descendants<Paragraph>().First();
                Assert.Equal(ToReplace, firstParagraph.InnerText);
                Assert.Contains(firstParagraph.Descendants<Text>(), t => t.Text == ToReplace);

                Paragraph lastParagraph = document.Descendants<Paragraph>().Last();
                Assert.Equal(ToReplace, lastParagraph.InnerText);
                Assert.DoesNotContain(lastParagraph.Descendants<Text>(), t => t.Text == ToReplace);
            }

            // Act.
            ReplaceText(stream);

            // Assert.
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, false))
            {
                Document document = wordDocument.MainDocumentPart.Document;

                Paragraph firstParagraph = document.Descendants<Paragraph>().First();
                Assert.Equal(ReplaceWith, firstParagraph.InnerText);
                Assert.Contains(firstParagraph.Descendants<Text>(), t => t.Text == ReplaceWith);

                Paragraph lastParagraph = document.Descendants<Paragraph>().Last();
                Assert.NotEqual(ReplaceWith, lastParagraph.InnerText);
                Assert.DoesNotContain(lastParagraph.Descendants<Text>(), t => t.Text == ReplaceWith);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM