Table of Contents
Option#1: Build an easy web scraper using ImportXML in Google Spreadsheets
Step 1: Open a new Google sheet.
Step 2: Open a target website with Chrome. In this case, we choose Games sales. Right-click on the web page and it brings out a drop-down menu. Then select "inspect". Press a combination of three keys: "Ctrl” + “Shift” + “C" to activate "Selector". This would allow the inspection panel to get the information of the selected element within the webpage.
Step 3: Copy and paste the website URL into the sheet.
Option#2: Grab price data with a simple formula: ImportXML
Step1: Copy the Xpath of the element. Select the price element, and Right-Click to bring out the drop-down menu. Then select “Copy”, choose “Copy XPath”.
Step 2: Type the formula to the spreadsheet.
=IMPORTXML(“URL”, “XPATH expression”)
Note the "Xpath expression" is the one we just copied from Chrome. Replace the double quotation mark " " within the Xpath expression with a single quotation mark''.
Option#3: Another formula to get data with Google Sheets
There's another formula we can use:
=IMPORTHTML(“URL”, “QUERY”, Index)
With this formula, you extract the whole table.
Option#4: Automatic web scraping tool without coding
Now, let's see how the same scraping task can be accomplished easily with a web scraper, Octoparse. It allows you extract more data from website than Google Sheets, and you don't need to learn coding skills as it has auto-detect mode. Octoparse works on both Windows and Mac devices, download it and follow the steps below to enjoy.
A video about web scraping with Octoparse
Steps to Scrape Web Data with Google Sheets Web Scraping Alternative
Step 1: Open Octoparse after the quick installation, build a new task by choosing “+Task” under the “Advanced Mode”.
Step 2: Choose your preferred Task Group. Then enter the target website URL, and click "Save URL". In this case: Game Sale website //steamspy.com/
Step 3: Notice Game Sale website is displayed within Octoparse interactive view section. We need to create a loop list to make Octoparse go through the listings.
1. Click one table row (it could be any file within the table) Octoparse then detects similar items and highlights them in red.
2. We need to extract by rows, so choose “TR” (Table Row) from the control panel.
3. After one row has been selected, choose the “Select all sub-element” command from the Action Tips panel. Choose “Select All” command to select all rows from the table.
Step 4: Choose “Extract data in the loop” to extract the data.
You can export the data to Excel, CSV, TXT or other desired formats. Whereas the spreadsheet needs you to physically copy and paste, Octoparse automates the process. In addition, Octoparse has more control over dynamic websites with AJAX or reCaptcha.
If you're finding a data service for your project, Octoparse data service is a good choice. We work closely with you to understand your data requirement and make sure we deliver what you desire. Talk to Octoparse data expert now to discuss how web scraping services can help you maximize efforts.
Pada artikel ini, Anda akan belajar cara mengekspor data Excel ke Google Sheets secara terprogram dengan Python.
File Excel banyak digunakan untuk menyimpan data dan melakukan berbagai jenis operasi di dalamnya, seperti membuat bagan, menerapkan rumus. Di sisi lain, Google Sheets adalah aplikasi online populer untuk membuat dan memanipulasi spreadsheet. Google Sheets juga menyediakan pembagian spreadsheet waktu nyata dengan banyak orang. Dalam kasus tertentu, Anda mungkin perlu mengekspor file Excel XLS atau XLSX ke Google Spreadsheet secara terprogram. Untuk mencapainya, artikel ini memberikan panduan lengkap tentang cara menyiapkan proyek Google dan mengekspor data dari file Excel ke Google Sheets dengan Python.
Prasyarat - Ekspor Data Excel ke Google Sheets dengan Python
Proyek Google Cloud
Untuk berkomunikasi dengan Google Sheets, kita harus membuat proyek di Google Cloud dan mengaktifkan Google Sheets API. Selain itu, kita perlu membuat kredensial yang digunakan untuk mengotorisasi tindakan yang akan kita lakukan dengan kode kita. Anda dapat membaca pedoman tentang .
Setelah membuat proyek Google Cloud dan mengaktifkan Google Sheets API, kita dapat melanjutkan untuk menginstal API berikut di aplikasi Python kita.
Perpustakaan Python untuk Mengekspor File Excel ke Google Sheets
Untuk mengekspor data dari file Excel XLS/XLSX ke Google Sheets, kita memerlukan API berikut.
- Aspose.Cells for Python - To read the data from Excel files.
- - To create and update spreadsheets on Google Sheets.
Ekspor Data dari Excel ke Google Sheets dengan Python
Berikut panduan langkah demi langkah cara membaca data dari file Excel XLSX dan menuliskannya ke Google Sheets di aplikasi Python.
Buat aplikasi Python baru.
Instal Aspose.Cells dan pustaka klien Google di proyek.
Tempatkan file JSON (yang telah kita unduh setelah membuat kredensial di Google Cloud) ke dalam direktori proyek.
Tulis metode bernama createpreadsheet yang membuat spreadsheet baru di Google Sheets, menyetel nama sheet default, dan mengembalikan ID spreadsheet.
- Tulis metode lain bernama addsheet untuk menambahkan sheet baru di spreadsheet Google.
- Sekarang, inisialisasi layanan Google Sheets menggunakan kredensial (file JSON) dan tentukan cakupan aplikasi. Parameter scopes digunakan untuk menentukan izin akses ke Google Sheets dan propertinya.
- Kemudian, muat file XLS atau XLSX Excel menggunakan Aspose.Cells dan dapatkan nama lembar kerja pertama di buku kerja.
- Panggil metode createpreadsheet untuk membuat spreadsheet baru di Google Sheets.
- Ulangi lembar kerja di file Excel. Di setiap iterasi, baca data dari lembar kerja dan tambahkan ke array.
- Untuk setiap lembar kerja di file Excel, buat permintaan untuk menulis data ke Google Sheets.
Berikut ini adalah fungsi lengkap untuk mengekspor data dari file Excel ke spreadsheet di Google Sheets.
def export_to_google(fileName): # Jika mengubah cakupan ini, hapus file token.json. SCOPES = ['//www.googleapis.com/auth/spreadsheets'] creds = None # File token.json menyimpan akses pengguna dan menyegarkan token, dan # dibuat secara otomatis saat alur otorisasi selesai untuk yang pertama # waktu. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # Jika tidak ada kredensial (valid) yang tersedia, biarkan pengguna masuk. 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) # Simpan kredensial untuk proses selanjutnya with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('sheets', 'v4', credentials=creds) # Muat buku kerja Excel wb = Workbook(fileName) # Dapatkan koleksi lembar kerja collection = wb.getWorksheets() collectionCount = collection.getCount() # Dapatkan buku kerja dan nama lembar pertama spreadsheetName = wb.getFileName() firstSheetName = collection.get(0).getName() # Buat spreadsheet di Google Sheets spreadsheetID = create_spreadsheet(service, spreadsheetName, firstSheetName) # Untuk mengatur rentang lembar kerja sheetRange = None # Ulangi semua lembar kerja for worksheetIndex in range(collectionCount): # Dapatkan lembar kerja menggunakan indeksnya worksheet = collection.get(worksheetIndex) # Tetapkan rentang lembar kerja if(worksheetIndex==0): sheetRange= "{0}!A:Y".format(firstSheetName) else: add_sheet(service, spreadsheetID, worksheet.getName()) sheetRange= "{0}!A:Y".format(worksheet.getName()) # Dapatkan jumlah baris dan kolom rows = worksheet.getCells().getMaxDataRow() cols = worksheet.getCells().getMaxDataColumn() # Daftar untuk menyimpan data lembar kerja worksheetDatalist = [] # Ulangi baris for i in range(rows): # Daftar untuk menyimpan setiap baris di lembar kerja rowDataList = [] # Ulangi setiap kolom di baris yang dipilih for j in range(cols): cellValue = worksheet.getCells().get(i, j).getValue() if( cellValue is not None): rowDataList.append(str(cellValue)) else: rowDataList.append("") # Tambahkan ke data lembar kerja worksheetDatalist.append(rowDataList) # Tetapkan nilai body = { 'values': worksheetDatalist } # Jalankan permintaan result = service.spreadsheets().values().update( spreadsheetId=spreadsheetID, range=sheetRange, valueInputOption='USER_ENTERED', body=body).execute() # Cetak jumlah sel yang diperbarui print('{0} cells updated.'.format(result.get('updatedCells'))) except HttpError as err: print(err) print("Workbook has been exported to Google Sheets.")Kode Sumber Lengkap
Berikut ini adalah kode sumber lengkap untuk mengekspor file Excel XLSX ke Google Sheets dengan 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): # Jika mengubah cakupan ini, hapus file token.json. SCOPES = ['//www.googleapis.com/auth/spreadsheets'] creds = None # File token.json menyimpan akses pengguna dan menyegarkan token, dan # dibuat secara otomatis saat alur otorisasi selesai untuk yang pertama # waktu. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # Jika tidak ada kredensial (valid) yang tersedia, biarkan pengguna masuk. 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) # Simpan kredensial untuk proses berikutnya with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('sheets', 'v4', credentials=creds) # Muat buku kerja Excel wb = Workbook(fileName) # Dapatkan koleksi lembar kerja collection = wb.getWorksheets() collectionCount = collection.getCount() # Dapatkan buku kerja dan nama lembar pertama spreadsheetName = wb.getFileName() firstSheetName = collection.get(0).getName() # Buat spreadsheet di Google Sheets spreadsheetID = create_spreadsheet(service, spreadsheetName, firstSheetName) # Untuk mengatur rentang lembar kerja sheetRange = None # Ulangi semua lembar kerja for worksheetIndex in range(collectionCount): # Dapatkan lembar kerja menggunakan indeksnya worksheet = collection.get(worksheetIndex) # Tetapkan rentang lembar kerja if(worksheetIndex==0): sheetRange= "{0}!A:Y".format(firstSheetName) else: add_sheet(service, spreadsheetID, worksheet.getName()) sheetRange= "{0}!A:Y".format(worksheet.getName()) # Dapatkan jumlah baris dan kolom rows = worksheet.getCells().getMaxDataRow() cols = worksheet.getCells().getMaxDataColumn() # Daftar untuk menyimpan data lembar kerja worksheetDatalist = [] # Ulangi baris for i in range(rows): # Daftar untuk menyimpan setiap baris di lembar kerja rowDataList = [] # Ulangi setiap kolom di baris yang dipilih for j in range(cols): cellValue = worksheet.getCells().get(i, j).getValue() if( cellValue is not None): rowDataList.append(str(cellValue)) else: rowDataList.append("") # Tambahkan ke data lembar kerja worksheetDatalist.append(rowDataList) # Tetapkan nilai body = { 'values': worksheetDatalist } # Jalankan permintaan result = service.spreadsheets().values().update( spreadsheetId=spreadsheetID, range=sheetRange, valueInputOption='USER_ENTERED', body=body).execute() # Cetak jumlah sel yang diperbarui 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): # Detail lembar bentang spreadsheetBody = { 'properties': { 'title': "{0}".format(_title) }, 'sheets': { 'properties': { 'title' : "{0}".format(_sheetName) } } } # Buat spreadsheet spreadsheet = _service.spreadsheets().create(body=spreadsheetBody, fields='spreadsheetId').execute() # Buka di browser web webbrowser.open_new_tab("//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)} } } ]} # Jalankan permintaan res = _service.spreadsheets().batchUpdate(spreadsheetId=_spreadsheetID, body=data).execute() # Buat objek icense Aspose.Cells license = License() # Tetapkan lisensi Aspose.Cells untuk menghindari batasan evaluasi license.setLicense("D:\\Licenses\\Conholdate.Total.Product.Family.lic") export_to_google("Book1.xlsx")Dapatkan Lisensi Aspose.Cells Gratis
Anda bisa mendapatkan [lisensi sementara] gratis 7 dan menggunakan Aspose.Cells for Python tanpa batasan evaluasi.
Kesimpulan
Pada artikel ini, Anda telah mempelajari cara mengekspor data Excel ke Google Sheets dengan Python. Kami telah membahas cara membuat proyek di Google Cloud, mengaktifkan Google Sheets API, membaca file Excel, dan mengekspor data dari file Excel ke Google Sheets. Untuk mempelajari lebih lanjut tentang Aspose.Cells for Python, Anda dapat mengunjungi dokumentasi. Selain itu, Anda dapat mengajukan pertanyaan melalui forum kami.