So, after much researching and using code below in a Class the items I’m passing (a DataTable) open up in Excel. I have around 5 sheets that need to open in the same book. The code below is for the first 2. The problem is they are all opening in NEW WorkBooks — I need them all to open in the SAME WorkBook. They are opening on the correct sheet in each new Workbook though. I thought a simple “if” statement would work, however, it is not–
Any input on how to get them consolidated into one WorkBook would be greatly appreciated and thanks in advance!
Microsoft.Office.Interop.Excel.Application oExcel = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
oExcel.Visible = true;
oExcel.DisplayAlerts = false;
oExcel.Application.SheetsInNewWorkbook = 5;
oBooks = oExcel.Workbooks;
oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
oSheets = oBook.Worksheets;
if (sheetName == "Combined")
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
oSheet.Name = sheetName;
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1, dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);
range.Value2 = arr;
}
else if (sheetName == "Auto")
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(2);
oSheet.Name = sheetName;
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}
Microsoft.Office.Interop.Excel.Range c1 =
(Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 =
(Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1,
dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);
range.Value2 = arr;
}
Well your code is a bit too long to understand without comments, but if you wanna add a new sheet inside your current workbook, there is the myWorkbook.Sheets.Add() method (where myWorkbook is a ref to your current workbook).
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.sheets.add(v=office.14).aspx