简体   繁体   中英

C# “COMException was unhandled”

VS is showing me an error when I run my program, it starts fine and the datagrid is populated with info from my Access DB file, but when the DoWork button is triggered i'm seeing the following error on line 37 ws.Cells[1, 0] = "Act";

An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code

 Additional information: Exception from HRESULT: 0x800A03EC 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Threading;
using System.Data.OleDb;

namespace DataExporter
{
    public partial class Form1 : Form
    {
        System.Data.DataTable dt = new System.Data.DataTable();
        public Form1()
        {
            InitializeComponent();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //List<Product> list = ((DataParameter)e.Argument).ProductList;
            System.Data.DataTable list = ((DataParameter)e.Argument).ProductList;
            string filename = ((DataParameter)e.Argument).FileName;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
            Worksheet ws = (Worksheet)excel.ActiveSheet;
            excel.Visible = false;
            int index = 1;
            //int process = list.Count;
            int process = list.Rows.Count;
            //Add Column
            ws.Cells[1, 0] = "Act";
            ws.Cells[1, 1] = "ProductID";
            ws.Cells[1, 2] = "ProductKey";
            ws.Cells[1, 3] = "AllowInternetOrder";
            ws.Cells[1, 4] = "AllowPhoneOrder";
            ws.Cells[1, 5] = "AllowProductReview";
            ws.Cells[1, 6] = "AvailabilityRule";
            ws.Cells[1, 7] = "BuyingGuide";
            ws.Cells[1, 8] = "BuyingGuideName";
            ws.Cells[1, 9] = "CreateDate";
            ws.Cells[1, 10] = "DisplayOrder";
            ws.Cells[1, 11] = "DisplayTemplate";
            ws.Cells[1, 12] = "DynamicFormCode";
            ws.Cells[1, 13] = "Extension";
            ws.Cells[1, 14] = "FAQ";
            ws.Cells[1, 15] = "FAQName";
            ws.Cells[1, 16] = "Featured";
            ws.Cells[1, 17] = "MetaDescription";
            ws.Cells[1, 18] = "MetaKeywords";
            ws.Cells[1, 19] = "Name";
            ws.Cells[1, 20] = "Overview";
            ws.Cells[1, 21] = "OverviewName";
            ws.Cells[1, 22] = "PageTitle";
            ws.Cells[1, 23] = "ProductDetailUrl";
            ws.Cells[1, 24] = "ProductType";
            ws.Cells[1, 25] = "Published";
            ws.Cells[1, 26] = "RedirectUrl";
            ws.Cells[1, 27] = "SellerID";
            ws.Cells[1, 28] = "ShowAddToCart";
            ws.Cells[1, 29] = "ShowAddToWishList";
            ws.Cells[1, 30] = "ShowBuyNow";
            ws.Cells[1, 31] = "ShowInventory";
            ws.Cells[1, 32] = "ShowMSRP";
            ws.Cells[1, 33] = "ShowPrice";
            ws.Cells[1, 34] = "ShowQuantity";
            ws.Cells[1, 35] = "ShowRewardPoints";
            ws.Cells[1, 36] = "ShowSavings";
            ws.Cells[1, 37] = "ShowSeeDetails";
            ws.Cells[1, 38] = "ShowSKU";
            ws.Cells[1, 39] = "ShowSocialShare";
            ws.Cells[1, 40] = "ShowUpdate";
            ws.Cells[1, 41] = "Specifications";
            ws.Cells[1, 42] = "SpecificationsName";
            ws.Cells[1, 43] = "StartDate";
            ws.Cells[1, 44] = "StopDate";
            ws.Cells[1, 45] = "Summary";
            ws.Cells[1, 46] = "Terms";
            ws.Cells[1, 47] = "TermsName";
            ws.Cells[1, 48] = "UpdateDate";
            ws.Cells[1, 49] = "UrlName";
            foreach (DataRow dr in list.Rows)
            {
                if (!backgroundWorker.CancellationPending)
                {
                    backgroundWorker.ReportProgress(index++ * 100 / process);
                    ws.Cells[index, 0] = dr.ItemArray[0].ToString();
                    ws.Cells[index, 1] = dr.ItemArray[1].ToString();
                    ws.Cells[index, 2] = dr.ItemArray[2].ToString();
                    ws.Cells[index, 3] = dr.ItemArray[3].ToString();
                    ws.Cells[index, 4] = dr.ItemArray[4].ToString();
                    ws.Cells[index, 5] = dr.ItemArray[5].ToString();
                    ws.Cells[index, 6] = dr.ItemArray[6].ToString();
                    ws.Cells[index, 7] = dr.ItemArray[7].ToString();
                    ws.Cells[index, 8] = dr.ItemArray[8].ToString();
                    ws.Cells[index, 9] = dr.ItemArray[9].ToString();
                    ws.Cells[index, 10] = dr.ItemArray[10].ToString();
                    ws.Cells[index, 11] = dr.ItemArray[11].ToString();
                    ws.Cells[index, 12] = dr.ItemArray[12].ToString();
                    ws.Cells[index, 13] = dr.ItemArray[13].ToString();
                    ws.Cells[index, 14] = dr.ItemArray[14].ToString();
                    ws.Cells[index, 15] = dr.ItemArray[15].ToString();
                    ws.Cells[index, 16] = dr.ItemArray[16].ToString();
                    ws.Cells[index, 17] = dr.ItemArray[17].ToString();
                    ws.Cells[index, 18] = dr.ItemArray[18].ToString();
                    ws.Cells[index, 19] = dr.ItemArray[19].ToString();
                    ws.Cells[index, 20] = dr.ItemArray[20].ToString();
                    ws.Cells[index, 21] = dr.ItemArray[21].ToString();
                    ws.Cells[index, 22] = dr.ItemArray[22].ToString();
                    ws.Cells[index, 23] = dr.ItemArray[23].ToString();
                    ws.Cells[index, 24] = dr.ItemArray[24].ToString();
                    ws.Cells[index, 25] = dr.ItemArray[25].ToString();
                    ws.Cells[index, 26] = dr.ItemArray[26].ToString();
                    ws.Cells[index, 27] = dr.ItemArray[27].ToString();
                    ws.Cells[index, 28] = dr.ItemArray[28].ToString();
                    ws.Cells[index, 29] = dr.ItemArray[29].ToString();
                    ws.Cells[index, 30] = dr.ItemArray[30].ToString();
                    ws.Cells[index, 31] = dr.ItemArray[31].ToString();
                    ws.Cells[index, 32] = dr.ItemArray[32].ToString();
                    ws.Cells[index, 33] = dr.ItemArray[33].ToString();
                    ws.Cells[index, 34] = dr.ItemArray[34].ToString();
                    ws.Cells[index, 35] = dr.ItemArray[35].ToString();
                    ws.Cells[index, 36] = dr.ItemArray[36].ToString();
                    ws.Cells[index, 37] = dr.ItemArray[37].ToString();
                    ws.Cells[index, 38] = dr.ItemArray[38].ToString();
                    ws.Cells[index, 39] = dr.ItemArray[39].ToString();
                    ws.Cells[index, 40] = dr.ItemArray[40].ToString();
                    ws.Cells[index, 41] = dr.ItemArray[41].ToString();
                    ws.Cells[index, 42] = dr.ItemArray[42].ToString();
                    ws.Cells[index, 43] = dr.ItemArray[43].ToString();
                    ws.Cells[index, 44] = dr.ItemArray[44].ToString();
                    ws.Cells[index, 45] = dr.ItemArray[45].ToString();
                    ws.Cells[index, 46] = dr.ItemArray[46].ToString();
                    ws.Cells[index, 47] = dr.ItemArray[47].ToString();
                    ws.Cells[index, 48] = dr.ItemArray[48].ToString();
                    ws.Cells[index, 49] = dr.ItemArray[49].ToString();
                }
            }
            //Save file
            ws.SaveAs(filename, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
            excel.Quit();
        }

        struct DataParameter
        {
            public System.Data.DataTable ProductList;
            public string FileName { get; set; }
        }

        DataParameter _inputParameter;

        private void Form1_Load(object sender, EventArgs e)
        {
            string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MY_DB_Name.accdb";
            using (OleDbConnection olcon = new OleDbConnection(ConnectionString))
            {
                using (OleDbDataAdapter adapter = new OleDbDataAdapter())
                {

                    string command = "MY ACCESS QUERY THAT PULLS 50 COLS HERE";
                    //cmd.CommandText = "SELECT * FROM [" + sheetName + "]";

                    OleDbCommand cmd = new OleDbCommand(command, olcon);
                    //Fill Gridview with Data from Access
                    try
                    {
                        dt.Clear();
                        adapter.SelectCommand = cmd;
                        adapter.Fill(dt);
                        dataGridView1.DataSource = dt;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    finally
                    {
                        olcon.Close();
                        var totalWidth = dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.None);
                    }
                }
            }

        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
            lblStatus.Text = string.Format("Processing...{0}", e.ProgressPercentage);
            progressBar.Update();
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread.Sleep(100);
                lblStatus.Text = "Your data has been successfully exported.";
            }
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
                return;
            using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xls" })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    _inputParameter.FileName = sfd.FileName;
                    //_inputParameter.ProductList = GetProductsList2();
                    _inputParameter.ProductList = (System.Data.DataTable)dataGridView1.DataSource;
                    progressBar.Minimum = 0;
                    progressBar.Value = 0;
                    backgroundWorker.RunWorkerAsync(_inputParameter);
                }
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

It seems, that this error because excel has non-zero based row and column numbering. You need to change

ws.Cells[1, 0] = "Act";

as

ws.Cells[1, 1] = "Act";

And change the numeration of other cells.

I have not actually find it (non-zero numbering) at official documentation, so this is only based on my experience of working with excel.

Related answer on SuperUser - Which Excel objects are zero-based and which are one-based?

Collections - 1-based index
...
Excel collections: Workbooks, Sheets, Ranges, Shapes

ws.Cells returns the Range object.

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