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

前端 未结 3 2147
Happy的楠姐
Happy的楠姐 2020-12-15 10:01

I am writing a C# program which copies a range of cells from a worksheet of one workbook to a worksheet of an other workbook. But the problem I am facing is I am only able t

3条回答
  •  一整个雨季
    2020-12-15 10:55

    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();
    }
    

提交回复
热议问题