python - 遍历 openpyxl 中只读工作簿中的列

标签 python excel openpyxl

我有一个有点大的 .xlsx 文件 - 19 列,5185 行。我想打开文件,读取一列中的所有值,对这些值执行一些操作,然后在同一工作簿中创建一个新列并写出修改后的值。因此,我需要能够在同一个文件中读取和写入。

我的原始代码是这样做的:

def readExcel(doc):
    wb = load_workbook(generalpath + exppath + doc)
    ws = wb["Sheet1"]

    # iterate through the columns to find the correct one
    for col in ws.iter_cols(min_row=1, max_row=1):
        for mycell in col:
            if mycell.value == "PerceivedSound.RESP":
                origCol = mycell.column

    # get the column letter for the first empty column to output the new values
    newCol = utils.get_column_letter(ws.max_column+1)

    # iterate through the rows to get the value from the original column,
    # do something to that value, and output it in the new column
    for myrow in range(2, ws.max_row+1):
        myrow = str(myrow)
        # do some stuff to make the new value
        cleanedResp = doStuff(ws[origCol + myrow].value)
        ws[newCol + myrow] = cleanedResp

    wb.save(doc)

但是,由于工作簿太大,python 在第 3853 行之后抛出了内存错误。 openpyxl 文档说使用只读模式 ( https://openpyxl.readthedocs.io/en/latest/optimized.html ) 来处理大工作簿。我现在正在尝试使用它;但是,当我添加 read_only = True 参数时,似乎无法遍历列:

def readExcel(doc):
    wb = load_workbook(generalpath + exppath + doc, read_only=True)
    ws = wb["Sheet1"]

    for col in ws.iter_cols(min_row=1, max_row=1):
        #etc.

python 抛出这个错误: AttributeError: 'ReadOnlyWorksheet' 对象没有属性 'iter_cols'

如果我将上面代码段的最后一行更改为:

for col in ws.columns:

python 抛出同样的错误: AttributeError: 'ReadOnlyWorksheet' 对象没有属性 'columns'

迭代行很好(并且包含在我上面链接的文档中):

for col in ws.rows:

(没有错误)

This question询问 AttritubeError 但解决方案是删除只读模式,这对我不起作用,因为 openpyxl 不会在非只读模式下读取我的整个工作簿。

那么:如何循环访问大型工作簿中的列?

我还没有遇到过这种情况,但一旦我可以遍历这些列,我就会遇到:如果所述工作簿很大,我如何读写同一个工作簿?

谢谢!

最佳答案

如果工作表只有大约 100,000 个单元格,那么您应该没有任何内存问题。您可能应该进一步调查这一点。

iter_cols() 在只读模式下不可用,因为它需要对底层 XML 文件进行持续且非常低效的重新解析。但是,使用 zipiter_rows() 将行转换为列相对容易。

def _iter_cols(self, min_col=None, max_col=None, min_row=None,
               max_row=None, values_only=False):
    yield from zip(*self.iter_rows(
        min_row=min_row, max_row=max_row,
        min_col=min_col, max_col=max_col, values_only=values_only))

import types
for sheet in workbook:
    sheet.iter_cols = types.MethodType(_iter_cols, sheet)

关于python - 遍历 openpyxl 中只读工作簿中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47582274/

相关文章:

python - Django错误 'RawQuerySet'对象没有属性 'all'

python - groupby apply 没有给出预期结果

.net - 数据库中的 Excel 自动化,最好的技术是什么?

python - 将 Excel 文件流保存到 azure blob 存储

python - 在python中使用lxml添加xml前缀声明

python - 正则表达式查找不起作用的空格

excel - 如何查找具有特定字符的文件名

excel - 如何在Excel中将两种不同的日期格式更改为单一日期格式

python - xlwings 与 openpyxl 阅读 Excel 工作簿的区别

python - 使用 openpyxl 编辑电子表格。无法写入单元格, "cell is read-only error"