如何创buildExcel行并将其插入Excel范围?

我有一个如下所示的Excel工作表(只是一个例子)

在这里输入图像说明

我创build了一个Microsoft.Office.Interop.Excel.Range对象,引用从Item1到Category5(上图中选定单元格)的范围。

现在我想要创build一个新的行(Market1,Market2,Market3,Market4,Market5),并将其添加到范围下方,即在Category行下方。

我第一次使用Microsoft.Office.Interop.Excel类。 有人可以帮助我弄清楚如何创build添加一个新的行到现有的范围对象。

这是我写的代码 –

 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; } } 

就像是

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

你可能不得不再下一行,或者使用xlUp 。 我没有真的尝试过这个。