Click here to Skip to main content
15,914,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying something like this for saving the data to excel sheet 4

C#
Excel.Worksheet xlWorkSheet4 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);
           

             i = 1;
             foreach (DataRow row in lstDS[2].Tables[0].Rows)
             {


                 string fieldFromDB = row[1].ToString();
                 string FromDB = row[2].ToString();
             //   // if (FromDB.StartsWith("GW"))
                 foreach (DataRow row1 in lstDS[0].Tables[0].Rows)
                {
                     string fieldFromDB1 = row1[1].ToString();

                    if (fieldFromDB == fieldFromDB1)
                     {

                 foreach (DataRow row2 in lstDS[1].Tables[0].Rows)
                 {
                     string fieldFromDB2 = row2[1].ToString();
                         //xlWorkSheet2.Cells[i, 1] = row[8];
                         //xlWorkSheet2.Cells[i, 2] = row1[8];
                     if (fieldFromDB1 == fieldFromDB2)
                     {

                         xlWorkSheet4.Cells[i, 1] = fieldFromDB;
                         xlWorkSheet4.Cells[i, 2] = fieldFromDB1;
                         xlWorkSheet4.Cells[i, 3] = fieldFromDB2;
                         i++;

                     }



                 }
             }
                     }
             }
           


            xlWorkBook.SaveAs(path1, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);


I have no problem when trying to save into excel sheets 1,2,3

I am getting unhandled exception when I am trying to save into excel sheet 4

Additional information: Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

Can any one help me in solving this???


Thanks
John
Posted
Updated 9-Dec-13 12:28pm
v2
Comments
Sergey Alexandrovich Kryukov 9-Dec-13 13:30pm    
In what line?
—SA
KmgKrishnan 9-Dec-13 18:50pm    
Check how many sheets that you have in your work book and add it manually before doing the above operation. I believe Adam Zgagacz solution should be working fine.

1 solution

When you create new Workbook in Excel it has by default only 3 worksheets.
If you want to have more you need to add them using code like:

C#
(Excel.Worksheet)xlWorkBook.Worksheets.Add();
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900