Click here to Skip to main content
15,881,744 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get multiple excel sheets in same workbook. I found solution for that. Here is my code...

public void Export(DataTable ds, string filePath)
{
string data = null;
string columnName = null;
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet=null;
object misValue = System.Reflection.Missing.Value;
Excel.Range range;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);

C#
for (int l = 0; l < 4; l++)
       {
           xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(l);
           xlWorkSheet.Cells[1, 1] = "Report";
          // xlWorkSheet.get_Range("A1:D1", Type.Missing).Merge(Type.Missing);
         //  xlWorkSheet.get_Range("A1", "D1").Font.Bold = true;
           xlWorkSheet.Cells.Font.Name = "Courier New";
           xlWorkSheet.Name = "Sheet" + DateTime.Now.Second.ToString();
           columnName = ds.Columns[l].ColumnName.ToString();
           xlWorkSheet.Cells[3, l+1] = columnName;
           data = ds.Rows[1].ItemArray[l].ToString();
           xlWorkSheet.Cells[1, l+1] = data;

C#
}

        xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();


C#
Process[] pros = Process.GetProcesses();
       for (int p = 0; p < pros.Length; p++)
       {
           if (pros[p].ProcessName.ToLower().Contains("excel"))
           {
               pros[p].Kill();
               break;
           }
       }

       releaseObject(xlWorkSheet);
       releaseObject(xlWorkBook);
       releaseObject(xlApp);
   }
   private void releaseObject(object obj)
   {
       try
       {
           System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
           obj = null;
       }
       catch (Exception ex)
       {
           obj = null;
       }
       finally
       {
           GC.Collect();
       }
   }



but after the creation of third sheet when loop executing for 4th excel sheet error is throwing as "Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))". Please help me
Posted
Comments
Member 12305778 24-Nov-17 1:28am    
Any one have answer for this?
Please give solution

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