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

前端 未结 3 2148
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:40

    You should be able to do this:

            Excel.Range from = srcworkSheet.Range("C1:C100");
            Excel.Range to = destworkSheet.Range("C1:C100");
    
            from.Copy(to);
    
    0 讨论(0)
  • 2020-12-15 10:54

    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.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题