Google cloud firestore 将excel/google工作表电子表格导入云Firestore数据库的最简单方法是什么?

Google cloud firestore 将excel/google工作表电子表格导入云Firestore数据库的最简单方法是什么?,google-cloud-firestore,Google Cloud Firestore,我需要一次性将一个大的数据表导入数据库。我目前有一个Excel文件,但我很高兴把它复制到谷歌工作表等 到目前为止,我已经通过CloudFireStore直接手动添加了一些条目 有没有解决方案可以实现这一点?我认为将表格数据导出到Firestore的最简单方法是使用Google应用程序脚本库(用于Google Sheets) 第一步 复制我创建的一个示例 步骤2 从步骤1中示例谷歌电子表格副本的菜单中,单击Tools>scripteditor。这将打开与示例电子表格关联的示例Google应用程序脚

我需要一次性将一个大的数据表导入数据库。我目前有一个Excel文件,但我很高兴把它复制到谷歌工作表等

到目前为止,我已经通过CloudFireStore直接手动添加了一些条目


有没有解决方案可以实现这一点?

我认为将表格数据导出到Firestore的最简单方法是使用Google应用程序脚本库(用于Google Sheets)

第一步 复制我创建的一个示例

步骤2 从步骤1中示例谷歌电子表格副本的菜单中,单击
Tools>scripteditor
。这将打开与示例电子表格关联的示例Google应用程序脚本

步骤3 按照安装步骤进行操作,然后使用以下内容更新脚本:

  • 电子邮件
  • 钥匙
  • 投射
这些变量是通过转到生成的。这需要您已经有Firebase或Google云帐户设置。我不会重复中已经迭代过的所有步骤。只需仔细遵循它们,并意识到私钥是以
----BEGIN private key-----\n
开始的整个密钥,中间的所有内容,以及以
\n----END private key------\n
结束的整个密钥

步骤4 在电子表格中插入包含数据的页面,然后编辑脚本以使用新的工作表名称和数据。我已经对脚本进行了大量的注释,因此几乎每一行代码都在做什么都非常清楚。对于那些只想看看背后的谷歌应用程序脚本的人,下面是代码:

// Note this Script uses an external library as per this page: 
// https://github.com/grahamearley/FirestoreGoogleAppsScript
// This solution requires a Google Spreadhseet and a Firebase Account
// FOLLOW THE INSTRUCTIONS ON THAT GITHUB REPO TO SETUP NEEDED API KEYS!!!

//Global Variables
const ss = SpreadsheetApp.getActiveSpreadsheet(); // Gets the active "workbook"
const sheet = ss.getSheetByName('Restaurants'); // CHANGE TO YOUR SHEET NAME
const headerRowNumber = 1; // If you have more than one row for your header, then change this value to number of header rows

// If you want to mark modified cells, then set up a trigger for the following function:
// Edit > Current Project Triggers > (+ Add Trigger) > On Edit Spreadsheet etc
function onEdit(e) {
  var cell = ss.getActiveCell(); //This will also effectively get our row
  var dataRange = sheet.getDataRange(); //This checks for all rows/columns with data
  var modifiedCol = dataRange.getLastColumn()-1; //Our "modified" column should be the second to last
  if (cell.getColumn() < modifiedCol && cell.getRow() > headerRowNumber) { //If we edit any cells to the left of our modified column and below our header...
    var celltoMark = sheet.getRange(cell.getRowIndex(),modifiedCol)   //Get the R/C cordinates of cell to place modified time
    celltoMark.setValue(new Date()); //write timestamp to that cell
  }
};
// This will parse any comma separated lists you create in any of your fields (useful for search words, or attributes, etc)
function listToArray(list) {
  var ogArray = list.split(","); //Input is a comma separated list
  let trimmedArr = ogArray.map(string => string.trim()); //Let's strip out the leading/trailing whitespaces if any
  return trimmedArr; //return the cleaned array
}

