gpt4 book ai didi

c# - 如何创建 Excel 行并将其插入 Excel 范围?

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:05 25 4
gpt4 key购买 nike

我有一个 excel 工作表如下(只是一个例子)

enter image description here

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

现在我想创建一个新行(市场 1、市场 2、市场 3、市场 4、市场 5)并将其添加到范围下方,即类别行下方。

我是第一次使用 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;
}
}

最佳答案

有点像

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

您可能需要向下移动另一行,或使用 xlUp。我还没有实际尝试过。

关于c# - 如何创建 Excel 行并将其插入 Excel 范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43866510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com