簡體   English   中英

無法訪問對象Excel WorkBook ASP.NET的屬性“ saveAs”

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

我在這里有一個小問題:我有一個用C#構建的asp.net應用程序,它會生成一個Excel數據透視表。 當我使用Visual Studio的IIS Express在localhost上運行它時,我沒有問題,它從數據源創建文件並將其下載到我的下載文件夾中而沒有問題。

但是,一旦將它放在IIS Server的生產環境中並嘗試測試該應用程序,當我單擊導出按鈕時,就會出現以下異常:

說明:執行當前Web請求時出現未處理的異常。 查看堆棧跟蹤以獲取有關錯誤及其在代碼中起源的更多信息。

異常:System.Runtime.InteropServices.COMException:無法獲得對Workbook類的SaveAs屬性的訪問權限。

源代碼錯誤:

執行當前Web請求時出現未處理的異常。 查看堆棧跟蹤以獲取有關錯誤及其在代碼中起源的更多信息。

池跟蹤:

[COMException(0x800a03ec):無法訪問Workbook類的SaveAs屬性。
System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult,ExcepInfo&excepInfo,UInt32 argErr,字符串消息)+145
CallSite.Target(Closure,CallSite,ComObject,String)+702
System.Dynamic.UpdateDelegates.UpdateAndExecute2(CallSite網站,T0 arg0,T1 arg1)+491
System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2(CallSite網站,T0 arg0,T1 arg1)+657
inicio.pivotTable(DataTable源)+11550
inicio.btnExportar_Click(對象發送者,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(布爾includeStagesBeforeAsyncPoint,布爾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;
}

我不知道該怎么辦,感謝您的幫助

嘗試使用IIS中的“應用程序池”運行該應用程序,該池使用服務器上Windows用戶的憑據(也可用於登錄服務器)。 Office Automation對於無法進行交互式Windows會話的用戶不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM