IIS 5.1IIS 6.0Visual Studio .NET 2002.NET 1.0IISVisual Studio .NET 2003Windows 2003WebForms.NET 1.1Windows 2000Windows XPIntermediateDevVisual StudioWindows.NETVisual BasicASP.NETC#
"内存或磁盘空间不足。请立即保存文档" - 从 ASP.NET 打开 MS Word






4.09/5 (12投票s)
2005年10月5日
1分钟阅读

78612
本文将帮助您使用最少的配置工作,从服务器端代码 (ASP.NET) 打开 MS-Word 文档(文档或文档模板)或 MS-Excel 表格。
引言
人们经常根据其 Web 应用程序中的要求使用/打开 Ms-Word 或 MS-Excel。 但是,从客户端脚本打开 Word 文档对于开发人员来说更容易,但在客户端浏览器中,我们不确定 Active-x 组件是否已启用。 此外,启用客户端浏览器中的 Active-X 组件是临时的。 为了避免这些混乱,我们需要从服务器端(ASP.NET)处理此操作。 由于安全问题,当从 ASP.NET 打开 Word 文档或模板文件时,我们总是会收到此错误:“内存或磁盘空间不足。请立即保存文档”。
本文将帮助您使用最少的配置工作,从服务器端代码打开 MS-Word 文档(文档或文档模板)或 MS-Excel 表格。 对于我的要求,我将此代码用作可重用的 DLL (VB.NET) 并从 ASP.NET 中调用它。
源代码
VB.NET 中的代码 (DLL)
Option Explicit Off
Imports System.Data
Imports System
Imports Microsoft.Office.Interop.Word
Namespace Wordclass
Public Class WordClass
'Purpose: This createword function is to open
'the Template.dot (Word Template) file and
'save this document as DetailDocument.doc then user will
'be redirected to the DetailDocument.doc page where
'the user can open or save the document in to their local machine.
'Function Name:Create Word
'Scope Public
'Parameters:
'1.str_FilePath-Template.dot file path which
' resides in Web.config and taken dynamically
'2.str_server_Path-URL of the Application
'3.dsPutDetails-Dataset Which is populating values
' from different Tables and writing
' the contents in to word document.
'Return Type:Boolean
Public Function CreateWord(ByVal str_FilePath As String, _
ByVal str_Server_Path As String, _
ByVal dsPutDetails As DataSet) As Boolean
Dim oWord As New Microsoft.Office.Interop.Word.Application
Dim oDoc As New Microsoft.Office.Interop.Word.Document
Try
obj_FileDelete = CreateObject("Scripting.FileSystemObject")
If obj_FileDelete.FileExists(str_FilePath & "SaveDetails.doc") Then
obj_FileDelete.DeleteFile(str_FilePath & "SaveDetails.doc")
End If
'We used to get error while executing
'the next line which is opening the word template
oDoc = oWord.Documents.Open(str_FilePath & "Template.dot")
If Not IsNothing(dsPutDetails) Then
If dsPutDetails.Tables.Count <> 0 Then
If dsPutDetails.Tables("Search_Result").Rows.Count > 0 Then
oDoc.lblname.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("appl_name").ToString()
oDoc.lblid.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("app_id").ToString()
oDoc.lbltype.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("app_type").ToString()
oDoc.lblcriticality.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("app_crit").ToString()
oDoc.lblarchitecture.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("app_arch_type").ToString()
oDoc.lbltestcases.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("test_case").ToString()
oDoc.lblniface.Caption = _
dsPutDetails.Tables("Search_Result").Rows(0)
("app_no_of_interfaces").ToString()
oDoc.lblbownername.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("b_own_name").ToString()
oDoc.lblbownerph.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("b_own_phone").ToString()
oDoc.lblbowneremail.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("b_own_email").ToString()
oDoc.lbltownername.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("t_own_name").ToString()
oDoc.lbltownerph.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("t_own_phone").ToString()
oDoc.lbltowneremail.Caption = _
dsPutDetails.Tables("Search_Result").
Rows(0)("t_own_email").ToString()
End If
End If
End If
oDoc.SaveAs(str_FilePath & "SaveDetails.doc")
'Return True
Catch ex As Exception
Finally
oDoc.Close(False)
oWord.Quit()
oDoc = Nothing
oWord = Nothing
End Try
End Function
End Class
End Namespace
'Add this WordClassLib as a reference
'in your ASP.NET application
从 ASP.NET 调用(后台代码为 C#)
using WordClassLib.Wordclass;
/* "Event for Export to word document"*/
private void btnExptoWord_Click(object sender,System.EventArgs e)
{
private DataSet ds_DBSearch = new DataSet("Ds_Worddetails");
/*Fill and populate the DS_Worddetails dataset from the table in your database*/
//Instantiating object for VBDLL WordClass
WordClass ObjWord = new WordClass();
try
{
//Getting the WordFile Path from Web.config
//Calling Creatword function and passing
//all the required parameters
ObjWord.CreateWord(ConfigurationSettings.AppSettings.Get(
"WordFile").ToString(),str_ServerPath,ds_WordDetails);
}
catch(Exception Ex)
{
Errorlog.ErrorLog objErr=new Errorlog.ErrorLog();
if (objErr.LogErrorToDB("Error while export to word ",Ex,"")==true)
objErr=null;
Response.Write("<script text = 'javascript'>" +
"parent.location.href = '"+str_ServerPath+
"/Error.aspx'</script>");
}
finally
{
ObjWord=null;
}
Response.Redirect(str_ServerPath + "/SaveDetails.doc");
}
/***************************************/
/*If you run the application you will get an error
"There is insufficient memory or disk space.save
the document now" while opening the word document
This is because of high level security in ASP.NET,
so we need to impersonate the user who is launching
the application in web.config
*/
web.config 中的配置设置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
/>
<customErrors
mode="RemoteOnly"
/>
<authentication mode="Windows" />
<authorization>
<allow users="*" /> <!-- Allow all users -->
</authorization>
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="30"
/>
<!-- GLOBALIZATION
This section sets the globalization settings of the application.
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>
<!-- Here we have to put the impersonation section
to identity the user for this application-->
<identity impersonate="true"
userName="Domain or ComputerName\UserName" password="Password"/>
</system.web>
<appSettings>
<!-- Database connection information-->
<add key = "ConnString" value="Provider=SQLOLEDB.1;Persist Security
Info=False;User ID=username;Password = password;
Initial Catalog=DatabaseName;Data Source=DatabaseServerName" />
<!--File Path for Word Template-->
<add key = "WordFile" value="C:\inetpub\wwwroot\appname\" />
</appSettings>
</configuration>
--After adding this section in web.config run the application,
--now u can successfully open the document from ASP.NET application.
结论
此代码已在 Windows XP、2000 和 Windows 2003 上进行了评估和测试。 只需在web.config中为此应用程序模拟用户就足够了,无需在组件服务 (Dcomcnfg.exe) 下配置 Microsoft Word 组件。 希望本文将帮助您在 ASP.NET 中使用 MS Word 或 MS Excel。 如果您需要有关本文的任何信息/查询,请告诉我。
谢谢。