简体   繁体   English

使用 openpyxl 访问 excel 单元格值

[英]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.在我的项目中,每次按下按钮时,时间都会保存在 self.time 变量中,我将其转换为日期时间,然后每次单击将其写入不同列的 Excel 文件中。 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).我还想做的是在 excel 中写入另一个点击所需的实际时间(基本上是已经写入的值减去保存的新时间)。 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.不幸的是,它只是让我返回 00:00:00 作为结果。 How can successufuly access the previous value saved in the row 3 to find the time one need to click?如何成功访问第3行保存的前一个值以找到需要单击的时间? EDIT: could it be possible to have only the time difference?编辑:可能只有时差吗? without having to save str(self.time) ?无需保存 str(self.time) ?

Your code isn't trying to read the value in row 3;您的代码并未尝试读取第 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.它设置第 3 行单元格的值,然后将第 4 行单元格的值设置为第 3 行单元格的值减去自身。 Essentially, the code for row 4 is "datetime(self.time) - datetime(self.time)", which is why you're getting 00:00:00.本质上,第 4 行的代码是“datetime(self.time) - datetime(self.time)”,这就是为什么你得到 00:00:00。

To get the time difference between the last value in the sheet and the current self.time value:要获取工作表中的最后一个值与当前 self.time 值之间的时间差:

  • Store the value of the last_value in a variable将 last_value 的值存储在一个变量中
  • subtract the last_value from self.time and store result in a variable从 self.time 中减去 last_value 并将结果存储在一个变量中
  • 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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