[英]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".我编写的代码仅适用于 xlsx 文件,如果我使用 xls 文件运行它,我会得到“范围 class 的复制方法失败”。 I need a solution which will work with specifically xls files.我需要一个适用于特定 xls 文件的解决方案。
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.我认为问题在于您在 Excel 应用程序的 2 个实例中打开 Excel 文件。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.