在现有Excel工作表的开头插入单元格区域?

时间:2017-11-20 17:20:55

标签: c# excel vsto

我有一个包含5行3列的工作表。我复制了这张表:

activeSheet.Copy(Type.Missing, activeSheet);

var outputSheetIndex = activeSheet.Index + 1;

var outputSheet = (Worksheet)application.Sheets[outputSheetIndex];

上面将纸张复制到另一张纸上。我现在想在outputSheet中插入另一个范围,并将outputSheet列移到右边。

我不确定应用Insert方法的范围对象。

我尝试在开头创建一个要插入的新范围,但这不起作用:

 var startCell = outputSheet.Cells[1, 1];
                    var endCell = outputSheet.Cells[output.Count(),
                        properties.Length + 1];

              var writeRange = outputSheet.Range[startCell, endCell];

writeRange.Insert(XlInsertShiftDirection.xlShiftToRight);

当我插入writeRange时,我希望现有的数据范围向右移动。

2 个答案:

答案 0 :(得分:0)

如果我理解,你想要将OutputSheet中的所有数据推到右边,在左边留下一列。例如:

如果是这样的话:

  • |一个|一个|一个|一个
  • |两个|两个|两个|两个

你想要这样,对吧? :

  • | “null”|一个|一个|一个|一个
  • | “null”|两个|两个|两个|两个

然后做:

outputSheet.Columns[1].Insert(); //creates empty column and pushes the actual data to the right

如果你想从inputSheet(原始工作表)插入一个范围到输出中,只需执行:

Excel.Range inputRange = ((Excel.Range)inputSheet.Cells[1, 4].EntireColumn; //Let's say you want to pass the 4th column (forget the 1, it doesn't do anything because you get the Entire Column, so it ignores the x-axis which are the Rows)
Excel.Range outputRange = ((Excel.Range)outputSheet.Cells[1, 1].EntireColumn; //into the first Column of the outputSheet
outputRange.Value = inputRange.Value;

如果出现意外情况(如单元格合并),只需获取特定的行或列并将其删除:

outputSheet.Columns[2].Delete();

答案 1 :(得分:0)

如果您只想在新的(复制的工作表)上插入空白列,我认为这样可行:

outputSheet.Range["A:A"].Insert(
    Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
    Type.Missing);

如果您希望该列位于其他位置,您可以更改" A:A"到你想要的范围。

相关问题