במאמר זה תלמדו כיצד לייצא נתוני Excel ל-Google Sheets באופן פרוגרמטי ב-Python.

ייצא קבצי Excel ל-Google Sheets ב-Python

קבצי Excel נמצאים בשימוש נרחב לאחסון הנתונים ולביצוע סוגים שונים של פעולות עליהם, כגון יצירת תרשימים, יישום נוסחאות. מצד שני, Google Sheets הוא יישום מקוון פופולרי ליצירה ולטפל בגיליונות אלקטרוניים. Google Sheets מספק גם שיתוף בזמן אמת של גיליונות אלקטרוניים עם מספר אנשים. במקרים מסוימים, ייתכן שיהיה עליך לייצא קבצי Excel XLS או XLSX ל-Google Sheets באופן פרוגרמטי. כדי להשיג זאת, מאמר זה מספק מדריך מלא כיצד להגדיר פרויקט של Google ולייצא נתונים מקובצי Excel ל-Google Sheets ב-Python.

דרישות מוקדמות - ייצוא נתוני Excel ל-Google Sheets ב-Python

Google Cloud Project

כדי לתקשר עם Google Sheets, נצטרך ליצור פרויקט ב-Google Cloud ולהפעיל את Google Sheets API. כמו כן, עלינו ליצור אישורים המשמשים לאשר את הפעולות שאנו הולכים לבצע עם הקוד שלנו. אתה יכול לקרוא את ההנחיות בנושא כיצד ליצור פרויקט של Google Cloud ולהפעיל את API של Google Sheets.

לאחר יצירת פרויקט Google Cloud והפעלת ה-API של Google Sheets, נוכל להמשיך להתקין את ממשקי ה-API הבאים באפליקציית Python שלנו.

ספריות Python לייצוא קבצי Excel ל-Google Sheets

כדי לייצא נתונים מקובצי Excel XLS/XLSX ל-Google Sheets, נצטרך את ממשקי ה-API הבאים.

ייצא נתונים מ-Excel ל-Google Sheets ב-Python

להלן המדריך שלב אחר שלב כיצד לקרוא נתונים מקובץ XLSX של Excel ולכתוב אותם ל-Google Sheets ביישום Python.

  1. צור אפליקציית Python חדשה.

  2. התקן את Aspose.Cells וספריות הלקוחות של גוגל בפרויקט.

pip install aspose.cells
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
  1. הכנס את קובץ ה-JSON (שהורדנו לאחר יצירת אישורים ב-Google Cloud) בספריית הפרויקט.

  2. כתוב שיטה בשם createspreadsheet שיוצרת גיליון אלקטרוני חדש ב-Google Sheets, מגדירה את השם של גיליון ברירת המחדל ומחזירה את המזהה של הגיליון האלקטרוני.

def create_spreadsheet(_service, _title, _sheetName):   
    # פרטי גיליון אלקטרוני
    spreadsheetBody = {
        'properties': {
            'title': "{0}".format(_title)
        },
        'sheets': {
            'properties': {
                'title' : "{0}".format(_sheetName)
            }
        }
    }

    # צור גיליון אלקטרוני
    spreadsheet = _service.spreadsheets().create(body=spreadsheetBody,
                                                fields='spreadsheetId').execute()
    
    print('Spreadsheet ID: {0}'.format(spreadsheet.get('spreadsheetId')))
    print('Spreadsheet URL: "https://docs.google.com/spreadsheets/d/{0}'.format(spreadsheet.get('spreadsheetId')))
    
    # פתח בדפדפן אינטרנט
    webbrowser.open_new_tab("https://docs.google.com/spreadsheets/d/{0}".format(spreadsheet.get('spreadsheetId')))

    return spreadsheet.get('spreadsheetId')
  1. כתוב שיטה נוספת בשם addsheet כדי להוסיף גיליון חדש בגיליון האלקטרוני של גוגל.
