简体   繁体   English

无法访问对象Excel WorkBook ASP.NET的属性“ saveAs”

[英]Cannot acces to the propperty “saveAs” of the object Excel WorkBook ASP.NET

I have a little issue here: I have an asp.net application built in C# and it generates an Excel pivot table. 我在这里有一个小问题:我有一个用C#构建的asp.net应用程序,它会生成一个Excel数据透视表。 I have no problem when I run it on localhost with IIS Express from Visual Studio, it creates the file from a datasource and downloads it to my downloads folder with no problem. 当我使用Visual Studio的IIS Express在localhost上运行它时,我没有问题,它从数据源创建文件并将其下载到我的下载文件夹中而没有问题。

But once I put it on my production with IIS Server and try to test the application, when I click the export button, I get the following exception: 但是,一旦将它放在IIS Server的生产环境中并尝试测试该应用程序,当我单击导出按钮时,就会出现以下异常:

Description: unhandled exception when executing the current Web request. 说明:执行当前Web请求时出现未处理的异常。 Review the stack trace for more information about the error and where it originated in the code. 查看堆栈跟踪以获取有关错误及其在代码中起源的更多信息。

Exception: System.Runtime.InteropServices.COMException: Cannot obtain acces to the SaveAs property of the Workbook class. 异常:System.Runtime.InteropServices.COMException:无法获得对Workbook类的SaveAs属性的访问权限。

Source code error: 源代码错误:

Unhandled exception when executing the current Web request. 执行当前Web请求时出现未处理的异常。 Review the stack trace for more information about the error and where it originated in the code. 查看堆栈跟踪以获取有关错误及其在代码中起源的更多信息。

Pool tracking: 池跟踪:

[COMException (0x800a03ec): Cannot obtain access to the SaveAs property of Workbook class.] [COMException(0x800a03ec):无法访问Workbook类的SaveAs属性。
System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String message) +145 System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult,ExcepInfo&excepInfo,UInt32 argErr,字符串消息)+145
CallSite.Target(Closure , CallSite , ComObject , String ) +702 CallSite.Target(Closure,CallSite,ComObject,String)+702
System.Dynamic.UpdateDelegates.UpdateAndExecute2(CallSite site, T0 arg0, T1 arg1) +491 System.Dynamic.UpdateDelegates.UpdateAndExecute2(CallSite网站,T0 arg0,T1 arg1)+491
System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2(CallSite site, T0 arg0, T1 arg1) +657 System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2(CallSite网站,T0 arg0,T1 arg1)+657
inicio.pivotTable(DataTable source) +11550 inicio.pivotTable(DataTable源)+11550
inicio.btnExportar_Click(Object sender, EventArgs e) +153 inicio.btnExportar_Click(对象发送者,EventArgs e)+153
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11773973 System.Web.UI.WebControls.Button.OnClick(EventArgs e)+11773973
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)+150
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5062 System.Web.UI.Page.ProcessRequestMain(布尔includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)+5062

This only happens when I run it from IIS Server. 仅当我从IIS服务器运行它时,才会发生这种情况。

Here is the code I use for generating my Excel file: 这是我用于生成Excel文件的代码:

private void pivotTable(DataTable source) {
    System.Globalization.CultureInfo oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");

    //get the type of excel application
    Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
    dynamic xlApp = Activator.CreateInstance(ExcelType);

    dynamic xlWBook = xlApp.WorkBooks.Add();

    DataTable dt = source;

    int x = dt.Rows.Count;
    int y = (dt.Columns.Count);
    int col, row;

    Object[,] rawData = new Object[x + 1, y];

    //filling data
    for (col = 0; col < y; col++) {
        rawData[0, col] = dt.Columns[col].ColumnName.ToUpper();
    }

    for (col = 0; col < y; col++) {
        for (row = 0; row < x; row++) {
            rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
        }
    }

    // Excel worksheet
    dynamic xlWSheet;
    String uRange = string.Format("A1:{0}{1}", excelColName(dt.Columns.Count), dt.Rows.Count + 1);

    xlWSheet = xlWBook.WorkSheets.Add();
    xlWSheet.name = dt.TableName;
    //rawData as exactly as the datasource
    xlWSheet.Range(uRange, Type.Missing).Value2 = rawData;

    dynamic dataRange = xlWSheet.Range(uRange);

    xlWBook.Names.Add(Name: dt.TableName + "_Range", RefersTo: dataRange);

    xlWSheet = xlWBook.WorkSheets.Add();
    xlWSheet.name = "Pivot_" + dt.TableName;

    dynamic ptCache = xlWBook.PivotCaches.Add(SourceType: 1, SourceData: dt.TableName + "_Range");
    dynamic ptTable = ptCache.CreatePivotTable(TableDestination: xlWSheet.Range("A3"), TableName: "PT" + dt.TableName);

    //generating pivot table
    ptTable.ManualUpdate = true;
    ptTable.PivotFields("CLIENTE").Orientation = 3;
    ptTable.PivotFields("CLIENTE").Position = 1;
    ptTable.PivotFields("CLASE").Orientation = 1;
    ptTable.PivotFields("CLASE").Position = 1;
    ptTable.PivotFields("AÑO").Orientation = 2;
    ptTable.PivotFields("AÑO").Position = 1;

    ptTable.CalculatedFields().Add("MONTO", "=SUM(TOTAL)", true);
    ptTable.PivotFields("MONTO").Orientation = 4;
    ptTable.ManualUpdate = false;

    ptCache = null;
    ptTable = null;
    xlWSheet = null;
    dataRange = null;
    //get the path from webconfig
    string path = ConfigurationManager.AppSettings["path"];
    //check if the file is alredy in the path, just to avoid excel asking to replace it
    if (File.Exists(path + Session["usuario"].ToString().Replace(" ", string.Empty) + ".xlsx")) {
        File.Delete(path + Session["usuario"].ToString().Replace(" ", string.Empty) + ".xlsx");
    }

    //save the generated file in the path 
    //this is the method mentioned in the iis exception, but it says "property"
    xlWBook.SaveAs(path + Session["usuario"].ToString().Replace(" ", string.Empty) + ".xlsx");
    //quit excel
    xlWBook.Close();
    xlApp.Quit();
    xlWBook = null;
    xlApp = null;

    GC.Collect();
    FileStream fs = null;
    string FileName = "presupuesto" + Session["usuario"].ToString().Replace(" ", string.Empty) + ".xlsx";
    //get the file i saved before
    fs = System.IO.File.Open(path + Session["usuario"].ToString().Replace(" ", string.Empty) + ".xlsx", System.IO.FileMode.Open);               
    byte[] file = new byte[fs.Length];
    //read the file
    fs.Read(file, 0, Convert.ToInt32(fs.Length));
    fs.Close();
    //send the file in response
    Response.AddHeader("Content-disposition", "attachment; filename=" + FileName);
    //delete de file because i don't want it to be in server anymore
    System.IO.File.Delete(path + Session["usuario"].ToString().Replace(" ", string.Empty) + ".xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    //send the file in response
    Response.BinaryWrite(file);
    Response.End();

    System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture;
}

I don't know what to do, I'll be thankful for any help 我不知道该怎么办,感谢您的帮助

Try to run the application using an Application Pool in IIS that uses the credentials of a Windows user on the server that can also be used to logon to the server. 尝试使用IIS中的“应用程序池”运行该应用程序,该池使用服务器上Windows用户的凭据(也可用于登录服务器)。 Office Automation does not work for users that cannot have an interactive Windows session. Office Automation对于无法进行交互式Windows会话的用户不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM