2017-10-13 16 views
0

我在这里有一个小问题:我有一个用C#构建的asp.net应用程序,它生成一个Excel数据透视表。当我使用Visual Studio的IIS Express在本地主机上运行它时,它没有任何问题,它从数据源创建文件并将其下载到我的下载文件夹中,没有任何问题。无法访问Excel WorkBook的属性“saveAs”ASP.NET

但是,一旦我把它放在我的生产与IIS服务器,并尝试测试应用程序,当我点击导出按钮,我得到以下异常:

Description: unhandled exception when executing the current Web request. 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.

Source code error:

Unhandled exception when executing the current Web request. 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.]
System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String message) +145
CallSite.Target(Closure , CallSite , ComObject , String) +702
System.Dynamic.UpdateDelegates.UpdateAndExecute2(CallSite site, T0 arg0, T1 arg1) +491
System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2(CallSite site, T0 arg0, T1 arg1) +657
inicio.pivotTable(DataTable source) +11550
inicio.btnExportar_Click(Object sender, EventArgs e) +153
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11773973
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5062

这只发生,当我从运行IIS服务器。

下面是我用我的生成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; 
} 

我不知道该怎么办,我的任何帮助感激

+0

您已将此标签标记为ASP.NET。为什么在ASP.NET中使用Office Interop?这是一个可怕的想法。不要这样做。 [微软说不要](https://support.microsoft.com/en-us/help/257757/considerations-for-server-side-automation-of-office)。有更好的替代方案,您可以在不使用COM的情况下生成Excel文件,例如EPPlus,NPOI,ClosedXML,Aspose。 Open XML SDK等 – mason

回答

0

尝试使用运行应用程序IIS中的应用程序池,它使用服务器上Windows用户的凭据,也可以用来登录到服务器。对于无法进行交互式Windows会话的用户,Office Automation不起作用。

+0

谢谢忘了提到,在begginig我有问题的COM权限,所以我把用户放在我的应用程序池,它是阿伦雷与用户权限运行,所以现在我得到这个不同的例外 –