如何将byte[]转换为互操作对象的Word(转换成Word文档)?

4
我想将一个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

但是当我想阅读它时,我不知道如何从数据库中获取的流生成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
@psubsee2003:就像我说的那样,我将一个Word文档保存在数据库中,现在我想要读取并在Word应用程序中显示它。 - mahboub_mo
bw.Write(ViewSource.CurrentItem.LetterPatternDocument.FileContent); 这是你自己的查看器吗? - JohnZaj
4个回答

0
你可以尝试这个方法: 将文件保存到某个地方,并将文件路径保存到数据库。当您想要读取此文件时,可以从数据库中获取文件路径。希望能对您有所帮助 :)

0

尝试对文档对象进行序列化,以保留文档的状态并将其保存在数据库中。在读取时,反序列化文档对象将再次可用于显示。


0

Word 无法打开流,但您可以保存它,修改后在数据库更新后,只需删除这个“临时”文件。


0

如果您不想使用 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);

关于这个主题,您还可以在我的博客上阅读此文章以获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接