![](/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.