function writeToFireStore() {
  const email = 'sheets@yourprojectid.iam.gserviceaccount.com'; // CHANGE THIS!!!
  const key = '-----BEGIN PRIVATE KEY-----\nYOURPRIVATEKEY\n-----END PRIVATE KEY-----\n'; // CHANGE THIS!!!
  const projectID = 'yourprojectid'; // CHANGE THIS!!!
  var firestore = FirestoreApp.getFirestore(email, key, projectID);
  const collection = "MySpreadsheetData"; // Name of your Firestore Database "Collection"

  var dataRange = sheet.getDataRange().offset(headerRowNumber, 0, sheet.getLastRow() - headerRowNumber); //this is your data range
  var data = dataRange.getValues(); // this is an array of your datarange's values
  var lastCol = dataRange.getLastColumn(); // this is the last column with a header
  var newDoc = {}; // Instantiate your data object. Each one will become the data for your firestore documents

  // r = row number in this case
  for (let r = 0; r <= dataRange.getLastRow(); r++) {
    //Logger.log("R = ",r);
    var cellMod = dataRange.getCell(r+1, lastCol-1);
    var cellFS = dataRange.getCell(r+1, lastCol);
    var cellModVal = cellMod.getValue();
    var cellFSVal = cellFS.getValue();
    //
    // IMPORTANT READ THIS IMPORTANT READ THIS IMPORTANT READ THIS IMPORTANT READ THIS IMPORTANT READ THIS!!!
    // Well, read the line below...
    if (r > 2) break; //Comment Out this line after you're done testing otherwise you'll write all your rows to firestore after every run
    newDoc[r] = {
      name : data[r][1],
      category : data[r][2],
      cuisine : data[r][3],
      address: {
        add1: data[r][4],
        add2: data[r][5],
        city: data[r][6],
        state: data[r][7],
        zip: data[r][8]
      },
      tel: data[r][9],
      searchterms: listToArray(data[r][10]) //Let's turn a csv list into an array
    }

    // For the sake of efficiency and to save $, we WON'T create documents that have already been created...
    // ...and we won't update documents that have a fireStore Timestamp that's newer than a Modified Timestamp

      // If there's not firestore timestamp in our spreadsheet, then let's create firestore document and update firestore stamp:
    if (!cellFSVal) {
      var now = new Date(); //Generate timestamp right now
      try {
        firestore.createDocument(collection + "/" + data[r][0], newDoc[r]); // To Use Your Own Document ID
        //Now let's insert a timestamp in our Firestore TS column of the sheet so we know it's been added to Firestore
        cellFS.setValue(now);
        Logger.log("Row ",r,"(",data[r][1],") is NEW and was added to FireStore Successfully");
      } catch (e) {
        Logger.log("Error: ",e," : Document with same name already existed in Firestore."); 
      }
    }
    //var if FS Timestamp exists but, the modified time stamp is greater, let's update the Firstore Document
    else if ((cellFSVal) && (cellModVal > cellFSVal)) {
      try {
        firestore.updateDocument(collection + "/" + data[r][0], newDoc[r]);
        //Now let's insert a timestamp in our Firestore TS column of the sheet so we know it's been updated to Firestore
        cellFS.setValue(now);
        Logger.log("Row ",r,"(",data[r][1],") updated/edited.");
      } catch (e) {
        Logger.log("Error: ",e," : Document existed, we tried updating it, but jack shit happened.");
      }
    }
    else {
      Logger.log("Row ",r,"(",data[r][1],") Already in Firestore & hasn't been modified. Skipped.");
    }
  }
}
//注意:此脚本使用与此页面相同的外部库:
// https://github.com/grahamearley/FirestoreGoogleAppsScript
//此解决方案需要Google Spreadhseet和Firebase帐户
//按照GITHUB REPO上的说明设置所需的API密钥!!!
//全局变量
const ss=SpreadsheetApp.getActiveSpreadsheet();//获取活动的“工作簿”
const sheet=ss.getSheetByName('Restaurants');//更改您的工作表名称
常数headerRownNumber=1;//如果标题有多行,则将此值更改为标题行数
//如果要标记修改的单元格,请为以下功能设置触发器:
//编辑>当前项目触发器>(+添加触发器)>编辑电子表格等
功能OneEdit(e){
var cell=ss.getActiveCell();//这也将有效地获取我们的行
var dataRange=sheet.getDataRange();//检查所有包含数据的行/列
var modifiedCol=dataRange.getLastColumn()-1;//我们的“modified”列应该是倒数第二个
如果(cell.getColumn()headerRowNumber){//如果我们编辑修改列左侧和标题下方的任何单元格。。。
var celltoMark=sheet.getRange(cell.getRowIndex(),modifiedCol)//获取要放置修改时间的单元格的R/C坐标
setValue(new Date());//将时间戳写入该单元格
}
};
//这将解析您在任何字段中创建的任何逗号分隔列表(对搜索词或属性等有用)
函数listToArray(列表){
var ogArray=list.split(,“”;//输入是一个逗号分隔的列表
让trimmedArr=ogArray.map(string=>string.trim());//让我们去掉前导/尾随空格(如果有的话)
return trimmedArr;//返回清理后的数组
}
函数writeToFireStore(){
常数电子邮件sheets@yourprojectid.iam.gserviceaccount.com“;//改变这个!!!
const key='----开始私钥------\n您的私钥------结束私钥------\n';//更改此项!!!
const projectID='yourprojectid';//更改此项!!!
var firestore=FirestoreApp.getFirestore(电子邮件、密钥、projectID);
const collection=“MySpreadsheetData”;//Firestore数据库“集合”的名称
var dataRange=sheet.getDataRange().offset(headerRowNumber,0,sheet.getLastRow()-headerRowNumber);//这是您的数据范围
var data=dataRange.getValues();//这是数据范围值的数组
var lastCol=dataRange.getLastColumn();//这是最后一列的标题
var newDoc={};//实例化数据对象。每个对象都将成为firestore文档的数据
//r=在这种情况下的行号
for(让r=0;r2)break;//在完成测试后注释掉这一行,否则每次运行后都会将所有行写入firestore
newDoc[r]={
名称:data[r][1],,
类别:数据[r][2],,
烹饪:数据[r][3],
地址:{
地址1:数据[r][4],
加二:数据[r][5],
城市:数据[r][6],
国家:数据[r][7],
zip:data[r][8]
},
电话:data[r][9],,
searchterms:listToArray(data[r][10])//让我们将一个csv列表转换为一个数组
}
//为了提高效率和节省美元,我们不会创建已经创建的文档。。。
//…并且我们不会更新fireStore时间戳比修改后的时间戳新的文档
//如果我们的电子表格中没有firestore时间戳,那么让我们创建firestore文档并更新firestore stamp:
如果(!cellFSVal){
var now=new Date();//立即生成时间戳
试一试{
firestore.createDocument(collection+“/”+data[r][0],newDoc[r]);//使用您自己的文档ID
//现在,让我们在工作表的Firestore TS列中插入一个时间戳,以便我们知道它已添加到Firestore
cellFS.setValue(现在);
Logger.log(“Row”,r,”(“,data[r][1],”)是新的,已成功添加到FireStore);
}捕获(e){
Logger.log(“错误:”,e:“:Firestore中已存在同名文档。”);
}
}
//var如果FS Timestamp存在,但是修改的时间戳更大,那么让我们更新Firstore文档
else if((cellFSVal)&(cellModVal>cellFSVal)){
试一试{
firestore.updateDocument(公司