简体   繁体   English

使用c#在Excel范围中剪切和粘贴列

[英]Cut and Paste Columns in Excel Range with c#

I'm trying to move column B in front of column Q in an excel sheet as part of a report I'm working on. 我正在尝试将excel表中列Q前面的列B移动,作为我正在处理的报告的一部分。 I have experience in VBA but relatively little in c# so I've spent the last hour on Google and can't find a solution, I feel like this should be simple but I can't quite get it. 我有VBA的经验,但在c#中相对较少,所以我花了最后一小时在谷歌上找不到解决方案,我觉得这应该很简单,但我不能完全理解。

Method one, which results in a “Insert method of Range class failed” msg. 方法一,导致“Range类的插入方法失败”msg。

Excel.Range rngCut1 = JobLabourSheet.get_Range("B:B", Type.Missing);
Excel.Range rngPaste1 = JobLabourSheet.get_Range("Q:Q", Type.Missing);
            rngCut1.Columns.Cut(rngPaste1.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, rngCut1));

Method two results in a “Unable to get a Cut property of the Range class” msg. 方法二导致“无法获取Range类的Cut属性”msg。

Excel.Range rngCut1 = JobLabourSheet.get_Range("B:B", Type.Missing);
Excel.Range rngPaste1 = JobLabourSheet.get_Range("Q:Q", Type.Missing);
            rngCut1.Columns.Cut(rngPaste1.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, Missing.Value));

In the second method when I omit the CopyOrigin I get the msg but it does insert a blank column in front of column Q. 在第二种方法中,当我省略CopyOrigin时,我得到了msg,但它确实在列Q前插入了一个空白列。

In VBA I would use the following: 在VBA中,我将使用以下内容:

Columns("B:B").Cut
Columns("Q:Q").Insert Shift:=xlToRight

But like I said, my c# experience is limited at the moment so I have no idea how to go about translating it to c# 但就像我说的那样,我的c#体验目前是有限的,所以我不知道如何将它翻译成c#

This isn't very intuitive, but this is how I got it to work. 这不是很直观,但这就是我开始工作的方式。 I took an "insert" range and used the Insert() method and passed a "range.Cut()" method as the "Copy Origin" parameter. 我采用了“插入”范围并使用了Insert()方法并将“range.Cut()”方法作为“复制原点”参数传递。

Reference docs: 参考文档:

Here is a sample app (be sure to add a reference to Microsoft.Office.Interop.Excel): 这是一个示例应用程序(请务必添加对Microsoft.Office.Interop.Excel的引用):

using System;
using System.Collections.Generic;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelCutAndInsertColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWb = xlApp.Workbooks.Open(@"C:\stackoverflow.xlsx");
            Excel.Worksheet xlWs = (Excel.Worksheet)xlWb.Sheets[1]; // Sheet1

            xlApp.Visible = true;

            // cut column B and insert into A, shifting columns right
            Excel.Range copyRange = xlWs.Range["B:B"];
            Excel.Range insertRange = xlWs.Range["A:A"];

            insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, copyRange.Cut());
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM