简体   繁体   中英

Export To Excel C# Error

I don't get the error that appears in my export to excel code. I have this error

Unable to cast COM object of type 'System.__ComObject' to interface type '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)).

Here is the code in my gridview, my gridview's name is 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.

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:

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;

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

Further explanation: MSDN provides the following note regarding the Workbook Interface....

"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."

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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