如何:将数据插入文档而不写入磁盘
可以将数据插入到内存中的 Office 解决方案文档中,这样数据就不会被写入硬盘。 如果需要使用 HTTP 协议将文档作为字节数组发送给用户,则可以使用此功能直接在字节数组中修改数据,而不是创建一个用于在其中修改数据的临时文件。
**适用于:**本主题中的信息适用于 Word 2007 和 Word 2010 的文档级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能。
在文档中插入数据
将文档作为字节数组加载到内存中。
Dim name As String = "C:\Documents\WordApplication3.doc" Dim fileStream As System.IO.FileStream = Nothing Dim bytes() As Byte = Nothing Try fileStream = New System.IO.FileStream( _ name, System.IO.FileMode.Open, System.IO.FileAccess.Read) ReDim bytes(fileStream.Length) fileStream.Read(bytes, 0, fileStream.Length) Finally If Not fileStream Is Nothing Then fileStream.Close() End If End Try
string name = @"C:\Documents\WordApplication3.doc"; System.IO.FileStream fileStream = null; byte[] bytes = null; try { fileStream = new System.IO.FileStream( name, System.IO.FileMode.Open, System.IO.FileAccess.Read); bytes = new byte[(int)fileStream.Length]; fileStream.Read(bytes, 0, (int)fileStream.Length); } finally { if (fileStream != null) { fileStream.Close(); } }
将该字节数组(而不是文件名)传递给服务器端对象模型,然后执行数据操作。
Dim sd1 As ServerDocument = Nothing Try sd1 = New ServerDocument(bytes, name) ' Your data manipulation code goes here. sd1.Save()
ServerDocument sd1 = null; try { sd1 = new ServerDocument(bytes, name); // Your data manipulation code goes here. sd1.Save();
将该文档发送给最终用户并关闭 ServerDocument。
' If you have a Word document, use the MIME string: Response.ContentType = "application/msword" ' If you have an Excel workbook, use the MIME string: 'Response.ContentType = "application/vnd.ms-excel" Response.AddHeader("Content-disposition", "filename=" + name) Response.BinaryWrite(sd1.Document) Finally If Not sd1 Is Nothing Then sd1.Close() End If End Try
// If you have a Word document, use the MIME string: Response.ContentType = "application/msword"; // If you have an Excel workbook, use the MIME string: //Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-disposition", "filename=" + name); Response.BinaryWrite(sd1.Document); } finally { if (sd1 != null) { sd1.Close(); } }
编译代码
此示例需要:
一个包含代码示例的 ASP.NET 项目。 项目必须具有以下配置:
必须具有对 Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll 程序集(如果项目面向 .NET Framework 4)或 Microsoft.VisualStudio.Tools.Applications.ServerDocument.v10.0.dll 程序集(如果项目面向 .NET Framework 3.5)的引用。
对于 Microsoft.VisualStudio.Tools.Applications 命名空间,您将代码示例复制到其中的代码文件必须具有 Imports(在 Visual Basic 中)或 using(在 C# 中)语句。
名为 WordApplication3.doc 的 Microsoft Office Word 文档,它具有数据缓存且位于文件夹 C:\Documents 中。