【问题标题】:how to Convert byte[] to Word of interop object(to a word document)?如何将 byte[] 转换为互操作对象的 Word(到 word 文档)?
【发布时间】:2012-07-11 19:49:12
【问题描述】:

我想在数据库中保存一个word文档,我这样做:

  FileStream st = new FileStream(filePath, FileMode.Open);
  byte[] buffer = new byte[st.Length];
  st.Read(buffer, 0, (int)st.Length);
  st.Close();
  //save Buffer into DB
  //myentityobject.FileContent = buffer;
  //save it

但是当我想阅读它时,我不知道如何从我从 DB 获得的流中制作一个 word 文档。我尝试过这样的事情:

 var doc = myentityobject.FileContent;
 MemoryStream stream = new MemoryStream(doc as byte[]);
 letterPatternDoc = new Document(stream);
 filePath = @"D:\LetterPatternDocument001.doc";
 object oMissing = System.Reflection.Missing.Value;
 currentApp = new wd.Application();
 currentApp.Visible = true;
 currentDoc = currentApp.Documents.Add(Type.Missing, Type.Missing);
 currentDoc = doc;
 currentDoc.SaveAs(ref path, oMissing, oMissing, oMissing, oMissing, oMissing, false
               , oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,      oMissing, oMissing);

但它不起作用。

编辑:

我更改了代码,它现在可以工作了,我通过文件流保存文件,然后读取它。但我不知道这是一个好的解决方案吗?

FileStream fileSream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
        BinaryWriter bw = new BinaryWriter(fileSream);
        bw.Write(FileContent);//filecontent is a byte[]
        fileSream.Close();

       // WordDoc.OpenDocument(filePath);

【问题讨论】:

  • 详细说明“不起作用”......它做什么(或不做什么)
  • @ psubsee2003 : 正如我所说,我在数据库中保存了一个 word 文档,现在我想在 word 应用程序中阅读并显示它。
  • 什么是 bw.Write(ViewSource.CurrentItem.LetterPatternDocument.FileContent);那是你自己的观众吗?

标签: c# stream office-interop


【解决方案1】:

你可以试试这个方法吗: 将文件保存到某个地方,并将文件路径保存到数据库。当你想读取这个文件时,你可以从数据库中获取文件路径。希望它可以帮助你:)

【讨论】:

    【解决方案2】:

    尝试序列化文档对象,从而保留文档的状态并将其保存在 db 中。在阅读反序列化时,文档对象将再次可供您显示。

    【讨论】:

      【解决方案3】:

      word无法打开一个流,但是你可以保存它,修改它,然后在数据库中更新后,删除这个“临时”文件

      【讨论】:

        【解决方案4】:

        如果您不想使用 FileStream,您还可以利用 System.IO.File 命名空间内的内置 WriteAllBytes 静态方法。

        这是一个简短的示例(假设 Interop.Word 已安装并引用):

        // byte[] fileBytes = getFileBytesFromDB();
        var tmpFile = Path.GetTempFileName();
        File.WriteAllBytes(tmpFile, fileBytes);
        
        Application app = new word.Application();
        Document doc = app.Documents.Open(filePath);
        
        // do your stuff    
        
        // convert the DOCX file back to a Byte Array
        doc.Close();
        app.Quit(); // VERY IMPORTANT: do this to close the MS Word instance
        byte[] newFileBytes= File.ReadAllBytes(tmpFile);
        File.Delete(tmpFile);
        

        有关此主题的更多信息,您也可以在我的博客上read this post

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多