[英]C# excel interop cut and paste exception
我正在做一个项目,却遇到了一个我不知道如何解决的异常。 我到处搜索,找不到解决方案。
我正在尝试在已在A列的单元格中找到特定值的电子表格中切出一个范围,并将该特定值的整个行粘贴到从A2开始的新电子表格中,直到不再在原始值中找到该值为止。电子表格。
我的代码当前在新的电子表格中粘贴了一行,然后给了我这个例外:“信息无法粘贴,因为剪切区域和粘贴区域的大小和形状不相同。”
Excel.Range from = currentFind.EntireRow;
Excel.Range to = oSheet.get_Range("A2:A2500");
我想我需要使用活动单元格和活动工作表属性。
请帮我!
public void btnLoad_Click(object sender, EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
if (dmCheck.IsChecked == true && fldCheck.IsChecked == true)
{
oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add());
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
string dXLPath = @"N:/DAILY2.xlsx";
Excel.Workbook dWB = oXL.Workbooks.Open(dXLPath);
Excel.Worksheet dSheet = dWB.Worksheets.get_Item(1);
Excel.Range dRng = dSheet.get_Range("B1");
dRng.EntireColumn.Hidden = true;
Excel.Range currentFind = null;
Excel.Range firstFind = null;
Excel.Range taskHazpoi = dSheet.get_Range("A2", "A2500");
currentFind = taskHazpoi.Find("HAZPOI", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
while(currentFind != null)
{
if (firstFind == null)
{
firstFind = currentFind;
}
else if (currentFind.get_Address(Excel.XlReferenceStyle.xlA1) == firstFind.get_Address(Excel.XlReferenceStyle.xlA1))
{
break;
}
Excel.Range from = currentFind.EntireRow;
Excel.Range to = oSheet.get_Range("A2:A2500");
from.Cut(to);
currentFind = taskHazpoi.FindNext(currentFind);
}
else if (dmCheck.IsChecked == false && fldCheck.IsChecked == false)
{
MessageBox.Show("Please check the DM and Flood box", "Report Loader");
}
我建议您使用Epplus代替interop Excel(我使用它)。 好处:
无需在系统中安装Office软件包。
内存中没有Excel实例。
方法更清晰。
使用示例:
http://zeeshanumardotnet.blogspot.com.es/2011/06/creating-reports-in-excel-2007-using.html?m=1
您在Nuget中找到了它。
问候,
您尝试将整行复制到单元格区域A2:A2500中,这就是触发异常的原因。
对于“至”范围,请使用oSheet.get_Range("A2").EntireRow
或oSheet.get_Range("A:A")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.