import os
import datetime
import xlwings as xw
from google.cloud import bigquery
def update_excel_with_availability(file_name, day):
# Set the environment variable
os.environ[‘GOOGLE_APPLICATION_CREDENTIALS’] = ‘C:/Users/OneDrive/Dynamisk anmelding-Python utvikling/bq_python_key.json’
# Connect to BigQuery
client = bigquery.Client()
# Calculate the target date for the availability data
target_date = datetime.date.today() + datetime.timedelta(days=day)
# Run the BigQuery query to fetch the availability data for the target date
query = f"""
WITH last_data AS (
SELECT
DataId,
Value,
ReceivedTime,
Timestamp,
ROW_NUMBER() OVER (PARTITION BY DataId ORDER BY ReceivedTime DESC) AS rn
FROM
`cluster.ol.mod_int_raw`
WHERE
DataId IN ('max_pellets', 'max_oil', 'max_vpa', 'max_biodiesel', 'max_avfall', 'max_biooil', 'max_reg', 'max_eboilers', 'max_vp', 'max_lng', 'max_navfall')
AND DATE(Timestamp) = DATE('{target_date.strftime('%Y-%m-%d')}')
)
SELECT
DataId,
timestamp,
Value,
ReceivedTime,
FROM
last_data
WHERE
rn = 1
"""
# Execute the BigQuery query
query_job = client.query(query)
# Extract the availability values from the query result
availability_data = {}
for row in query_job:
data_id = row['DataId']
value = row['Value']
availability_data[data_id] = value
# Load the existing Excel file
app = xw.App(visible=False)
try:
workbook = app.books.open(file_name)
except Exception as e:
app.quit()
raise ValueError(f"Error opening workbook {file_name}: {e}")
try:
# Select the appropriate sheet in the Excel file
try:
sheet = workbook.sheets['Input']
except Exception as e:
raise ValueError(f"Error accessing sheet 'Input': {e}")
try:
# Get the column index for each DataId in the Excel file
column_mapping = {
'max_pellets': 15,
'max_oil': 19,
'max_vpa': 11,
'max_biodiesel': 18,
'max_avfall': 10,
'max_biooil': 17,
'max_reg': 9,
'max_eboilers': 14,
'max_vp': 13,
'max_lng': 16,
'max_navfall': 12
}
# Iterate over the hours of the day (24 hours)
for hour in range(24):
# Update the availability value for each DataId in the corresponding hour column
for data_id, column_index in column_mapping.items():
# Get the availability value for the current DataId
availability_value = availability_data.get(data_id)
# Calculate the row index for the current hour
row_index = hour + 2 # Assuming the data starts from row 2
# Update the cell with the availability value
try:
cell = sheet.range((row_index, column_index))
if cell is None:
raise ValueError(f"Unable to access cell at row {row_index}, column {column_index}")
cell.value = availability_value
# Format the cell number format to general
cell.number_format = '0'
except Exception as e:
raise ValueError(f"Error accessing cell at row {row_index}, column {column_index}: {e}")
# Save the modified Excel file
workbook.save()
print(f"Kjel-tilgjengelighet in {file_name} has been updated for day {day}!")
except Exception as e:
print(f"Error occurred during update: {str(e)}")
finally:
if 'workbook' in locals():
workbook.close()
app.quit()
filename = “PythonAnmeldingInput.xlsx”
update_excel_with_availability(filename, 2)
I am trying to import data from google big query and update an excel file. And this code is working 50 percent of the time. It gives an error unable to acess cell at one row. Running the code multiple times works. but i am trying to find why is it not working all the time. This is where it is failing cell = sheet.range((row_index, column_index))
if cell is None:
raise ValueError(f”Unable to access cell at row {row_index}, column