0

I wanna import my ListBox in a Excel File. But i keep getting this error HRESULT: 0x800A03EC can someone help me i googled it but couldnt find anything

My code

        string ExcelFileLocation = (@"C:\Users\bra\Desktop\EXCELFILe");


        Excel.Application oApp;
        Excel.Worksheet oSheet;
        Excel.Workbook oBook;


        oApp = new Excel.Application();
        oBook = oApp.Workbooks.Add();
        oSheet = (Excel.Worksheet) oBook.Worksheets.get_Item(1);

        int i = 0;
        i++;

        for (int j = 0; j < listBox1.Items.Count; j++)
        {
            oSheet.Cells[j, 1] = listBox1.Items;

        }
        oBook.SaveAs(ExcelFileLocation);
        oBook.Close();
        oApp.Quit();

my ListBox items

  private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add("TEST1");
            listBox1.Items.Add("TEST2");
            listBox1.Items.Add("TEST3");

        }
m.h.p
  • 1
  • 2

2 Answers2

1

Your variable "j" must begin at 1 not 0.

mdelpeix
  • 147
  • 8
0

Your code is trying to assign the set of all items (i.e. ListBox.Items) to each and every cell in Excel.

What you probably meant to do is something like

for (int j = 0; j < listBox1.Items.Count; j++)
{
    oSheet.Cells[j + 1, 1] = listBox1.Items[j].ToString(); // Notice the [j] indexer
}

More importantly, excel indexes start at 1, like @mdelpeix rightfully noticed. That is most likely what is throwing the particular exception your question is about, so his answer should probably get the answer mark :)

Paul-Jan
  • 16,057
  • 58
  • 87