Heim  >  Artikel  >  Backend-Entwicklung  >  So automatisieren (erstellen, aktualisieren) Sie Excel-Dateien über APIs mit Python und Openpyxl.

So automatisieren (erstellen, aktualisieren) Sie Excel-Dateien über APIs mit Python und Openpyxl.

王林
王林Original
2024-08-16 18:01:40305Durchsuche

How to Automate(create, update) Excel Files from APIs with Python and Openpyxl.

Ich weiß also, dass viele Leute, wenn von Automatisierung die Rede ist, das Ganze höchst abstrakt betrachten. Vielleicht denke ich sogar an eine Werkstatt für Reparaturen. lol.
Wie auch immer, Automatisierung in der Programmierung ist genau der Code, den Sie schreiben, aber mit anderen Techniken, die dabei helfen, ihn richtig auszuführen.

Als ich anfing, Python zu verwenden, diente es dem Schreiben von Datenstrukturen und Algorithmen, aber später nutzte ich es auch für andere Dinge, wie zum Beispiel das Ausprobieren meiner ML-Modellentwicklung und dann Python zum Programmieren.

In diesem Artikel werde ich eine Schritt-für-Schritt-Anleitung bereitstellen, wie ich eine Excel-Datei und verschiedene Blätter auf einem MacBook automatisiert habe, ohne Visual Basic für Anwendungen zu verwenden.

Um loszulegen, müssen Sie zunächst kein Python-Entwickler sein, da ich hier einen Codeausschnitt einfügen werde.

Erforderliche Werkzeuge

  • VScode natürlich
  • Python installiert/aktualisiert
  • Eine virtuelle Umgebung zum Ausführen neuer Installationen oder Updates für Ihren Python-Code.
  • Die virtuelle Umgebung ist die .venv. Sie werden es in Ihrem vscode sehen.
  • Openpyxyl installieren
  • Installieren Sie alle anderen erforderlichen Abhängigkeiten.
  • Loslegen Sie.

Die verschiedenen Aspekte, die wir berücksichtigen werden:

  • Erstellen einer neuen Excel-Datei mit Python
  • Aktualisieren einer vorhandenen Excel-Datei mit Python Aktualisieren eines bestimmten Excel-Dateiblatts nur mit Python
  • Verwendung von APIs zum Aktualisieren von Excel-Dateien und Excel-Dateiblättern.
  • Erstellen einer Schaltfläche, mit der Benutzer per Klick aktualisieren können.
  • Hinzufügen dynamischer Datums- und Uhrzeitangaben zu Ihrem Code
  • Eine Alternative zur Excel-Schaltfläche ist Cron oder die Windows-Shell
  • Was ist statt VBA noch möglich?
  • Probleme beim Schreiben von VBA in einem MacBook
  • Probleme, mit denen ich beim Erstellen der Schaltfläche konfrontiert war
  • Warum ich mich für cron entschieden habe
  • Erstellt dies sowohl für Windows- als auch für Mac-Benutzer
  • Weitere Tools, die zur Automatisierung von Excel verwendet werden können
  • Power-Abfrage über die Webfunktion
  • Power-Automatisierung
  • Visual Basic in Excel

Erstellen einer neuen Excel-Datei mit Python

Das Erstellen einer Excel-Tabelle in Python mit openpyxl ist einfach.
Sie müssen lediglich openpyxl, pandas und request installieren, wenn Sie Daten von einer API erhalten.
Gehen Sie zur openpyxl-Dokumentation, um zu erfahren, wie Sie es in Ihre Anwendung importieren und welche Pakete Sie verwenden möchten.

import pandas
import requests
from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter

Als nächstes,
Sie erstellen eine neue Arbeitsmappe
Legen Sie es als aktive Arbeitsmappe fest
Fügen Sie Ihren Titel und Ihre Kopfzeile hinzu und füllen Sie die Daten aus
Speichern Sie die neue Arbeitsmappe unter Ihrem bevorzugten Excel-Namen und Tada!
Sie haben Ihre erste Excel-Datei erstellt.

# create a new workbook
wb = Workbook()
ws = wb.active
ws.title = "Data"

ws.append(['Tim', 'Is', 'Great', '!'])
ws.append(['Sam', 'Is', 'Great', '!'])
ws.append(['John', 'Is', 'Great', '!'])
ws.append(['Mimi', 'Is', 'Great', '!'])
wb.save('mimi.xlsx')

Erstellen eines neuen Blattes in einer Excel-Datei.

Das Erstellen eines bestimmten Blatts in Ihrer Excel-Datei ist ein ähnlicher Vorgang. Sie müssen jedoch das zu erstellende Blatt mit einem Blattnamen angeben.

# create sheet
wb.create_sheet('Test')
print(wb.sheetnames)

