gpt4 book ai didi

python - openpyxl:将一系列数字读取到数组的更好方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:34 26 4
gpt4 key购买 nike

我正在寻找一种使用openpyxl读取一系列单元格的更好(更具可读性/更少被组合在一起)的方法。我目前所拥有的可以工作,但涉及通过组装字符串的位来组成 Excel 单元格范围(例如 A1:C3),这感觉有点粗糙。

目前,这就是我从特定单元格开始读取 nCols 列和 nRows 行的方式(最小工作示例,假设 worksheet.xlsx 位于工作目录中,并且在 Sheet1 中的单元格 A1C3 中写入单元格引用:

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)

返回:

[[u'B2' u'C2']
[u'B3' u'C3']]

这种方法除了有点难看之外,还存在功能限制。例如,在超过 26 列的工作表中,对于像 AA 这样的列,它将失败。

是否有更好/正确的方法使用 openpyxl 从给定的左上角读取 nRowsnCols

最佳答案

openpyxl 提供了在数字列索引(基于 1 的索引)和 Excel 的“AA”样式之间进行转换的函数。有关详细信息,请参阅 utils 模块。

但是,一般来说您不需要它们。您可以使用工作表的 get_squared_range() 方法进行编程访问。并且,从 openpyxl 2.4 开始,您可以使用 iter_rows()iter_cols() 方法执行相同的操作。注意。 iter_cols() 在只读模式下不可用。

使用 iter_rows() 的等效 MWE 为:

from openpyxl import load_workbook
import numpy as np
wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)
ws = wb[wsName]

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

allCells = np.array([[cell.value for cell in row] for row in ws.iter_rows()])

# allCells is zero-indexed
data = allCells[(firstRow-1):(firstRow-1+nRows),(firstCol-1):(firstCol-1+nCols)]
print(data)

使用 get_squared_range() 的等效 MWE 为:

from openpyxl import load_workbook
import numpy as np

wsName = "Sheet1"
wb = load_workbook(filename="worksheet.xlsx", data_only=True)

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

data = np.array([[i.value for i in j] for j in wb[wsName].get_squared_range(
firstCol, firstRow, firstCol+nCols-1, firstRow+nRows-1)])
print(data)

两者都返回:

[[u'B2' u'C2']
[u'B3' u'C3']]

另请参阅https://openpyxl.readthedocs.io/en/default/pandas.html有关一起使用 Pandas 和 openpyxl 的更多信息。

关于python - openpyxl:将一系列数字读取到数组的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39968466/

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