如何将Firebase数据库与Google表格同步?

时间:2017-07-05 10:51:19

标签: firebase ionic-framework firebase-realtime-database angularfire google-sheets-api

我正在使用带有ts的Ionic 3项目将Firebase集成到我的应用程序中。 我用以下代码将firebase与Ionic项目集成

constructor(angFire: AngularFireDatabase){
}
 books: FirebaseListObservable<any>;

要将数据从我的应用程序发送到firebase,我使用了push方法并更新了我使用的update($key)条目。现在我拥有Firebase后端的所有数据。

现在,我如何将firebase数据库与Google表格同步,以便添加到firebase后端的每个条目都必须更新为工作表。我使用第三方 ZAPIER 进行此集成,但如果我了解如何自行进行此同步,那就太好了。

在浏览时,有许多教程可以将数据从Google表格中导入Firebase。但我没有遇到任何教程,反之亦然。

我按照下面的教程,但它没有指向电子表格。 https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

我考虑通过JavaScript SDK或REST API将Firebase直接导入Google Scripts。两者都有Google Scripts无法满足的要求/步骤或极难满足的要求/步骤。

  • 没有可预见的方法在Google Script中下载JavaScript SDK,因为几乎每种方法都需要一个DOM,而Google表格中没有这个DOM。
  • REST API需要GoogleCredentials,一眼就看起来很难进入Google脚本

所以,另一个选择是在真正的服务器端环境中与Firebase进行交互。这将是很多代码,但以下是我将采取的步骤:

1)设置Pyrebase项目,以便您通过Python与Firebase项目进行互动。

import pyrebase

config = {
    "apiKey": "apiKey",
    "authDomain": "projectId.firebaseapp.com",
    "databaseURL": "https://databaseName.firebaseio.com",
    "storageBucket": "projectId.appspot.com",
    "serviceAccount": "path/to/serviceAccountCredentials.json"
}
firebase = pyrebase.initialize_app(config)

...

db = firebase.database()
all_users = db.child("users").get()

2)Google Scripts/Sheets项目设置为可与您的Google表格进行互动的课程

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

class GoogleSheets:

    ...
    # The rest of the functions from that link can go here
    ...

    def write(self, sheet, sheet_name, row, col):
        """
            Write data to specified google sheet
        """

        if sheet == None or sheet == "":
            print("Sheet not specified.")
            return

        day = time.strftime("%m/%d/%Y")
        clock = time.strftime("%H:%M:%S")
        datetime = day + " - " + clock
        values = [[datetime]]

        spreadsheetId = sheet
        rangeName = sheet_name + "!" + str(row) + ":" + str(col)
        body = {
            'values': values
        }

        credentials = self.get_credentials()
        http = credentials.authorize(httplib2.Http())
        discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                'version=v4')
        service = discovery.build('sheets', 'v4', http=http,
                          discoveryServiceUrl=discoveryUrl)
        result = service.spreadsheets().values().update(
            spreadsheetId=spreadsheetId, range=rangeName,
            valueInputOption="RAW", body=body).execute()

3)在Pyrebase项目中的某个地方调用Google表格

from GoogleSheets import GoogleSheets

...

g = GoogleSheets()
g.write(<project-id>, <sheet-name>, <row>, <col>)

...

4)设置一个cron作业,以便经常运行python脚本

# every 2 minutes
*/2 * * * * /root/my_projects/file_example.py

你需要一些基本的服务器(Heroku,Digital Ocean)来运行它。

这并不广泛,因为要编写很多代码,但您可以完成基础知识。让我们现在想要制作一个包。

答案 1 :(得分:1)

您可以使用Zapier这是第三方服务,您可以通过该服务轻松集成Firebase和Google电子表格,反之亦然。它还为谷歌文档和其他功能提供了一些支持。

Sub makeUniqueTable()

    Application.ScreenUpdating = False

    Dim MainWS As Worksheet
    Set MainWS = ThisWorkbook.Sheets("Part Tracking Scorecard")

    Dim UniqueWS As Worksheet
    Set UniqueWS = ThisWorkbook.Sheets("Unique Parts")

    UniqueWS.Cells.Clear

    Call cloneTable(MainWS.ListObjects("PartTable"), "UniquePartTable", UniqueWS)

    Dim UniquePartTable As ListObject
    Set UniquePartTable = UniqueWS.ListObjects("UniquePartTable")

    Call removeDuplicates(UniquePartTable, "Part Number")

    'Optional: remove unnecessary columns by listing columns to be deleted...
    'Call deleteColumns(UniquePartTable, Array("Unnecessary Column 1", "Unnecessary Column 2"))
    '...or kept:
    'Call deleteColumns(UniquePartTable, Array("Part Number", "Manufacturer", "Product Description"), True)

    Application.ScreenUpdating = True

