Вопрос

У меня есть файл Excel на веб-сервере, где развернут мой сайт. Сценарий, у меня есть экран, который позволяет пользователю загружать файл Excel с веб-сервера и сохранять до локального диска, затем выберите тот же путь к экспорту данных, но я получаю ошибку ниже.

ASP.NET не авторизован для доступа к запрошенному ресурсу. Рассмотреть возможность Предоставление прав доступа к ресурсу к запросу ASP.NET личность. ASP.NET имеет идентичность базового процесса (обычно {Machine} \ aspnet на IIS 5 или сетевой службе по IIS 6), который используется, если Применение не осенствует. Если приложение олицетворение через, личность будет анонимный пользователь (как правило, IUSR_MACHINENAME) или аутентифицированный Запросить пользователя. Чтобы получить доступ ASP.NET в файл, щелкните правой кнопкой мыши файл В Explorer выберите «Свойства» и выберите вкладку «Безопасность». Щелчок «Добавить», чтобы добавить соответствующего пользователя или группу. Выделите ASP.NET.NET. Учетная запись и установите флажки для желаемого доступа.

Это мой код:

private void btnExportToExcel_Click(object sender, System.EventArgs e)
{
    Microsoft.Office.Interop.Excel.ApplicationClass appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
    DataSet dsResult = new DataSet();
    object missingValue = System.Reflection.Missing.Value;
    decimal wkOpenBal = 0.00m;
    decimal wkAddition = 0.00m; 
    decimal wkDisposal = 0.00m;
    string rptDt = "";

    decimal os_p = 0.00M;
    decimal os_s = 0.00M;
    decimal closs_16_25 = 0.00M;
    decimal closs_26 = 0.00M;
    decimal os_clr_p = 0.00M;
    decimal os_whs_p = 0.00M;
    decimal os_clr_s = 0.00M;
    decimal os_whs_s = 0.00M;           
    decimal mark_to_mkt = 0.00M;
    decimal mark_to_mkt_error = 0.00M;


    if(txtWeeklyFile.Value != "")
    {
        //DATABASE CALL
        objBursaSubmission = (IBursaSubmission) ObjectFactory.Instance.GetObject(ObjectIdentifier.BursaSubmissionManager);                      
        dsResult = objBursaSubmission.GetReportData(txtRptdt.Text);

        try
        {
            if(dsResult != null && dsResult.Tables[0].Rows.Count > 0)
            {
                if(System.IO.File.Exists(txtWeeklyFile.Value.ToString()))
                {
                    wkOpenBal = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["WK_OPENBAL"]);
                    wkAddition = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["WK_ADDITION"]);
                    wkDisposal = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["WK_DISPOSAL"]);
                    rptDt = dsResult.Tables[0].Rows[0]["LOGICAL_DT"].ToString();                

                    os_p = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["OS_P"]);
                    os_s = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["OS_S"]);
                    closs_16_25 = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["CLOSS_16_25"]);
                    closs_26 = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["CLOSS_26"]);
                    os_clr_p = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["OS_CLR_P"]);
                    os_whs_p = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["OS_WHS_P"]);
                    os_clr_s = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["OS_CLR_S"]);
                    os_whs_s = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["OS_WHS_S"]);
                    mark_to_mkt = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["MARK_TO_MKT"]);
                    mark_to_mkt_error = Convert.ToDecimal(dsResult.Tables[0].Rows[0]["mark_to_mkt_error"]);

                    decimal clr_total_p = os_clr_p + os_whs_p;
                    decimal clr_total_s = os_clr_s + os_whs_s;

                    Microsoft.Office.Interop.Excel.Workbook wBook = appExcel.Workbooks.Open(txtWeeklyFile.Value.ToString(),Type.Missing,Type.Missing,Type.Missing,
                        Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,
                        Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);

                    //SHEET MARKET POSITION SHEET 1                                                             
                    Worksheet sheetMarktetPosition1 = (Worksheet)wBook.Sheets[1];                       
                    Range mPositionRange = sheetMarktetPosition1.UsedRange;                 

                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[6,7]).Value2 = rptDt.ToString();

                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[14,3]).Value2 = os_p.ToString();
                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[14,7]).Value2 = mark_to_mkt.ToString();                         
                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[16,3]).Value2 = os_s.ToString();                            
                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[15,5]).Value2 = "";
                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[40,3]).Value2 = clr_total_p.ToString();
                    ((Microsoft.Office.Interop.Excel.Range)mPositionRange.Cells[41,3]).Value2 = clr_total_s.ToString();
                }
            }
        }
        catch (Exception ex)
        {
            //code for any other type of exception
        }
    }
}
.

Это было полезно?

Решение

You cannot safely use Office Automation from a server process. See the answer to Editing an Excel document with Macros in ASP.NET to learn how far you have to go to make this safe. See ASP.NET Web Service using office 2010 COM to learn what can happen if you just try calling it from ASP.NET.

The problem, briefly, is that Office Automation was designed for the automation, from a desktop application, of the Microsoft Office products, which are desktop applications. All sorts of things don't work properly when you're using them from a server application.

Другие советы

Do you have remote desktop access to this server?

You will need to set the permissions on the folder that the Excel file is being exported to as well as setup the permissions in DCOMCNFG so that the AppPool user can automate Excel. (Start, Run, DCOMCNFG, Component Services, Computers, DCOM Config and right click the Microsoft Excel object.

Have you considered an Excel writer instead? Such as EPPlus.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top