簡體   English   中英

使用 C# 在 Excel 中復制/粘貼單元格

[英]Copy/paste cells in Excel with C#

如何在 Excel 文件中選擇特定用戶范圍並復制這些單元格並使用 C# 插入復制的單元格Shift:=xlDown

這是我需要轉換為 C# 的 VBA 代碼:

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

我不知道如何將這段代碼轉換成 C# 代碼來運行。

如果你還沒有嘗試過這個,那么你可以試試這個

VS添加對您的項目的引用: Microsoft.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);
    }
}

下面的代碼在 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;
    }
}
}
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;

使用EPPlus - Excel 最好的 C# 開源庫之一 - 您可以執行以下操作

        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();
        }

您可以通過在 NuGet 包管理器控制台中運行以下命令來使用 Nuget 安裝 EPPlus。

Install-Package EPPlus

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM