我的Excel工作表,如下(只是一個例子)如何創建Excel行並將其插入Excel範圍?
我已經創建了一個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;
}
}
這些可能有所幫助:[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
你嘗試過什麼嗎?請分享您的代碼 – FortyTwo
謝謝你的迴應。我已將代碼添加到帖子中。 – manjuv