Toufic Diab
Toufic Diab

Reputation: 1

Convert Interop to ClosedXML

I have 3 lines of C# Interop code that I am struggling to convert to ClosedXML. Can anyone please help?

str2 = worksheet.Range("B3", "L13").get_End(XlDirection.xlDown).get_Address(false, false, XlReferenceStyle.xlA1, System.Type.Missing, System.Type.Missing).Replace("B", "L");
object[,] objArray = (object[,]) worksheet.Range("B3", str2).Value;
str3 = worksheet.Range("B3", "L13").get_End(XlDirection.xlDown).get_Address(false, false, XlReferenceStyle.xlA1, System.Type.Missing, System.Type.Missing).Replace("B", "L");

Thanks

Upvotes: 0

Views: 422

Answers (1)

Aleksei
Aleksei

Reputation: 591

As answered here

This snipped looks overly complicated. First, you create a range from B3 to L13, then move down to the last row (getting to B13, apparently), then replace B to L which gives you L13 and finally you create a range B3:L13 once more to get the values from there.

ClosedXML does not have a built-in method to convert a range into a two-dimensional array but this can be easily done manually:

var range = worksheet.Range("B3:L13");
var objArray = new object[range.ColumnCount(), range.RowCount()];
for (int i = 0; i < range.ColumnCount(); i++)
{
    for (int j = 0; j < range.RowCount(); j++)
    {
        objArray[i, j] = range.Cell(j+1, i+1).Value;
    }
}

Upvotes: 1

Related Questions