你能看一下下面的案例并帮助我更新Excel吗?
我想先在 A 列中找到今天的日期,然后在 B 列中更新当前时间。
目前我已经尝试过 Openpyxl 并编写了下面的代码,但没有成功。 请帮忙
import os
os.chdir('C:\\New folder')
import openpyxl, datetime, time
wb = openpyxl.load_workbook('Sandeep1.xlsx')
ws = wb.get_sheet_by_name('A1')
for cell in ws['A']:
if cell.value == datetime.datetime.now().strftime('%Y-%m-%d')
update ws['B'] = datetime.datetime.now().strftime('%H:%M:%S')
我重写了你的代码,使其可以工作并且还包含一些注释。
import openpyxl, datetime, time
filename = "TestWorkBook.xlsx"
wb = openpyxl.load_workbook(filename) #Opening up the Workbook
ws = wb["SheetContainingDates"] #Selecting the sheet to work against
ds = datetime.datetime.now().strftime('%Y-%m-%d') #Todays date
ts = datetime.datetime.now().strftime('%H:%M:%S') #Timestamp from "now"
for cell in ws["A"]: #Loops through all set values in Column A
if str(ds) in str(cell.value): #Checks if the string-format of ds is in the string-format of cell.value
ws["B%s" % cell.row] = ts #Sets the neighboring cell to the Timestamp
wb.save(filename) #Saves the workbook after it's done with all the cells.
如果您想在所有可用工作表上执行代码,无需将
sheetname
硬编码到脚本中,只需创建一个循环来遍历所有可用工作表即可:
import openpyxl, datetime, time
filename = "TestWorkBook.xlsx"
wb = openpyxl.load_workbook(filename) #Opening up the Workbook
ds = datetime.datetime.now().strftime('%Y-%m-%d') #Todays date
ts = datetime.datetime.now().strftime('%H:%M:%S') #Timestamp from "now"
for sheet in wb.worksheets: #Loops through all the sheets of the Workbook.
for cell in sheet["A"]: #Loops through all set values in Column A
if str(ds) in str(cell.value): #Checks if the string-format of ds is in the string-format of cell.value
sheet["B%s" % cell.row] = ts #Sets the neighboring cell to the Timestamp
wb.save(filename) #Saves the workbook after it's done with all the cells.