Excel InterOp - 将范围添加到工作表的末尾

时间:2013-10-14 13:58:44

标签: c# office-interop com-interop excel-interop

我有一个包含N行数据的Excel.Workbook.Worksheet对象。我有一个Excel.Range对象,其中包含来自另一个工作表的M行。如何将范围添加到工作表的末尾?

2 个答案:

答案 0 :(得分: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()将直接到表格的底部)

答案 1 :(得分: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);
        }
    }
}