简体   繁体   中英

Writing to a specific cell in excel under specific conditions in python

I am quite new to python but not to programming per se.

I am currently trying to solve a problem where i want to write to a specific cell in an already existing excel worksheet on specific conditions.

This is the structure of my worksheet: excel worksheet

What i am trying to do is get the current date and time like this:

current_date = date.today().strftime("%d.%m.%Y")
current_time = datetime.now().strftime("%H:%M")

Now for example if today is the 02.03.2021 and it is currently 09:09 i want to write to cell C4.

I have tried googling and i am starting to believe that this is not possible but maybe some of you guys have any ideas.

Thank you so much in advance.

I would suggest to read the excel file in pandas data frame. Than write in whatever cell you want like df.at[row, col] = some_value . And than you could write it back to excel https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html

Of course it is possible, everything is. Here is a sample code to achieve what you want:

import pandas as pd
import numpy as np
from datetime import datetime

# Create a test dataframe, normally you want to import it from a file using the read_excel method
df = pd.DataFrame([['11:00', np.nan, np.nan, np.nan],
                   ['12:00', np.nan, np.nan, np.nan],
                   ['13:00', np.nan, np.nan, np.nan],
                   ['14:00', np.nan, np.nan, np.nan],
                   ['15:00', np.nan, np.nan, np.nan]],
                  columns=['Time', '04.04.2021', '05.04.2021', '06.04.2021'])

# Get the current date and time, make sure they are in the same format as in your excel worksheet
current_date = datetime.now().strftime("%d.%m.%Y")
current_time = datetime.now().strftime("%H:00") # we only want the hour in 24-hour format

# Use the 'at' method to access a single value for a row/column label pair and write your value
df.at[df['Time'] == current_time, current_date] = 'some custom value'

df.to_csv('test.csv', index=False)

I run the script at 5/4/2021, 14:20 local time and got the following output: 在此处输入图像描述

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