简体   繁体   中英

Access excel cells value with openpyxl

In my project everytime a button is pressed the time is saved in self.time variable, I convert it with datetime and then I write it in an excel file in different column for every click. What I'd like to do is also to write in excel the actual time that another click require (basically the value already written less the new time saved). This is mi code:

from openpyxl import load_workbook
from datetime import datetime

self.time.append(self.saved)

fmt = '%H:%M:%S'
current_row = sheet.max_row 
current_column = sheet.max_column 
sheet.cell(row=3, column=current_column + 1).value  = str(self.time) 
sheet.cell(row=4, column=current_column + 1).value  = datetime.strptime(self.time, fmt) - datetime.strptime(sheet.cell(row=3, column=current_column + 1).value, fmt) 

Unfortunly it just gives me back 00:00:00 as results. How can successufuly access the previous value saved in the row 3 to find the time one need to click? EDIT: could it be possible to have only the time difference? without having to save str(self.time) ?

Your code isn't trying to read the value in row 3; its setting the value of the cell in row 3, then setting the value of the cell in row 4 to the value of the cell in row 3 minus itself. Essentially, the code for row 4 is "datetime(self.time) - datetime(self.time)", which is why you're getting 00:00:00.

To get the time difference between the last value in the sheet and the current self.time value:

  • Store the value of the last_value in a variable
  • subtract the last_value from self.time and store result in a variable
  • write that variable to the next row in the sheet
from datetime import datetime
from openpyxl import load_workbook

# load workbook and get the desired sheet
wb = load_workbook('file name')
ws = wb['sheet name']

# represents self.time from your example 
time = "04:12:21"

fmt = "%H:%M:%S"
current_row = ws.max_row
current_column = ws.max_column

# get the last value
last_value = ws.cell(row=current_row, column=current_column).value

# subtract current time from last_value
value_to_insert = datetime.strptime(last_value, fmt) - datetime.strptime(time, fmt)

# write the value to worksheet
ws.cell(row=current_row + 1, column=current_column).value = value_to_insert

wb.save('file name')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM