简体   繁体   中英

Extending Excel WorkSheet Range

I need to create a Excel file by C# code.

I am doing it the way that was recommended by microsoft/msdn https://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx

At the msdn example, the cells range is fixed:

// Select the Excel cells, in the range c1 to c7 in the worksheet.
Range aRange = ws.get_Range("C1", "C7");

if (aRange == null)
{
    Console.WriteLine("Could not get a range. Check to be sure you have the correct versions of the office DLLs.");
}

// Fill the cells in the C1 to C7 range of the worksheet with the number 6.
Object[] args = new Object[1];
args[0] = 6;
aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

But in my function that i am writing

public void Create ExcelFile(List<string> strList);

i need to increase the number of rows to the number of the objects that i get in the List function parameter.

How to do it?

thanks.

Since you are using an object of type List (as per your requirement), you can keep the start range constant, ie, in this case "C1" and end range can be the count of your string values in the Collections List.

Inside your method CreateExcelFile which has List<string> strList as input, get an endRange as below and you can utilize the same when you get the Range.

string endRange = string.Concat("C", strList.Count.ToString());
Range aRange = ws.get_Range("C1", endRange);

I hope this solves your issue.

I found the answer.

This is my code:

int i = 1;
foreach (ItemDetailsPrice item in strList)
{
    //xlWorkSheet.Cells[i, 0] = new Cell("Code");
    aRange = (Excel.Range)xlWorkSheet.Cells[i, 1];
    args[0] = plant;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 2];
    args[0] = item.ItemCode;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 3];
    args[0] = item.ItemName;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 4];
    args[0] = item.ItemPrice;
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    aRange = (Excel.Range)xlWorkSheet.Cells[i, 5];
    args[0] = "Y";
    aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

    i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM