I am trying to use Openpyxl to search for data in one Excel workbook, and write it to another (pre-existing) Excel workbook. The aim is something like this:
My code below appears to run without any errors, however, when I open Workbook 2, no data is being written in to it. Does anyone know why/can suggest a fix?
# 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()
Other info:
After quick observation, these lines
c = ws1.cell(row=cell.row, column=4).value
ws2.cell(row=2, column=2).value = c.value
As I read it you want the data from Column E that would be 'column=5' And as the variable c is just an int when you then reference it on the next line it's just '... = c' not c.value. Int has no attribute called 'value' Finally each loop overwrites c in the same cell for the second workbook so you'd only get the last value found. You need to sum the values of c, '+=' as you loop and then write the final sum. You can do that outside the loop along with the write to the excel book, though it will also work updating the cell each iteration. Also C3 would be row and col 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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.