【问题标题】:Copy/paste cells in Excel with C#使用 C# 在 Excel 中复制/粘贴单元格
【发布时间】:2017-12-30 20:47:33
【问题描述】:

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

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

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

不知道怎么把这段代码转成C#代码运行。

【问题讨论】:

  • 你试过什么?这里没有人会为您编写代码。我认为您应该从在这里搜索类似的主题开始,然后尝试使它们适应您的问题。当您有一些代码时,我们很乐意为您提供帮助:)
  • 我搜索了代码,但它没有执行和实现但它不起作用。然后我需要复制并插入特定范围的单元格以向下移动我试过但只有整行被向下移动。我写的上面的代码是 excel,它提供了一个选项来从我复制的那个过程中记录宏
  • 编辑您的问题并将代码放入其中。您将通过一些代码获得更多反馈

标签: c# .net excel vba


【解决方案1】:

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

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 互操作编码中小心使用 2 个点。否则,好的答案显示 OP 编程模型(Interop vs VBA)除了 sqr 括号和行终止符之外完全相同。
  • 感谢您提供此代码 m 仍然面临一些问题 Excel.Range source = workSheet.Range["A9:L9"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);在这一行中,m 出现错误,即无法将 bool 转换为 Microsoft.office.Interop.Excel.Range
【解决方案2】:

下面的代码在 Excel 工作簿之间执行复制粘贴,并且我可以根据您的需要提供三种方法。第 1 - 从工作表上的所有行和列复制数据,第 2 - 仅将数据复制到 B 列(2 列),无论其他列中是否有更多数据,第 3 - 类似于 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;
    }
}
}

【讨论】:

    【解决方案3】:
    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;
    

    【讨论】:

      【解决方案4】:

      使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多