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);
for (int l = 0; l < 4; l++)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(l);
xlWorkSheet.Cells[1, 1] = "Report";
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;
}
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();
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