简体   繁体   中英

How to get range in EPPlus

Does anyone know how to execute the following in EPPlus.

The following is the way when using VSTO. I'm trying to get some specific ranges from a worksheet.

sheet.get_Range("7:9,12:12,14:14", Type.Missing)

You can use this

ExcelPackage pck = new ExcelPackage()
var ws = pck.Workbook.Worksheets.Add("Sheet1");
ExcelRange cells = ws.Cells[1, 1, 1, 10];//get 10 cells in row 1 

I am not fully familiar with `get_Range' but based on the documention it works just like the cells object of EPPlus. So this:

[TestMethod]
public void Multi_Range_Test()
{

    //Throw in some data
    var datatable = new DataTable("tblData");
    datatable.Columns.Add(new DataColumn("Col1", typeof(int)));
    datatable.Columns.Add(new DataColumn("Col2", typeof(int)));
    datatable.Columns.Add(new DataColumn("Col3", typeof(int)));

    for (var i = 0; i < 20; i++)
    {
        var row = datatable.NewRow();
        row[0] = i;
        row[1] = i * 10;
        row[2] = i * 100;
        datatable.Rows.Add(row);
    }

    var existingFile2 = new FileInfo(@"c:\temp\temp.xlsx");
    if (existingFile2.Exists)
        existingFile2.Delete();

    using (var package = new ExcelPackage(existingFile2))
    {
        //Add the data
        var sheet = package.Workbook.Worksheets.Add("Sheet1");
        sheet.Cells.LoadFromDataTable(datatable, true);

        var range = sheet.Cells["7:9,12:12,14:14"];
        foreach (var rangeBase in range)
        {
            Console.WriteLine("{{{0} : {1}}}", rangeBase.Address, rangeBase.Value);
        }

        //Save the file
        package.Save();
    }
}

results in this in the output window:

{A7 : 5}
{B7 : 50}
{C7 : 500}
{A8 : 6}
{B8 : 60}
{C8 : 600}
{A9 : 7}
{B9 : 70}
{C9 : 700}
{A12 : 10}
{B12 : 100}
{C12 : 1000}
{A14 : 12}
{B14 : 120}
{C14 : 1200}

AntonE's answer is correct, but I thought I'd point out what each index in the subscript operator signifies:

ExcelWorkSheet.Cells[FromRow, FromCol, ToRow, ToCol]

Hence, ws.Cells[1,1,1,10] means: "Get all cells starting from the first row and first column to the 10th column, but first row".

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