def add_sheet(_service, _spreadsheetID, _sheetName):
    data = {'requests': [
        {
            'addSheet':{
                'properties':{'title': '{0}'.format(_sheetName)}
            }
        }
    ]}

    # בצע את הבקשה
    res = _service.spreadsheets().batchUpdate(spreadsheetId=_spreadsheetID, body=data).execute()
  1. כעת, אתחל את שירות Google Sheets באמצעות האישורים (קובץ JSON) והגדר את היקפי היישום. הפרמטר scopes משמש לציון הרשאות הגישה ל-Google Sheets ולמאפיינים שלהם.
# אם תשנה היקפים אלה, מחק את הקובץ token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

creds = None
# הקובץ token.json מאחסן את אסימוני הגישה והרענון של המשתמש, והוא
# נוצר באופן אוטומטי כאשר זרימת ההרשאה מסתיימת בפעם הראשונה
# זְמַן.
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

# אם אין אישורים (תקפים) זמינים, אפשר למשתמש להיכנס.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials1.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # שמור את האישורים לריצה הבאה
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

    service = build('sheets', 'v4', credentials=creds)
  1. לאחר מכן, טען את קובץ Excel XLS או XLSX באמצעות Aspose.Cells וקבל את השם של גליון העבודה הראשון בחוברת העבודה.
# טען חוברת עבודה של Excel
wb = Workbook(fileName)

# קבל איסוף דפי עבודה
collection = wb.getWorksheets()
collectionCount = collection.getCount()

# קבל חוברת עבודה ושם הגיליון הראשון
spreadsheetName = wb.getFileName()
firstSheetName = collection.get(0).getName()
  1. קרא לשיטת createspreadsheet כדי ליצור גיליון אלקטרוני חדש ב-Google Sheets.
# צור גיליון אלקטרוני ב-Google Sheets
spreadsheetID = create_spreadsheet(service, spreadsheetName, firstSheetName)
  1. עברו בלולאה בין גליונות העבודה בקובץ האקסל. בכל איטרציה, קרא נתונים מגיליון העבודה והוסף אותם למערך.
# עברו בלולאה בכל דפי העבודה
for worksheetIndex in range(collectionCount):

    # קבל גיליון עבודה באמצעות האינדקס שלו
    worksheet = collection.get(worksheetIndex)

    # הגדר טווח גליון עבודה
    if(worksheetIndex==0):
        sheetRange= "{0}!A:Y".format(firstSheetName)
    else:
        add_sheet(service, spreadsheetID, worksheet.getName())
        sheetRange= "{0}!A:Y".format(worksheet.getName())

    # קבל מספר שורות ועמודות
    rows = worksheet.getCells().getMaxDataRow()
    cols = worksheet.getCells().getMaxDataColumn()

    # רשימה לאחסון הנתונים של גליון העבודה
    worksheetDatalist = []

    # לולאה בין שורות
   for i in range(rows):
        # רשום לאחסון כל שורה בגליון עבודה 
        rowDataList = []

        # עברו בלולאה בכל עמודה בשורה שנבחרה
       for j in range(cols):
            cellValue = worksheet.getCells().get(i, j).getValue()
            if( cellValue is not None):
                rowDataList.append(str(cellValue))
            else:
                rowDataList.append("")

        # הוסף לגליון עבודה נתונים
        worksheetDatalist.append(rowDataList)
  1. עבור כל גליון עבודה בקובץ האקסל, צור בקשה לכתיבת נתונים ל-Google Sheets.
# הגדר ערכים
body = {
    'values': worksheetDatalist
}

# בצע את הבקשה
result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheetID, range=sheetRange,
    valueInputOption='USER_ENTERED', body=body).execute()

# הדפס את מספר התאים המעודכנים    
print('{0} cells updated.'.format(result.get('updatedCells')))

להלן הפונקציה המלאה לייצוא נתונים מקובץ Excel לגיליון אלקטרוני ב-Google Sheets.

