简体   繁体   English

导出到Excel C#错误

[英]Export To Excel C# Error

I don't get the error that appears in my export to excel code. 我没有得到导出到excel代码中出现的错误。 I have this error 我有这个错误

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Range'. 无法将“System .__ ComObject”类型的COM对象强制转换为接口类型“Microsoft.Office.Interop.Excel.Range”。 This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020846-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)). 此操作失败,因为由于以下错误,对IID为“{00020846-0000-0000-C000-000000000046}”的接口的COM组件的QueryInterface调用失败:不支持此类接口(HRESULT异常:0x80004002(E_NOINTERFACE)) 。

Here is the code in my gridview, my gridview's name is dgvCommission. 这是我的gridview中的代码,我的gridview的名字是dgvCommission。

void worker_DoWork(object sender, DoWorkEventArgs e)
   {
       try
        {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_elapsed);
            timer.Start();
            Invoke(new MyDelegate(ShowLabel), "Loading...");

            BACS.DateFrom = this.dtFrom.Value.ToShortDateString(); //this.dtFrom.Text;
            BACS.DateTo = this.dtTo.Value.ToShortDateString(); //this.dtTo.Text;
            BACS.BrokerAgent = BrokerXML;
            BACS.Payor = PayorXML;
            DS = BACS.GET_SP_BACS_ComputeCommission();
            ReadData(DS, this.dgvCommision);
            CheckGrid();
            Thread.Sleep(1);
            timer.Stop();
        }
       catch
       { }
    }

And here is my export to excel code in my form. 这是我在表单中导出到excel代码。

private void ExportToExcel()
    {
        string[] arrays = new string[19];
        arrays[0] = "Type";
        arrays[1] = "Broker Agent";
        arrays[2] = "Payor";
        arrays[3] = "Billing #";
        arrays[4] = "OR No.";
        arrays[5] = "OR Date";
        arrays[6] = "Particulars";
        arrays[7] = "Mode";
        arrays[8] = "Amount Billed";
        arrays[9] = "Amount Paid";
        arrays[10] = "Non Comm Items";
        arrays[11] = "Net";
        arrays[12] = "Output VAT";
        arrays[13] = "Commissionable Amount";
        arrays[14] = "WTAX Rate";
        arrays[15] = "WTAX";
        arrays[16] = "Net Commission";
        arrays[17] = "InputVAT";
        arrays[18] = "For Fund Release";

        SystemUtil.ExportToExel(DS, arrays);
    }

ExportToExcel class code is this: ExportToExcel类代码是这样的:

public void ExportToExel(DataSet ds,string[] arrays)
    {
            Excel.Application oXL;
            Excel.Workbook oWB;
            Excel.Worksheet oSheet;
            //Excel.Range oRange;

            oXL = new Excel.Application();
            // Set some properties 
            oXL.Visible = true;
            oXL.DisplayAlerts = false;

            // Get a new workbook. 
            oWB = oXL.Workbooks.Add(Missing.Value);

            // Get the active sheet 
            oSheet = (Excel.Worksheet)oWB.ActiveSheet;
            oSheet.Name = "EXCEL";

            DataTable dt2 = new DataTable(); 
            if (ds.Tables[0] != null)
            {
                dt2 = ds.Tables[0];
            }


            int rowCount = 1;
            foreach (DataRow dr in dt2.Rows)
            {
                rowCount += 1;
                for (int i = 1; i < dt2.Columns.Count + 1; i++)
                {
                    if (rowCount == 2)
                    {
                        oSheet.Cells[1, i] = arrays[i - 1];// dt.Columns[i - 1].ColumnName;
                        // oSheet.Cells[1,i].Font.Background = System.Drawing.Color.Red;
                    }
                    oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
                }
            }

            ////// Resize the columns 
            //oRange = oSheet.get_Range(1, 23);
            ////oRange.EntireColumn.AutoFit();
            //oRange.Range[1, 2].AutoFit();

            // Save the sheet and close 
            oSheet = null;
            // oRange = null;
            //oWB.SaveAs(@"c:\REPORTS.xls", Excel.XlFileFormat.xlWorkbookNormal,
            //    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            //    Excel.XlSaveAsAccessMode.xlExclusive,
            //    Missing.Value, Missing.Value, Missing.Value,
            //    Missing.Value, Missing.Value);
            //oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            //oWB = null;
            //oXL.Quit();

            // Clean up 
            // NOTE: When in release mode, this does the trick 
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
    }

The exception error pops up in this code. 此代码中会弹出异常错误。 oSheet.Cells[1, i] = arrays[i - 1];

Do you guys know how can this happen? 你们知道这怎么可能发生吗? I don't understand what's wrong in my code.. Please help me on this one. 我不明白我的代码中有什么问题..请帮我解决这个问题。 Thanks in advance for your help. 在此先感谢您的帮助。

Try changing 尝试改变

oSheet = (Excel.Worksheet)oWB.ActiveSheet; oSheet =(Excel.Worksheet)oWB.ActiveSheet;

To oSheet = (Excel.Worksheet)oXL.ActiveSheet; 至oSheet =(Excel.Worksheet)oXL.ActiveSheet;

Further explanation: MSDN provides the following note regarding the Workbook Interface.... 进一步说明:MSDN提供了有关工作簿界面的以下注释....

"This interface is implemented by the Visual Studio Tools for Office runtime. It is not intended to be implemented in your code. For more information, see Visual Studio Tools for Office Runtime Overview." “此接口由Visual Studio Tools for Office运行时实现。它不适用于您的代码。有关详细信息,请参阅用于Office运行时概述的Visual Studio工具。”

That's why you have to reference the application interface after initializing a new workbook. 这就是为什么在初始化新工作簿后必须引用应用程序接口的原因。

Please mark this as answered if it resolved your question. 如果它解决了您的问题,请将其标记为已回答。

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

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