Ändern einer Excel-Tabelle.

Um eine Excel-Tabelle und nicht die gesamte Datei zu ändern,

Laden Sie die Arbeitsmappe, die Sie ändern möchten
Sie geben das jeweilige zu ändernde Blatt anhand seines Namens oder Index an. Es ist sicherer, den Index zu verwenden, falls sich der Name irgendwann ändert.
Im folgenden Codeausschnitt habe ich das Sheet-Label
verwendet

# wb = load_workbook('mimi.xlsx')

# modify sheet
ws = wb.active
ws['A1'].value = "Test"
print(ws['A1'].value)
wb.save('mimi.xlsx')

Zugriff auf mehrere Zellen

Um auf mehrere Zellen zuzugreifen,
Laden Sie die Arbeitsmappe
Machen Sie es zur aktiven Arbeitsmappe
Schleife durch seine Zeilen und Spalten

# Accessing multiple cells
 wb = load_workbook('mimi.xlsx')
 ws = wb.active

 for row in range(1, 11):
     for col in range(1, 5):
         char = get_column_letter(col)
         ws[char + str(row)] = char + str(row)
         print(ws[char + str(row)].value)

 wb.save('mimi.xlsx')

Excel-Zellen zusammenführen

Um verschiedene Zellen in Excel mit Python zusammenzuführen,
Laden Sie die Arbeitsmappe
Geben Sie die aktive Arbeitsmappe an
Geben Sie die Zellen an, die Sie zusammenführen möchten

# Merging excel cells
wb = load_workbook('mimi.xlsx')
ws = wb.active

ws.merge_cells("A1:D2")
wb.save("mimi.xlsx")

Auflösende Zellen

Um die Verbindung verschiedener Zellen in Excel mit Python aufzuheben,
Laden Sie die Arbeitsmappe
Geben Sie die aktive Arbeitsmappe an
Geben Sie die Zellen an, deren Verbindung Sie aufheben möchten

# merging excel cells
wb = load_workbook('mimi.xlsx')
ws = wb.active

ws.unmerge_cells("A1:D1")
wb.save("mimi.xlsx")

Einfügen neuer Excel-Zellen

Um neue Zellen einzufügen

Laden Sie die Arbeitsmappe
Geben Sie die aktive Arbeitsmappe an
Verwenden Sie insert_rows und insert_columns, um je nach Präferenz neue Zeilen oder neue Spalten einzufügen.

# inserting cells
wb = load_workbook('mimi.xlsx')
ws = wb. is active

ws.insert_rows(7)
ws.insert_rows(7)

ws.move_range("C1:D11", rows=2, cols=2)
wb.save("mimi.xlsx")

Aktualisieren einer vorhandenen Excel-Datei mit internen Daten
Fügen Sie Ihre Arrays und Objekte hinzu und übernehmen Sie die benötigten Informationen

from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font

data = {
    "Pam" : {
        "math":65,
        "science": 78,
        "english": 98,
        "gym": 89
    },
    "Mimi" : {
        "math":55,
        "science": 72,
        "english": 88,
        "gym": 77
    },
    "Sid" : {
        "math":100,
        "science": 66,
        "english": 93,
        "gym": 74
    },
    "Love" : {
        "math":77,
        "science": 83,
        "english": 59,
        "gym": 91
    },
}

wb = Workbook()
ws = wb.active
ws.title = "Mock"
headings = ['Name'] + list(data['Joe'].keys())
ws.append(headings)

for a person in data:
    grades = list(data[person].values())
    ws.append([person] + grades)

for col in range(2, len(data['Pam']) + 2):
    char = get_column_letter(col)
    ws[char + '7'] = f"=SUM({char + '2'}:{char + '6'})/{len(data)}"

for col in range(1, 6):
    ws[get_column_letter(col) + '1'].font = Font(bold=True, color="0099CCFF")


wb.save("NewMock.xlsx")

Aktualisieren einer vorhandenen Excel-Datei mit Python und APIs

Um eine Excel-Datei mit Python und APIs zu aktualisieren, müssen Sie die APIs mithilfe einer Get-Anfrage in Ihrer Datei aufrufen.
Legen Sie die aktive Excel-Datei wie oben beschrieben fest und führen Sie dann Ihr Skript aus.
Hier ist ein Beispiel dafür:

from openpyxl import Workbook, load_workbook
import requests
from datetime import datetime, timedelta

import schedule
import time

api_url = "https://yourapi"
excel_file = "yourfilename.xlsx"

def fetch_energy_data(offset=0):
    response = requests.get(api_url + f"&offset={offset}")
    data = response.json()

    if response.status_code == 200:
        data = response.json()
        return data["results"], data["total_count"] 
    else:
        print(f"Error fetching data: {response.status_code}")
        return [], 0

def update_excel_data(data):
    try:
        wb = load_workbook(excel_file)
        ws = wb.worksheets[0]  

        for row in range(5, ws.max_row + 1):  
            for col in range(1, 9):  
                ws.cell(row=row, column=col).value = None  

                now = datetime.now()
                current_year = now.year
                current_month = now.month

        start_date = datetime(current_year,current_month, 1) 
        end_date = datetime(current_year, current_month, 24) 

        filtered_data = [
            result
            for result in data
            if start_date <= datetime.fromisoformat(result["datetime"]).replace(tzinfo=None) <= end_date]


        for i, result in enumerate(filtered_data):  
            row = i + 5  
            ws[f"A{row}"] = result["datetime"]
            ws[f"B{row}"] = result["yourinfo"]
            ws[f"C{row}"] = result["yourinfo"]
            ws[f"D{row}"] = result["yourinfo"]
            ws[f"E{row}"] = result["yourinfo"]
            ws[f"F{row}"] = result["yourinfo"]  
            ws[f"G{row}"] = result["yourinfo"]
            ws[f"H{row}"] = result["yourinfo"]

        for row in range(5, ws.max_row + 1):
            ws[f"I{row}"] = ws[f"I{row}"].value  
            ws[f"J{row}"] = ws[f"J{row}"].value  
            ws[f"K{row}"] = ws[f"K{row}"].value  
            ws[f"L{row}"] = ws[f"L{row}"].value  

        wb.save(excel_file)
        print(f"Excel file updated: {excel_file}")
    except FileNotFoundError:
        print(f"Excel file not found: {excel_file}")
    except KeyError:
        print(f"Sheet 'Forecast PV' not found in the Excel file.")
    schedule.every().hour.do(update_excel_data)

    while True:
             schedule.run_pending()

if __name__ == "__main__":
    all_data = []
    offset = 0
    total_count = 0
    while True:
        data, total_count = fetch_energy_data(offset)  
        if not data:
            break
        all_data.extend(data)
        offset += 100  
        if offset >= total_count:  
            break


    update_excel_data(all_data)


To update a particular sheet, use the method mentioned above. best practices are done with the excel sheets index number from 0 till n-1.
as sheet names can change but sheet positions can not change.

 wb = load_workbook(excel_file)
        ws = wb.worksheets[0]
  • Creating a button that allows users to update on click. To achieve a button to automatically run your Python script, you need to create a button in your Excel file and write a program using the inbuilt programming language, Visual Basic for applications. Next, you write a program similar to this. An example of a VBA script is below.
Sub RunPythonScript()
    Dim shell As Object
    Dim pythonExe As String
    Dim scriptPath As String
    Dim command As String

     Path to your Python executable
    pythonExe = "C:\Path\To\Python\python.exe"

     Path to your Python script
    scriptPath = "C:\Path\To\Your\Script\script.py"

     Command to run the Python script
    command = pythonExe & " " & scriptPath

     Create a Shell object and run the command
    Set shell = CreateObject("WScript.Shell")
    shell.Run command, 1, True

     Clean up
    Set shell = Nothing
End Sub

the issue with this is some functions do not run in non-windows applications seeing that Excel and VBA are built and managed by Microsoft, there are inbuilt Windows functions for this that can only work on Windows.

However, if you are not writing a very complicated program, it will run properly.

  • Adding dynamic dates and time in your code

To achieve dynamic dates and times, you can use the date.now function built into Python.

now = datetime.now()
 current_year = now.year
current_month = now.month
  • An alternative to the Excel button is cron or Windows shell

For MacBook users, an alternative to the VBA and button feature, you can use a corn for MacBook and a Windows shell for Windows. to automate your task.

You can also make use of Google Clouds's scheduler. that allows you to automate tasks.

  • Instead of VBA, what else is possible?

Instead of VBA, direct Python codes can suffice. you can also use the script and run it as required.

  • Issues faced while writing VBA in a MacBook

The major issue lies in the fact that VBA is a Windows language and hence, has limited functions in a non-windows device.

  • Issues I faced while creating the button

The same issues are related to the VBA code.

  • Why I opted for cron
    I opted for corn because it is available and easy to use to achieve the goals.

  • Other tools that can be used for the automation of Excel

Other tools include:

  • Power query from web feature
  • Power automate
  • Visual Basic in Excel

Follow me on Twitter Handle: https://twitter.com/mchelleOkonicha

Follow me on LinkedIn Handle: https://www.linkedin.com/in/buchi-michelle-okonicha-0a3b2b194/
Follow me on Instagram: https://www.instagram.com/michelle_okonicha/

Das obige ist der detaillierte Inhalt vonSo automatisieren (erstellen, aktualisieren) Sie Excel-Dateien über APIs mit Python und Openpyxl.. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn