Created
January 16, 2023 09:38
-
-
Save huzefamehidpurwala/dc3dfb4a0ac3b4ee8dd6277a350a459f to your computer and use it in GitHub Desktop.
Create and append data to a xlsx file using openpyxl module.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import sleep | |
import openpyxl | |
from datetime import datetime | |
print("Welcome!\nWe are working...!") | |
# Get the current date and time | |
now = datetime.now() | |
worksheet_title = now.strftime("%Y-%m-%d") # for time %H-%M-%S | |
try: | |
# Open the existing workbook | |
wb = openpyxl.load_workbook("data.xlsx") | |
# check the active sheet is of the same name | |
# ws = wb.get_sheet_by_name(worksheet_title) | |
ws = wb[worksheet_title] | |
except KeyError: | |
wb = openpyxl.load_workbook("data.xlsx") | |
# create the new sheet if the sheet doesn't exist of the same name | |
ws = wb.create_sheet(title=worksheet_title) | |
# Add a header row to the new worksheet | |
ws.append(["Column 1", "Column 2", "Column 3", "Column 4", "Column 5"]) | |
except FileNotFoundError: | |
print("Creating the new file...") | |
# Create a new Excel workbook | |
wb = openpyxl.Workbook() | |
# getting the active worksheet | |
ws = wb.active | |
# renaming the active worksheet | |
if ws.title == "Sheet": | |
ws.title = worksheet_title | |
# Add a header row to the new worksheet | |
ws.append(["Column 1", "Column 2", "Column 3", "Column 4", "Column 5"]) | |
# Create a list of 20 tuples, each containing 5 objects of different data types | |
data = [("string", 1, 3.14, True, now.strftime("%H:%M:%S")), | |
("another string", 2, 2.718, False, now.strftime("%H:%M:%S")), | |
("yet another string", 3, 1.618, True, now.strftime("%H:%M:%S")), | |
("string", 4, 1.618, True, now.strftime("%H:%M:%S")) | |
# and so on... | |
] | |
# Append each tuple to the new worksheet in intervals of 1 minute | |
for i, tup in enumerate(data): | |
ws.append(tup) | |
if i != len(data) - 1: | |
sleep(60) | |
try: | |
wb.save("data.xlsx") | |
except PermissionError: | |
print("Cannot save the file") | |
else: | |
print("Work is done!\nThank you!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment