Search code examples
c#.netexcel.net-coremicrosoft.office.interop.excel

How to add multiple worksheet from different workbook to new workbook


I have three excel files and by selecting cetain sheets from workbook want to create new worksheet

var App = new Microsoft.Office.Interop.Excel.Application();

Workbook  book1 = App.Workbooks.Open(@"path");
Worksheet sheet1 = book1.Worksheets\[1\];

Workbook  book2 = App.Workbooks.Open(@"path");
Worksheet sheet2 = book2.Worksheets\[1\];

Workbook  book3 = App.Workbooks.Open(@"path");
Worksheet sheet3 = book3.Worksheets\[1\];

var newBook = App.Workbooks.Add();
sheet1.UsedRange.Copy(newBook.Worksheets[1].Range["A1"]);

---first sheet1 is adding perfectly but while adding second worksheet sheet2 it is throwing exception System.Runtime.InteropServices.COMException : Exception from HRESULT : 0x800401A8---

sheet2.UsedRange.Copy(newBook.Worksheets[2].Range["A1"]);
sheet3.UsedRange.Copy(newBook.Worksheets[3].Range["A1"]);
newBook.SaveAs(@"path\newWorkbook.xlsx");
newBook.Close();
App.Quit();

I already tried but same exception -
var sourceRange = sheet2.UsedRange; var targetRange = newBook.Worksheets[2].Range["A1"]; sourceRange.Copy(targetRange);

Solution

  • var App = new Microsoft.Office.Interop.Excel.Application();
    
    Workbook  book1 = App.Workbooks.Open(@"path");
    Worksheet sheet1 = book1.Worksheets\[1\];
    
    Workbook  book2 = App.Workbooks.Open(@"path");
    Worksheet sheet2 = book2.Worksheets\[1\];
    
    Workbook  book3 = App.Workbooks.Open(@"path");
    Worksheet sheet3 = book3.Worksheets\[1\];
    
    var newBook = App.Workbooks.Add();
    
    sheet1.Copy(newBook.Worksheets[1]);
    sheet2.Copy(newBook.Worksheets[2]);
    sheet3.Copy(newBook.Worksheets[3]);
    
    //delete sheet which created by default while creating newBook
    newBook.Worksheets[4].delete();
    
    string path = @"path";
    if(File.Exits(path))
    {
    File.Delete(path);
    }
    newBook.SaveAs(path);
    book1.Close();
    book2.Close();
    book3.Close();
    App.Quit();