简体   繁体   中英

Paste selected range from one xls file to another into a designated sheet and cell - “Copy method of Range class failed”

I wrote code which works only on xlsx files, if I run it with xls files I get "Copy method of Range class failed". I need a solution which will work with specifically xls files.

using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

public class Xls: CopyPaste
{
    public override void Run() {
        String srcPath = "C:\\test1.xls";
        Excel.Application xlsSrcApp;
        xlsSrcApp = new Excel.Application();
        Excel.Workbook srcXls = xlsSrcApp.Workbooks.Open(srcPath);
        Excel.Worksheet srcWrks = (Excel.Worksheet)srcXls.Worksheets["Sheet1"];
        Excel.Range srcRange;

        String destPath = "C:\\test2.xls";
        Excel.Application xlsDestApp;
        xlsDestApp = new Excel.Application();
        Excel.Workbook destXls = xlsSrcApp.Workbooks.Open(destPath, 0, false);
        Excel.Worksheet destWrks = (Excel.Worksheet)xlsDestApp.Worksheets["Sheet1"];
        Excel.Range destRange;

        Excel.Range srcRange = srcWrks.Range["A1:B2"];
        Excel.Range destRange = destWrks.Range["A10"];

        srcRange.Copy(destRange);

        destXls.SaveAs(destPath);

        xlsSrcApp.Application.DisplayAlerts = False;
        srcXls.Close(true, null, null);
        xlsSrcApp.Quit();

        xlsDestApp.Application.DisplayAlerts = False;
        destXls.Close(true, null, null);
        xlsDestApp.Quit();
    }
}

I think the problem is that you are opening the Excel files in 2 instances of the Excel Application.

Try this, it works for me.

using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

public class Xls: CopyPaste
{
    public override void Run() {
        string srcPath = "C:\\test1.xls";
        Excel.Application xlsSrcApp;
        xlsSrcApp = new Excel.Application();
        Excel.Workbook srcXls = xlsSrcApp.Workbooks.Open(srcPath);
        Excel.Worksheet srcWrks = (Excel.Worksheet)srcXls.Worksheets["Sheet1"];
        Excel.Range srcRange;

        string destPath = "C:\\test2.xls";
        Excel.Workbook destXls = xlsSrcApp.Workbooks.Open(destPath, 0, false);
        Excel.Worksheet destWrks = (Excel.Worksheet)destXls.Worksheets["Sheet1"];
        Excel.Range destRange;

        srcRange = srcWrks.Range["A1:B2"];
        destRange = destWrks.Range["A10"];

        srcRange.Copy(destRange);

        //No need to do SaveAs you set SaveChanges on Close to true
        //destXls.SaveAs(destPath);

        xlsSrcApp.Application.DisplayAlerts = false;
        srcXls.Close();
        destXls.Close(true);
        xlsSrcApp.Quit();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM