Tom
Tom

Reputation: 21

Writing a value to a cell (in excel workbook) using python

I'd like to automate a report consisting of many different data sources.

Instead of going into the interfaces and manually copying and pasting data into the report, I've used the API to pull the data.

Since the script will run daily to pull yesterday's numbers, I'd like to write the figures (for example, spend or clicks for yesterday) to specific cells in an excel workbook, which the original report will look up to get yesterdays figures.

The below code gives me the figures I need when printing totalcost:

for campaign in allCampaigns:
costamount = float(campaign["total"]["localSpend"]["amount"])
allCost.append(costamount)
totalcost = sum(allCost)
print(totalcost)

So i'd like to write (totalcost) to a specific cell in a workbook.

Thanks!

Upvotes: 0

Views: 1352

Answers (1)

Henrique Branco
Henrique Branco

Reputation: 1940

This is my suggestion:

import openpyxl

wb = openpyxl.load_workbook("path_to_your_file.xlsx")
ws = wb['your_sheet_name']
ws.cell(row = 1, col = 1, value = totalcost) # Writes the content of totalcost in A1
wb.save()

Just replace the path to your file, the sheet name of your workbook and the current position you want to insert the value.

Upvotes: 1

Related Questions