2017-05-09 8 views
2

Iは以下のようにExcelワークシート(一例)Excelの行を作成してExcelの範囲に挿入する方法は?

enter image description here

を持って私はアイテム1からCategory5の範囲(上記画像における選択されたセル)を参照Microsoft.Office.Interop.Excel.Rangeオブジェクトを作成しました。

今、新しい行(Market1、Market2、Market3、Market4、Market5)を作成し、カテゴリ行の下の範囲ieの下に追加します。

私は初めてMicrosoft.Office.Interop.Excelクラスを使用しています。 誰かがを作成する方法を理解するのに助けてくれますか?は、既存の範囲オブジェクトに新しい行を追加します。

public class Class1 
{ 
    static void Main(string[] args) 
    { 
     Application appExcel = new Application(); 


     WorkBook workBook = appExcel.Workbooks.Open(@"C:\Data.xlsx", true, false); 
     workSheet = (Worksheet)workBook.Sheets["Export"]; 

     Range usedRange = workSheet.UsedRange; 

     Range itemCatRange = GetSection(usedRange, "Item1","Group1"); //Gets the selected range as shown in pic 

     //Here I want to create a new row of cells and add the newly created row at the end of the above range "itemCatRange" 
    } 

    private static Range GetSection(Range usedRange, string startHeader, string endHeader) 
    { 
     string str = string.Empty; 
     string end = String.Empty; 

     Range algAlmRange; 
     foreach (Range row in usedRange.Rows) 
     { 

      object firstColumnValue = row.Columns.Value2[1, 1]; 
      if (firstColumnValue != null) 
      { 
       if (firstColumnValue.ToString() == startHeader) 
       { 
        str = row.Address; 
       } 
       else if (firstColumnValue.ToString() == endHeader) 
       { 
        end = row.Address; 
       } 

      } 
     } 

     algAlmRange = workSheet.Range[str, end]; 
     return algAlmRange; 
    } 
} 
+0

[Excel Interop - 行単位でデータを挿入して追加する](http://stackoverflow.com/questions/30495407/excel-interop-insert-add-data-by-row)、[Excel挿入行数](http://stackoverflow.com/questions/13418776/excel-insert-rows-not-add) – FortyTwo

+0

何か試しましたか?あなたのコードを共有してください – FortyTwo

+0

ありがとうございました。私はポストにコードを追加しました。 – manjuv

答えて

1

あなたが別の行を下に行かなければならない、またはxlUpを使用することができ

Range itemCatRange = GetSection(usedRange, "Item1","Group1"); 
Range lastRow = itemCatRange[itemCatRange.Rows, 1].EntireRow; 
lastRow.Insert(XlDirection.xlDown, XlInsertFormatOrigin.xlFormatFromLeftOrAbove); 

ような何か - ここ

は、私が書いたコードです。私は実際にこれを試していない。

+0

ありがとうReasra :) このソリューションは、範囲の最後に空の行を挿入するために機能しますが、新しい行を作成し、範囲の最後に追加したいです。 – manjuv

+0

多分 'Range nextRow = workSheet.Cells [lastRow.Row + 1、1] .EntireRow'そして' nextRow.Insert' ...しかし、確かに、私は 'xlUp'が正しく動作しているとは思わない。 – reasra

関連する問題