I have tried searching this on google but could get the answer for my problem. I am trying to merge multiple excel files into single one using below code. But it is giving me error like below (no additional info in innerexception) at sheet.Copy command.
Unable to get the Copy property of the Worksheet class
Code...
private void MergeXlsxFiles(string destXlsxFileName, params string[] sourceXlsxFileNames)
{
Application excelApp = null;
Workbook destWorkBook = null;
var temppathForTarget = Path.Combine(Directory.GetCurrentDirectory() , Guid.NewGuid() + ".xls");
if (File.Exists(temppathForTarget))
File.Delete(temppathForTarget);
try
{
excelApp = new Application
{
DisplayAlerts = false,
SheetsInNewWorkbook = 3
};
destWorkBook = excelApp.Workbooks.Add();
destWorkBook.SaveAs(temppathForTarget);
foreach (var sourceXlsxFile in sourceXlsxFileNames)
{
var file = Path.Combine(Directory.GetCurrentDirectory(), sourceXlsxFile);
var sourceWorkBook = excelApp.Workbooks.Open(file);
foreach (Worksheet ws in sourceWorkBook.Worksheets)
{
var wSheet = destWorkBook.Worksheets[destWorkBook.Worksheets.Count];
ws.Copy(wSheet);
destWorkBook.Worksheets[destWorkBook.Worksheets.Count].Name =
ws.Name;
}
sourceWorkBook.Close(XlSaveAction.xlDoNotSaveChanges);
}
destWorkBook.Sheets[1].Delete();
destWorkBook.SaveAs(destXlsxFileName);
}
catch (Exception ex)
{
}
finally
{
if (destWorkBook != null)
destWorkBook.Close(XlSaveAction.xlSaveChanges);
if (excelApp != null)
excelApp.Quit();
}
}
Does anyone knows what is wrong with this code.
I am referring Microsoft.Office.Interop.Excel dll from GAC with version 15.0.0.0 and I have MSOffice 2013 installed on my machine.
in sourceWorkBook.Sheetsand/ordestWorkBook.Sheets.Sheetsare not the same things asWorksheets. They can be, but they can also be other kinds of sheets, such as chart sheets. Tryin sourceWorkbook.Worksheetsand destWorkBook.Worksheets`?