openpyxl: a better way to read a range of numbers to an array
<p>I am looking for a better (more readable / less hacked together) way of reading a range of cells using <code>openpyxl</code>. What I have at the moment works, but involves composing the excel cell range (e.g. <code>A1:C3</code>) by assembling bits of the string, which feels a bit rough.</p>

<p>At the moment this is how I read <code>nCols</code> columns and <code>nRows</code> rows starting from a particular cell (minimum working example, assumes that <code>worksheet.xlsx</code> is in working directory, and has the cell references written in cells <code>A1</code> to <code>C3</code> in <code>Sheet1</code>:</p>

<pre><code>from openpyxl import load_workbook
import numpy as np

firstCol = "B"
firstRow = 2

nCols = 2
nRows = 2

lastCol = chr(ord(firstCol) + nCols - 1) 

cellRange = firstCol + str(firstRow) + ":" + lastCol + str(firstRow + nRows - 1)

wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)
data = np.array([[i.value for i in j] for j in wb[wsName][cellRange]])
print(data)
</code></pre>

<p>Returns:</p>

<pre><code>[[u'B2' u'C2']
 [u'B3' u'C3']]
</code></pre>

<p>As well as being a bit ugly there are functional limitations with this approach. For example in sheets with more than 26 columns it will fail for columns like <code>AA</code>.</p>

<p>Is there a better/correct way to read <code>nRows</code> and <code>nCols</code> from a given top-left corner using openpyxl?</p>

<p>For completeness (and so I can find it later) the equivalent code using the <code>pandas</code> function <code>read_excel</code> suggested by @Rob in a comment would be:</p>

<pre><code>import pandas
import numpy as np
wsName = "Sheet1"
df = pandas.read_excel(open("worksheet.xlsx", "rb"), sheetname=wsName, header=None)

firstRow = 2
firstCol = 2
nCols = 2
nRows = 2

# Data-frame is zero-indexed

data = np.array(df.ix[(firstRow-1):(firstRow-2+nRows), (firstRow-1):(firstRow-2+nRows)])
print(data)
</code></pre>

<p>Which returns:</p>

<pre><code>[[u'B2' u'C2']
 [u'B3' u'C3']]
</code></pre>

python numpy openpyxl