我有一个有点大的 .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 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:
(没有错误)
这个问题 https://stackoverflow.com/questions/45220078/attributeerror-with-openpyxl询问 AttritubeError 但解决方案是删除只读模式,这对我不起作用,因为 openpyxl 在非只读模式下不会读取我的整个工作簿。
那么:如何迭代大型工作簿中的列?
我还没有遇到过这种情况,但一旦我可以迭代这些列,我就会遇到这种情况:如果所述工作簿很大,我如何读取和写入同一工作簿?
Thanks!