2015-12-18 81 views
1

我想在每个工作表的excel文件中找到特定的单词,并试图用新单词替换它。当我尝试运行下面的程序时,它给了我错误。搜索并替换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); 
     } 
    } 
} 
} 
+0

取出声明“使用DocumentFormat.OpenXml.Packaging;” – user469104

+0

我刚刚注意到你的代码与word文档一起工作,你问的是excel。你在寻找这个词文档代码的优秀版本吗? – robaudas

回答

0

你的代码测试精细

这似乎是一个dll引用的问题(我用<package id="DocumentFormat.OpenXml" version="2.5" targetFramework="net451" />) Ø也许这是文件本身。我用Word 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); 
        } 
       } 
      } 
     } 
    } 
+0

我怎样才能做到这一点的Excel? – Justin

相关问题