>  기사  >  백엔드 개발  >  Python 및 Openpyxl을 사용하여 API에서 Excel 파일을 자동화(생성, 업데이트)하는 방법.

Python 및 Openpyxl을 사용하여 API에서 Excel 파일을 자동화(생성, 업데이트)하는 방법.

王林
王林원래의
2024-08-16 18:01:40306검색

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

그래서 많은 사람들이 자동화라고 하면 가장 추상적으로 생각하는 것으로 알고 있습니다. 아마도 수리를 위해 정비소를 생각할 수도 있습니다. ㅋㅋㅋ
어쨌든 프로그래밍의 자동화는 바로 여러분이 작성하는 코드이지만 이를 올바르게 실행하는 데 도움이 되는 다른 기술을 사용하는 것입니다.

처음 Python을 사용하기 시작했을 때는 데이터 구조와 알고리즘을 작성하는 것이었지만 나중에는 ML 모델 개발을 시도하고 Python을 프로그래밍하는 등 다른 용도로 사용하게 되었습니다.

이 기사에서는 애플리케이션용 Visual Basic을 사용하지 않고 MacBook에서 Excel 파일과 다양한 시트를 자동화하는 방법에 대한 단계별 가이드를 제공할 것입니다.

우선, 여기에 코드 조각을 붙여넣을 것이므로 시작하려면 Python 개발자가 될 필요는 없습니다.

필요한 도구

  • 물론 VScode
  • Python 설치/업데이트
  • Python 코드에 대한 새로운 설치나 업데이트를 실행하기 위한 가상 환경입니다.
  • 가상 환경은 .venv입니다. vscode에서 볼 수 있습니다.
  • openpyxyl 설치
  • 기타 필요한 종속성을 설치합니다.
  • 시작하세요.

고려할 다양한 측면:

  • 파이썬으로 새 엑셀 파일 만들기
  • Python으로 기존 Excel 파일 업데이트 Python으로만 특정 Excel 파일 시트 업데이트
  • API를 사용하여 Excel 파일 및 Excel 파일 시트를 업데이트합니다.
  • 사용자가 클릭하면 업데이트할 수 있는 버튼 만들기
  • 코드에 동적 날짜 및 시간 추가
  • Excel 버튼의 대안은 cron 또는 Windows 셸입니다
  • VBA말고 또 무엇이 가능할까요?
  • MacBook에서 VBA를 작성할 때 발생하는 문제
  • 버튼을 만들면서 겪은 문제
  • 내가 cron을 선택한 이유
  • Windows 및 Mac 사용자 모두를 위해 만들기
  • 엑셀 자동화에 사용할 수 있는 기타 도구
  • 웹 기능을 통한 파워 쿼리
  • 전력 자동화
  • Excel의 Visual Basic

Python으로 새 Excel 파일 만들기

openpyxl을 사용하여 Python에서 Excel 시트를 만드는 것은 쉽습니다.
API에서 데이터를 가져오는 경우 openpyxl, pandas 및 요청을 설치하기만 하면 됩니다.
openpyxl 문서로 이동하여 이를 애플리케이션과 사용하려는 패키지로 가져오는 방법을 알아보세요.

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

다음은
새 통합 문서를 만듭니다
활성 통합 문서로 설정
제목과 헤더를 추가하고 데이터를 채우세요
원하는 Excel 이름과 형식으로 새 통합 문서를 저장하세요!
첫 번째 Excel 파일을 만들었습니다.

# 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')

Excel 파일에 새 시트를 만듭니다.

Excel 파일에서 특정 시트를 만드는 과정도 비슷합니다. 단, 생성할 시트를 시트 이름으로 지정해야 합니다.

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

Excel 시트 수정.

전체 파일이 아닌 Excel 시트를 수정하려면

수정하려는 통합문서 로드
이름이나 색인을 사용하여 수정할 특정 시트를 지정합니다. 나중에 이름이 바뀔 경우를 대비해 색인을 사용하는 것이 더 안전합니다.
아래 코드 조각에서는 시트 레이블을 사용했습니다

# wb = load_workbook('mimi.xlsx')

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

여러 셀에 액세스

여러 셀에 액세스하려면
통합 문서 로드
활성 통합 문서로 만들기
행과 열을 반복합니다

# 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 셀 병합

Python을 사용하여 Excel에서 서로 다른 셀을 병합하려면
통합 문서 로드
활성 통합 문서 표시
병합하려는 셀을 표시하세요

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

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

셀 병합 해제

Python을 사용하여 Excel에서 서로 다른 셀을 병합 취소하려면
통합 문서 로드
활성 통합 문서 표시
병합을 취소하려는 셀을 지정하세요

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

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

새로운 엑셀 셀 삽입하기

새 셀을 삽입하려면

워크북 로드
활성 통합 문서 표시
insert_rows 및 insert_columns를 사용하여 선호도에 따라 새 행 또는 새 열을 삽입하세요.

# 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")

내부 데이터로 기존 Excel 파일 업데이트
배열과 개체를 추가하고 필요한 정보를 가져옵니다

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")

Python 및 API를 사용하여 기존 Excel 파일 업데이트

Python과 API를 사용하여 Excel 파일을 업데이트하려면 Get 요청을 사용하여 파일에 API를 호출해야 합니다.
위에서 설명한 대로 활성 Excel 파일을 설정한 다음 스크립트를 실행합니다.
이에 대한 예는 다음과 같습니다.

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/

위 내용은 Python 및 Openpyxl을 사용하여 API에서 Excel 파일을 자동화(생성, 업데이트)하는 방법.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.