将 Word(DOC、DOCX)转换为字节数组 C# Java

Aspose.Words API 提供了将 Microsoft Word DOCDOCX 文档转换为 C# 和 Java 中的字节数组的最简单方法。

在将文档存储在数据库中和/或然后从数据库中检索它们时,将 Word 文档转换为字节数组很有帮助。

Aspose.Words API 提供了在不使用 Microsoft Word 的情况下操作 Microsoft Word 文件的功能。如果您没有安装 Aspose.Words API,请按照 .NET 的 安装 页面和使用 Java 的 安装 页面上的说明进行操作。

使用 C# 将 Word 文档转换为字节数组

Aspose.Words for .NET 可用于转换 Document 对象以获取表示任何 .NET 应用程序中的 Document 的字节数组。 以下代码片段演示了将 DOC 文件转换为字节数组。

// Load the document from disk.
Document doc = new Document("Sample.doc");

// Create a new memory stream.
MemoryStream outStream = new MemoryStream();
// Save the document to stream.
doc.Save(outStream, SaveFormat.Docx);

// Convert the document to byte form.
byte[] docBytes = outStream.ToArray();

// The bytes are now ready to be stored/transmitted.

// Now reverse the steps to load the bytes back into a document object.
MemoryStream inStream = new MemoryStream(docBytes);

// Load the stream into a new document object.
Document loadDoc = new Document(inStream);
// Save the document.
loadDoc.Save("loadDoc.docx",SaveFormat.Docx);

使用 Java 将 Word 文档转换为字节数组

以下代码片段演示了使用 Aspose.Words for Java API 将 DOC 文件转换为字节数组。

// Load the document.
Document doc = new Document("Sample.doc");

// Create a new memory stream.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc.save(outStream, SaveFormat.DOCX);

// Convert the document to byte form.
byte[] docBytes = outStream.toByteArray();

// The bytes are now ready to be stored/transmitted.

// Now reverse the steps to load the bytes back into a document object.
ByteArrayInputStream inStream = new ByteArrayInputStream(docBytes);

// Load the stream into a new document object.
Document loadDoc = new Document(inStream);
// Save the document.
loadDoc.save("loadDoc.docx",SaveFormat.Docx);

也可以看看