2015-12-18 109 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

相關問題