2017-05-09 65 views
2

我的Excel工作表,如下(只是一個例子)如何創建Excel行並將其插入Excel範圍?

enter image description here

我已經創建了一個Microsoft.Office.Interop.Excel.Range對象參照來自Item1到類別5的範圍內(上述圖像中選擇細胞)。

現在我想要創建一個新的行(Market1,Market2,Market3,Market4,Market5)並將其添加到範圍下方,即,在Category行下方。我使用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

喜歡的東西

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

你可能要往下走另一行,或使用xlUp。我實際上沒有嘗試過。

+0

謝謝你reasra :) 該解決方案適用於在範圍的末尾插入空行,但我想創建一個新行並將其添加到範圍的末尾。 – manjuv

+0

也許'範圍nextRow = workSheet.Cells [lastRow.Row + 1,1] .EntireRow'然後'nextRow.Insert' ...但是,我不認爲'xlUp'工作正常。 – reasra