搜索和替换Excel文档中的文本无效

本文关键字:文本 无效 文档 替换 Excel 搜索 | 更新日期: 2023-09-27 18:27:29

我试图在每张表格的excel文件中找到特定的单词,并试图用新单词替换它。当我尝试运行以下程序时,它会给我一个错误。

应为类、委托、枚举、接口或结构。类型或未能找到命名空间名称"DocumentFormat"(是否缺少使用指令还是程序集引用?)错误1标识符预期

using System.IO;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Packaging;
using (WordprocessingDocument wordDoc = 
        WordprocessingDocument.Open(document, true))
{


using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
    docText = sr.ReadToEnd();
}

SearchAndReplace(@"C:'Users'Public'Documents'MyPkg8.docx");
public static void SearchAndReplace(string document)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }
        Regex regexText = new Regex("Hello world!");
        docText = regexText.Replace(docText, "Hi Everyone!");
        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}
}

搜索和替换Excel文档中的文本无效

您的代码测试良好的

这似乎是一个dll引用问题(我使用了<package id="DocumentFormat.OpenXml" version="2.5" targetFramework="net451" />)或者可能是文档这个词本身。我用了"2010"这个词。

尝试使用包管理控制台Install-Package DocumentFormat.OpenXml 重新添加包

或者直接重新下载/添加程序集https://www.nuget.org/packages/documentformat.openxml/

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Text.RegularExpressions;
    using DocumentFormat.OpenXml.Packaging;
    namespace UnitTestProject1
    {
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {           
                SearchAndReplace(@"C:'TestDoc'testdoc1.docx");
            }
            public static void SearchAndReplace(string document)
            {
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
                {
                    string docText = null;
                    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                    {
                        docText = sr.ReadToEnd();
                    }
                    Regex regexText = new Regex("Hello world!");
                    docText = regexText.Replace(docText, "Hi Everyone!");
                    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                    {
                        sw.Write(docText);
                    }
                }
            }
        }
    }