copying of specific range of excel cells from one worksheet to another worksheet

mrtig has a very elegant solution. But it won't work if you have the workbooks in separate instances of excel. So, the key is to open them in just one instance. I've modified your example to show using this approach:

public void CopyRanges()
{
    // only one instance of excel
    Excel.Application excelApplication = new Excel.Application();

    srcPath="C:\\Documents and Settings\\HARRY\\Desktop\\incident.csv";
    Excel.Workbook srcworkBook = excelApplication.Workbooks.Open(srcPath);
    Excel.Worksheet srcworkSheet = srcworkBook.Worksheets.get_Item(1);

    destPath = "C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report.xls";
    Excel.Workbook destworkBook = excelApplication.Workbooks.Open(destPath,0,false);
    Excel.Worksheet destworkSheet = destworkBook.Worksheets.get_Item(1);

    Excel.Range from = srcworkSheet.Range("C1:C100");
    Excel.Range to = destworkSheet.Range("C1:C100");

    // if you use 2 instances of excel, this will not work
    from.Copy(to);

    destworkBook.SaveAs("C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report " + DateTime.Now.ToString("MM_dd_yyyy") + ".xls");
    srcxlApp.Application.DisplayAlerts = false;
    destxlApp.Application.DisplayAlerts = false;
    destworkBook.Close(true, null, null);
    srcworkBook.Close(false, null, null);
    excelApplication.Quit();
}

You should be able to do this:

        Excel.Range from = srcworkSheet.Range("C1:C100");
        Excel.Range to = destworkSheet.Range("C1:C100");

        from.Copy(to);

For the First part of setting the same value for the entire range, instead of looping following will work out

range1 = workSheet.get_Range("A1:B100"); range1.Value = "Fixed";

And for copying you can try what @mrtig has suggested.

Tags:

C#

Excel