End Sub

Sub cloneTable(tbl As ListObject, newName As String, Optional newWS As Worksheet = Nothing)
'Copies a table (tbl) to a new worksheet (newWS) and gives it a name (newName)
'If there is any data in newWS, the new table will be added to the right of the used range
'If newWS is omitted, new table will be added to same worksheet as original table

    Dim ws As Worksheet
    Dim lastColumn As Long
    Dim newRng As Range
    Dim newTbl As ListObject

    If newWS Is Nothing Then
        Set ws = tbl.Parent
        lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
        Set newRng = ws.Range(ws.Cells(1, lastColumn + 2), ws.Cells(1 + tbl.ListRows.Count, lastColumn + tbl.ListColumns.Count + 1))
    Else
        Set ws = newWS
        If ws.ListObjects.Count > 0 Then
            lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
            Set newRng = ws.Range(ws.Cells(1, lastColumn + 2), ws.Cells(1 + tbl.ListRows.Count, lastColumn + tbl.ListColumns.Count + 1))
        Else
            Set newRng = ws.Range(ws.Cells(1, 1), ws.Cells(1 + tbl.ListRows.Count, tbl.ListColumns.Count))
        End If
    End If

    tbl.Range.Copy
    newRng.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
    Application.CutCopyMode = False

    Set newTbl = ws.ListObjects.Add(xlSrcRange, newRng, , xlYes)
    newTbl.Name = newName

End Sub
Sub removeDuplicates(tbl As ListObject, Optional colName As Variant = "")
'Removes duplicates from a table (tbl) based on column header names (colName()) provided by user
'If no column names are provided, duplicates will be removed based on all columns in table

    Dim i As Long
    Dim j As Long

    If Not IsArray(colName) Then
        If colName = "" Then
            ReDim colNumArr(0 To tbl.ListColumns.Count - 1) As Variant
            For i = 0 To tbl.ListColumns.Count - 1
                colNumArr(i) = tbl.ListColumns(i + 1).Range.Column
            Next
        Else
            ReDim colNumArr(0 To 0) As Variant
            colNumArr(0) = tbl.ListColumns(colName).Range.Column
        End If
    Else
        ReDim colNumArr(0 To UBound(colName) - LBound(colName)) As Variant
        j = 0
        For i = LBound(colName) To UBound(colName)
            colNumArr(j) = tbl.ListColumns(colName(i)).Range.Column
            j = j + 1
        Next
    End If

    tbl.Range.removeDuplicates Columns:=(colNumArr), Header:=xlYes

End Sub
Sub deleteColumns(tbl As ListObject, ByVal colName As Variant, Optional invert As Boolean = False, Optional sheetCol As Boolean = True)
'Deletes column(s) from sheet based on header names (colName) from a table (tbl)
'Will result in error if provided column contains multiple tables
'colName can be a String or an array of Strings
'Inverted mode deletes all columns *except* those in colName

    Dim i As Long
    Dim j As Long
    Dim x As Boolean

    If Not IsArray(colName) Then
        tempStr = colName
        ReDim colName(1 To 1) As String
        colName(1) = tempStr
    End If

    If invert = False Then
        For i = LBound(colName) To UBound(colName)
            If sheetCol = True Then
                tbl.Parent.Columns(tbl.ListColumns(colName(i)).Range.Column).Delete
            Else
                tbl.ListColumns(colName(i)).Delete
            End If
        Next
    Else
        For i = tbl.ListColumns.Count To 1 Step -1
            x = False
            For j = LBound(colName) To UBound(colName)
                If tbl.HeaderRowRange(i).Value = colName(j) Then
                    x = True
                    Exit For
                End If
            Next
            If x = False Then
                If sheetCol = True Then
                    tbl.Parent.Columns(tbl.ListColumns(i).Range.Column).Delete
                Else
                    tbl.ListColumns(i).Delete
                End If
            End If
        Next
    End If

End Sub

答案 2 :(得分:0)