Cut and Paste Columns in Excel Range with c#

后端 未结 1 1361
深忆病人
深忆病人 2020-12-18 04:38

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. I have experience in VBA but relatively little in c# so I\'ve spent

相关标签:
1条回答
  • 2020-12-18 05:29

    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.

    Reference docs:

    • http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.insert.aspx
    • http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlinsertshiftdirection.aspx
    • http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.cut.aspx

    Here is a sample app (be sure to add a reference to 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());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题