![](/img/trans.png)
[英]How can I copy Excel rows, filtering for a value, with Python and openpyxl?
[英]how can I iterate specific rows of excel worksheet if I have row numbers using openpyxl?
我是編程新手,目前正在學習 python 和 openpyxl 以進行 excel 文件操作。 我正在編寫一個腳本來幫助更新修復數據庫,該數據庫在 excel 表中選擇特定記錄。 我編寫了一個腳本,可以在其中獲取需要更新的 excel 數據的行號,但現在的挑戰是如何通過迭代在行(記錄)的列表中創建列表。
例如,我發現我需要來自第 22、23、34 和 35 行的數據。有沒有一種方法可以獲取這些行的數據,而無需更改每個行實例的 min_row 和 max_row 數?
我需要重寫的代碼部分是:
# copy the record on the rows of the row numbers found above.
rows_records = []
row_record = []
for row_cells in ws2.iter_rows(min_row=23, max_row=23, min_col=1, max_col = 6):
for cell in row_cells:
row_record.append(cell.value)
rows_records.append(row_record)
print(row_record)
print(rows_records)
import openpyxl
book = openpyxl.load_workbook('numbers.xlsx')
sheet = book.active
rows = sheet.rows
values = []
your_row_indices = [21,22,23]
for row in rows[your_row_indices]:
for cell in row:
values.append(cell.value)
由於 openpyxl 返回一個生成器,因此您必須將其轉換為列表才能特別訪問索引
import openpyxl
workbook = openpyxl.load_workbook('numbers.xlsx')
worksheet = workbook .active
rows = list(worksheet.iter_rows(max_col=6, values_only=True))
values = []
row_indices = [21, 22, 23, 34, 35]
for row_index in row_indices:
values.append(rows[row_index])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.