ในบทความนี้ คุณจะได้เรียนรู้วิธีส่งออกข้อมูล Excel ไปยัง Google ชีตโดยทางโปรแกรมใน Python

ส่งออกไฟล์ Excel ไปยัง Google ชีตใน Python

ไฟล์ Excel ถูกใช้อย่างแพร่หลายเพื่อจัดเก็บข้อมูลและดำเนินการประเภทต่างๆ ในนั้น เช่น การสร้างแผนภูมิ การใช้สูตร ในทางกลับกัน Google ชีต เป็นแอปพลิเคชันออนไลน์ยอดนิยมสำหรับสร้างและจัดการสเปรดชีต Google ชีตยังมีการแชร์สเปรดชีตแบบเรียลไทม์กับหลายๆ คน ในบางกรณี คุณอาจต้องส่งออกไฟล์ Excel XLS หรือ XLSX ไปยัง Google ชีตโดยทางโปรแกรม บทความนี้จะให้คำแนะนำฉบับสมบูรณ์เกี่ยวกับวิธีตั้งค่าโครงการ Google และส่งออกข้อมูลจากไฟล์ Excel ไปยัง Google ชีตใน Python

ข้อกำหนดเบื้องต้น - ส่งออกข้อมูล Excel ไปยัง Google ชีตใน Python

โครงการ Google Cloud

ในการสื่อสารกับ Google ชีต เราจะต้องสร้างโครงการบน Google Cloud และเปิดใช้งาน Google ชีต API นอกจากนี้ เราจำเป็นต้องสร้างข้อมูลประจำตัวที่ใช้เพื่ออนุญาตการดำเนินการที่เราจะดำเนินการกับรหัสของเรา คุณสามารถอ่านหลักเกณฑ์เกี่ยวกับ วิธีสร้างโครงการ Google Cloud และเปิดใช้งาน Google ชีต API

หลังจากสร้างโครงการ Google Cloud และเปิดใช้งาน Google ชีต API แล้ว เราสามารถดำเนินการติดตั้ง API ต่อไปนี้ในแอปพลิเคชัน Python ของเราได้

Python Libraries เพื่อส่งออกไฟล์ Excel ไปยัง Google ชีต

ในการส่งออกข้อมูลจากไฟล์ Excel XLS/XLSX ไปยัง Google ชีต เราจำเป็นต้องมี API ต่อไปนี้

ส่งออกข้อมูลจาก Excel ไปยัง Google ชีตใน Python

ต่อไปนี้เป็นคำแนะนำทีละขั้นตอนเกี่ยวกับวิธีอ่านข้อมูลจากไฟล์ Excel XLSX และเขียนลงใน Google ชีตในแอปพลิเคชัน Python

  1. สร้างแอปพลิเคชัน Python ใหม่

  2. ติดตั้ง Aspose.Cells และไลบรารีไคลเอ็นต์ของ Google ในโครงการ

pip install aspose.cells
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
  1. วางไฟล์ JSON (เราได้ดาวน์โหลดหลังจากสร้างข้อมูลประจำตัวใน Google Cloud) ลงในไดเร็กทอรีของโครงการ

  2. เขียนเมธอดที่ชื่อว่า createspreadsheet ซึ่งสร้างสเปรดชีตใหม่บน Google ชีต ตั้งชื่อชีตเริ่มต้น และส่งกลับ ID ของสเปรดชีต

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 เพื่อเพิ่มแผ่นงานใหม่ในสเปรดชีตของ Google
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 ชีตโดยใช้ข้อมูลรับรอง (ไฟล์ JSON) และกำหนดขอบเขตของแอปพลิเคชัน พารามิเตอร์ scopes ใช้เพื่อระบุสิทธิ์การเข้าถึง Google ชีตและคุณสมบัติต่างๆ
# หากแก้ไขขอบเขตเหล่านี้ ให้ลบไฟล์ 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 ชีต
# สร้างสเปรดชีตบน Google ชีต
spreadsheetID = create_spreadsheet(service, spreadsheetName, firstSheetName)
  1. วนซ้ำแผ่นงานในไฟล์ Excel ในการวนซ้ำแต่ละครั้ง ให้อ่านข้อมูลจากเวิร์กชีตและเพิ่มลงในอาร์เรย์
# วนรอบแผ่นงานทั้งหมด
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. สำหรับแต่ละแผ่นงานในไฟล์ Excel ให้สร้างคำขอเพื่อเขียนข้อมูลไปยัง Google ชีต
# ตั้งค่า
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 ชีต

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 ชีต
        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 ชีตใน 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 ชีต
        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 ฟรี

คุณสามารถรับ [ใบอนุญาตชั่วคราว] ฟรี 7 และใช้ Aspose.Cells for Python โดยไม่มีข้อจำกัดในการประเมิน

บทสรุป

ในบทความนี้ คุณได้เรียนรู้วิธีส่งออกข้อมูล Excel ไปยัง Google ชีตใน Python เราได้กล่าวถึงวิธีสร้างโครงการบน Google Cloud, เปิดใช้งาน Google ชีต API, อ่านไฟล์ Excel และส่งออกข้อมูลจากไฟล์ Excel ไปยัง Google ชีต หากต้องการสำรวจเพิ่มเติมเกี่ยวกับ Aspose.Cells for Python คุณสามารถไปที่ เอกสารประกอบ นอกจากนี้ คุณสามารถถามคำถามผ่าน ฟอรัม ของเรา

ดูสิ่งนี้ด้วย