![](/img/trans.png)
[英]Using Python & openpyxl to copy 1 specific row from one excel spreadsheet to another
[英]Openpyxl: Code fails to write data from one Excel spreadsheet to another
我正在嘗試使用 Openpyxl 在一個 Excel 工作簿中搜索數據,並將其寫入另一個(預先存在的)Excel 工作簿。 目標是這樣的:
我下面的代碼似乎運行沒有任何錯誤,但是,當我打開 Workbook 2 時,沒有數據被寫入其中。 有誰知道為什么/可以建議修復?
# importing openpyxl module
import openpyxl as xl
import sys
# opening the source excel file
filename ="C:\\Users\\hadam\\Documents\\Testing\\TB1.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# opening the destination excel file
filename1 = "C:\\Users\\hadam\\Documents\\Testing\\comp2.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.worksheets[1]
for sheet in wb1.worksheets:
for row in sheet.iter_rows():
for cell in row:
try:
if 'Sale' in cell.value:
# reading cell value from source excel file
c = ws1.cell(row=cell.row, column=4).value
# writing the read value to destination excel file
ws2.cell(row=2, column=2).value = c.value
except (AttributeError, TypeError):
continue
# saving the destination excel file
wb2.save(str(filename1))
sys.exit()
其他信息:
經過快速觀察,這些線條
c = ws1.cell(row=cell.row, column=4).value
ws2.cell(row=2, column=2).value = c.value
當我讀到它時,您想要來自 E 列的數據,即 'column=5' 並且由於變量 c 只是一個 int,當您在下一行引用它時,它只是 '... = c' 而不是 c.value . Int 沒有名為“值”的屬性最后每個循環都會覆蓋第二個工作簿的同一單元格中的 c,因此您只會獲得找到的最后一個值。 您需要在循環時對 c, '+=' 的值求和,然后寫出最終的總和。 您可以在循環之外執行此操作以及寫入 excel 書,盡管它也可以在每次迭代時更新單元格。 C3 也是第 3 行和第 3 列。
c = 0
for sheet in wb1.worksheets:
for row in sheet.iter_rows():
for cell in row:
try:
if 'Sale' in cell.value:
# reading cell value from source excel file
c += ws1.cell(row=cell.row, column=5).value
except (AttributeError, TypeError):
continue
# writing the read value to destination excel file
ws2.cell(row=3, column=3).value = c
# saving the destination excel file
wb2.save(str(filename1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.