def export_to_google(fileName):
    # אם תשנה היקפים אלה, מחק את הקובץ token.json.
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

    creds = None
    # הקובץ token.json מאחסן את אסימוני הגישה והרענון של המשתמש, והוא
    # נוצר באופן אוטומטי כאשר זרימת ההרשאה מסתיימת בפעם הראשונה
    # זְמַן.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
    # אם אין אישורים (תקפים) זמינים, אפשר למשתמש להיכנס.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials1.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # שמור את האישורים לריצה הבאה
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('sheets', 'v4', credentials=creds)
        
        # טען חוברת עבודה של Excel
        wb = Workbook(fileName)

        # קבל איסוף דפי עבודה
        collection = wb.getWorksheets()
        collectionCount = collection.getCount()

        # קבל חוברת עבודה ושם הגיליון הראשון
        spreadsheetName = wb.getFileName()
        firstSheetName = collection.get(0).getName()

        # צור גיליון אלקטרוני ב-Google Sheets
        spreadsheetID = create_spreadsheet(service, spreadsheetName, firstSheetName)

        # כדי להגדיר טווח גליון עבודה
        sheetRange = None

        # עברו בלולאה בכל דפי העבודה
       for worksheetIndex in range(collectionCount):

            # קבל גיליון עבודה באמצעות האינדקס שלו
            worksheet = collection.get(worksheetIndex)

            # הגדר טווח גליון עבודה
            if(worksheetIndex==0):
                sheetRange= "{0}!A:Y".format(firstSheetName)
            else:
                add_sheet(service, spreadsheetID, worksheet.getName())
                sheetRange= "{0}!A:Y".format(worksheet.getName())

            # קבל מספר שורות ועמודות
            rows = worksheet.getCells().getMaxDataRow()
            cols = worksheet.getCells().getMaxDataColumn()

            # רשימה לאחסון הנתונים של גליון העבודה
            worksheetDatalist = []

            # לולאה בין שורות
           for i in range(rows):
                # רשום לאחסון כל שורה בגליון עבודה 
                rowDataList = []

                # עברו בלולאה בכל עמודה בשורה שנבחרה
               for j in range(cols):
                    cellValue = worksheet.getCells().get(i, j).getValue()
                    if( cellValue is not None):
                        rowDataList.append(str(cellValue))
                    else:
                        rowDataList.append("")

                # הוסף לגליון עבודה נתונים
                worksheetDatalist.append(rowDataList)

            # הגדר ערכים
            body = {
                'values': worksheetDatalist
            }
            
            # בצע את הבקשה
            result = service.spreadsheets().values().update(
                spreadsheetId=spreadsheetID, range=sheetRange,
                valueInputOption='USER_ENTERED', body=body).execute()

            # הדפס את מספר התאים המעודכנים    
            print('{0} cells updated.'.format(result.get('updatedCells')))
    except HttpError as err:
        print(err)

    print("Workbook has been exported to Google Sheets.")

קוד מקור מלא

להלן קוד המקור המלא לייצוא קובץ Excel XLSX ל-Google Sheets ב-Python.

from __future__ import print_function
import jpype
import webbrowser
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import asposecells

jpype.startJVM()
from asposecells.api import Workbook, License


