一、是否需要close()?
在使用 openpyxl 時,wb.save() 后一般不需要再手動調用 wb.close()。wb.save() 會自動處理文件寫入和釋放。
如果是使用openpyxl.load_workbook(filename, read_only=True) 打開了一個只讀模式的工作簿,此時會建立文件流,需要在使用完之后調用 wb.close() 來釋放資源。不然的話內存中可能還會保留一個對文件的占用。
二、在操作ws.cell()時,column可以指定字符串嗎,例如‘AK’?
不可以直接使用列字母 'AK' 作為 column 參數,所以這時候需要openpyxl.utils.column_index_from_string() 把 'AK' 轉換成數字列號:
from openpyxl.utils import column_index_from_stringcol_num = column_index_from_string('AK') # AK → 37ws.cell(row=new_row, column=col_num, value='ssss')
反過來,如果有列號,想變成列字母:
from openpyxl.utils import get_column_lettercol_letter = get_column_letter(37) # → 'AK'
三、如何排除第 1 列再找最大行
def get_real_max_row(ws):for row in reversed(range(1, ws.max_row + 1)):# 遍歷該行中除第1列以外的單元格for cell in ws[row][1:]:if cell.value is not None:return rowreturn 0
四、Excel中的行和列的index是從0開始的嗎?
在使用 openpyxl 處理 Excel 的時候,Excel 中的行和列索引是從 1 開始的,例如:
openpyxl.cell(row=1, column=1) 對應的是 Excel 中的單元格 A1
row=1 是第 1 行
column=1 是第 1 列(即 A 列)
column=2 是 B 列,以此類推