我有一个包含 N 行数据的 Excel.Workbook.Worksheet 对象。我有一个 Excel.Range 对象,其中包含来自另一个工作表的 M 行。如何将 Range 添加到 Worksheet 的末尾?
问问题
2407 次
2 回答
2
假设您知道如何打开两张纸(如果没有,请参阅 JMK 的答案!)您想要的具体内容是:
Range src = ...
Range dest = sheet2.Cells(N+1,1);
src.Copy(dest);
如果您事先不知道 N,您可以执行类似的操作
Range dest = wb2.Sheets["Sheet1"].Range("A1").End(XlDirection.xlDown).Offset(1);
假设 A 列中的第一个空白单元格是数据应该去的地方。(还要检查目标工作表不为空,否则 End() 将直接到达工作表的底部)
于 2013-10-15T20:09:14.247 回答
1
你应该能够做这样的事情(未经测试,可能需要稍微调整):
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var application = new Application();
var workbookCopyingFrom = application.Workbooks.Open("a.xlsx");
var workbookCopyingTo = application.Workbooks.Open("b.xlsx");
var worksheetContainingRangeIWantToCopyAcross = workbookCopyingFrom.Sheets[1] as Worksheet;
if (worksheetContainingRangeIWantToCopyAcross != null)
{
var worksheetIWantToCopyToInWorkbookTwo = workbookCopyingTo.Sheets[2] as Worksheet;
if (worksheetIWantToCopyToInWorkbookTwo != null)
{
var usedRangeInWorkbookCopyingTo = worksheetIWantToCopyToInWorkbookTwo.UsedRange;
worksheetContainingRangeIWantToCopyAcross.UsedRange.Insert(XlInsertShiftDirection.xlShiftDown,
usedRangeInWorkbookCopyingTo);
worksheetIWantToCopyToInWorkbookTwo.Rows.Clear();
worksheetIWantToCopyToInWorkbookTwo.Rows.Insert(
CopyOrigin: worksheetContainingRangeIWantToCopyAcross);
}
}
workbookCopyingTo.Save();
workbookCopyingTo.Close();
application.Quit();
Marshal.ReleaseComObject(application);
}
}
}
于 2013-10-14T14:16:39.950 回答