def export_to_google(fileName):
    # אם תשנה היקפים אלה, מחק את הקובץ token.json.
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

    creds = None
    # הקובץ token.json מאחסן את אסימוני הגישה והרענון של המשתמש, והוא
    # נוצר באופן אוטומטי כאשר זרימת ההרשאה מסתיימת בפעם הראשונה
    # זְמַן.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
    # אם אין אישורים (תקפים) זמינים, אפשר למשתמש להיכנס.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials1.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # שמור את האישורים לריצה הבאה
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('sheets', 'v4', credentials=creds)
        
        # טען חוברת עבודה של Excel
        wb = Workbook(fileName)

        # קבל איסוף דפי עבודה
        collection = wb.getWorksheets()
        collectionCount = collection.getCount()

        # קבל חוברת עבודה ושם הגיליון הראשון
        spreadsheetName = wb.getFileName()
        firstSheetName = collection.get(0).getName()

        # צור גיליון אלקטרוני ב-Google Sheets
        spreadsheetID = create_spreadsheet(service, spreadsheetName, firstSheetName)

        # כדי להגדיר טווח גליון עבודה
        sheetRange = None

        # עברו בלולאה בכל דפי העבודה
       for worksheetIndex in range(collectionCount):

            # קבל גיליון עבודה באמצעות האינדקס שלו
            worksheet = collection.get(worksheetIndex)

            # הגדר טווח גליון עבודה
            if(worksheetIndex==0):
                sheetRange= "{0}!A:Y".format(firstSheetName)
            else:
                add_sheet(service, spreadsheetID, worksheet.getName())
                sheetRange= "{0}!A:Y".format(worksheet.getName())

            # קבל מספר שורות ועמודות
            rows = worksheet.getCells().getMaxDataRow()
            cols = worksheet.getCells().getMaxDataColumn()

            # רשימה לאחסון הנתונים של גליון העבודה
            worksheetDatalist = []

            # לולאה בין שורות
           for i in range(rows):
                # רשום לאחסון כל שורה בגליון עבודה 
                rowDataList = []

                # עברו בלולאה בכל עמודה בשורה שנבחרה
               for j in range(cols):
                    cellValue = worksheet.getCells().get(i, j).getValue()
                    if( cellValue is not None):
                        rowDataList.append(str(cellValue))
                    else:
                        rowDataList.append("")

                # הוסף לגליון עבודה נתונים
                worksheetDatalist.append(rowDataList)

            # הגדר ערכים
            body = {
                'values': worksheetDatalist
            }
            
            # בצע את הבקשה
            result = service.spreadsheets().values().update(
                spreadsheetId=spreadsheetID, range=sheetRange,
                valueInputOption='USER_ENTERED', body=body).execute()

            # הדפס את מספר התאים המעודכנים    
            print('{0} cells updated.'.format(result.get('updatedCells')))
    except HttpError as err:
        print(err)

    print("Workbook has been exported to Google Sheets.")

def create_spreadsheet(_service, _title, _sheetName):   
    # פרטי גיליון אלקטרוני
    spreadsheetBody = {
        'properties': {
            'title': "{0}".format(_title)
        },
        'sheets': {
            'properties': {
                'title' : "{0}".format(_sheetName)
            }
        }
    }

    # צור גיליון אלקטרוני
    spreadsheet = _service.spreadsheets().create(body=spreadsheetBody,
                                                fields='spreadsheetId').execute()
    
    # פתח בדפדפן אינטרנט
    webbrowser.open_new_tab("https://docs.google.com/spreadsheets/d/{0}".format(spreadsheet.get('spreadsheetId')))

    return spreadsheet.get('spreadsheetId')

def add_sheet(_service, _spreadsheetID, _sheetName):
    data = {'requests': [
        {
            'addSheet':{
                'properties':{'title': '{0}'.format(_sheetName)}
            }
        }
    ]}

    # בצע את הבקשה
    res = _service.spreadsheets().batchUpdate(spreadsheetId=_spreadsheetID, body=data).execute()

 # צור אובייקט רישיון Aspose.Cells
license = License()

# הגדר את הרישיון של Aspose.Cells כדי להימנע ממגבלות ההערכה
license.setLicense("D:\\Licenses\\Conholdate.Total.Product.Family.lic")

export_to_google("Book1.xlsx")

קבל רישיון Aspose.Cells בחינם

אתה יכול לקבל רישיון זמני בחינם ולהשתמש ב-Aspose.Cells עבור Python ללא מגבלות הערכה.

סיכום

במאמר זה למדת כיצד לייצא נתוני Excel ל-Google Sheets ב-Python. סקרנו כיצד ליצור פרויקט ב-Google Cloud, להפעיל את Google Sheets API, לקרוא קבצי Excel ולייצא נתונים מקובצי Excel ל-Google Sheets. כדי לחקור עוד על Aspose.Cells עבור Python, אתה יכול לבקר בתיעוד. כמו כן, אתה יכול לשאול את השאלות שלך דרך הפורום שלנו.

ראה גם