使用C#在Excel中复制/粘贴单元格

时间:2017-07-25 05:28:51

标签: c# .net excel excel-vba vba

如何在Excel文件中选择特定用户范围并复制这些单元格并使用C#插入复制的单元格Shift:=xlDown

这是我需要转换为C#的VBA代码:

Range("A9:L9").Select
Selection.Copy
Rows("10:10").Select
Selection.Insert Shift:=xlDown
Range("F10").Select

我不知道如何将此代码转换为C#代码才能运行。

4 个答案:

答案 0 :(得分:5)

如果你还没有尝试过,那么你可以试试这个

VSMicrosoft.Office.Interop.Excel

中添加对项目的引用
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
    static void Main(string[] args)
    {
       var excelapp = new Excel.Application();
       excelapp.Workbooks.Add();
       string path = "Your Excel Path";            
       Excel.Workbook workbook = excelapp.Workbooks.Open(path);
       Excel.Worksheet workSheet = workbook.Worksheets.get_Item(1);
       Excel.Range source = workSheet.Range["A9:L9"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
       Excel.Range dest = workSheet.Range["F10"];
       source.Copy(dest);
    }
}

答案 1 :(得分:1)

下面的代码在 Excel 工作簿之间执行复制粘贴,我可以根据您的需要提供三种方法。第一 - 从工作表上的所有行和列复制数据,第二 - 仅将数据复制到 B 列(2 列),无论其他列中是否有更多数据,第三 - 类似于 opt2,但具有特殊粘贴功能。此外,它会保存所有内容,关闭并终止 PID,因此没有打开的 Excel Com-Object。

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

namespace Excel
{
class CopyPaste2
{
    public CopyPaste2()
    {
        //copy-paste dynamic range

        source2WB = @"C:\WIP\source2WB.xlsm";
        destinationWB = @"C:\WIP\destinationWB.xlsm";

        Application xlApp = new Application();
        xlApp.Visible = true;

        Workbook sourceWorkbook2 = xlApp.Workbooks.Open(source2WB, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        Workbook destinationWorkbook = xlApp.Workbooks.Open(destinationWB, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        Worksheet SourceWorksheet = sourceWorkbook2.Worksheets.get_Item("Source2WSname");
        Worksheet DestinationWorksheet = destinationWorkbook.Worksheets.get_Item("destinationWSname");

        //Option 1 - copy data from all columns with value
        //Range last = SourceWorksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
        //Range sourceRng = SourceWorksheet.get_Range("A1", last);

        //Option 2 - copy only data up to column defined (i.e.A - 1 col, B - 2 cols etc.) regardless if there is more data in other columns
        Range last = SourceWorksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing).End[XlDirection.xlToLeft];
        Range sourceRng = SourceWorksheet.get_Range("B1", last);

        //Option 3 - copy only data up to column defined (i.e.A - 1 col, B - 2 cols etc.) regardless if there is more data in other columns
        //Range last = SourceWorksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing).End[XlDirection.xlToLeft];
        //Range sourceRng = SourceWorksheet.get_Range("B1", last);
        //      sourceRng.Copy(Missing.Value);

        //Option 3 - paste data into column 3 under last used row
        //Range destUsedRange = DestinationWorksheet.UsedRange;
        //int nRows = destUsedRange.Rows.Count +1;
        //Range destPaste = (Range)DestinationWorksheet.Cells[nRows, 3];
        //      destPaste.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

        //Option 1 and 2 - paste data into column 3 under last used row
        Range destUsedRange = DestinationWorksheet.UsedRange;
        int nRows = destUsedRange.Rows.Count +1;
        Range destPaste = (Range)DestinationWorksheet.Cells[nRows, 3];

        sourceRng.Copy(destPaste);

        destinationWorkbook.Save();
        sourceWorkbook2.Close();
        destinationWorkbook.Close();
        xlApp.Quit();

        int pid = -1;
        HandleRef hwnd = new HandleRef(xlApp, (IntPtr)xlApp.Hwnd);
        GetWindowThreadProcessId(hwnd, out pid);

        KillProcess(pid, "EXCEL");
    }


    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);
    static public void KillProcess(int pid, string processName)
    {
        // to kill current process of excel
        Process[] AllProcesses = Process.GetProcessesByName(processName);
        foreach (Process process in AllProcesses)
        {
            if (process.Id == pid)
            {
                process.Kill();
            }
        }
        AllProcesses = null;
    }
}
}

答案 2 :(得分:0)

Excel.Application excelapp = new Excel.Application();
excelapp.Workbooks.Add();
string path = @"Z:\Excel operation\TestExcel\hi.xlsx";
Excel.Workbook workbook = excelapp.Workbooks.Open(path);
Excel.Worksheet workSheet = workbook.Worksheets.get_Item(1);
workSheet.Range["A9:L9"].Copy(workSheet.Range["A10:L10"]);
      workSheet.Range["A10:L10"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
excelapp.Visible = true;
var source = workSheet.Range["A9:L9"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
            Excel.Range dest = workSheet.Range["A10:L10"];
workSheet.Range["A9:L9"].Copy(dest);
excelapp.ActiveWorkbook.Save();
excelapp.Visible = true;

答案 3 :(得分:0)

使用EPPlus-Excel最好的C#开源库之一-您可以执行以下操作

bool

您可以通过在NuGet软件包管理器控制台中运行以下命令,使用Nuget安装EPPlus。

        var fileName = new FileInfo(@"C:\Temp\sample101.xlsx");

        //lets open the copy 
        using (var excelFile = new ExcelPackage(fileName))
        {
           // select 1st worksheet
           var worksheet = excelFile.Workbook.Worksheets[0];

           // copy from A9:L9 
           var cellRange = worksheet.Cells["A9:L9"];

           // copy to destination A10:L10
           var destination = worksheet.Cells["A10:L10"];
           cellRange.Copy(destination);

           // save file
           excelFile.Save();
        }