【问题标题】:How to connect Dear inventory APIs and Google sheet?如何连接 Dearinventory APIs 和 Google sheet?
【发布时间】:2021-12-05 18:33:23
【问题描述】:

我想使用 Dear API 和 Google Sheets API 将 Dear 库存系统与 Google Sheets 连接,以导入产品列表、销售列表数据等。 它应该会自动更新。 有没有可能? 如果是的话,这里有什么方法吗?

【问题讨论】:

  • 应该是可以的。但是没有现成的方法。有人必须工作几个小时。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: api google-apps-script google-sheets scripting


【解决方案1】:

当然可以。有了这个,你就有了一个不会处理嵌套对象或数组的通用设置。但是您可以使用所需的数据创建特定的函数。但为此你应该雇人,或者自己做。

设置是您可以使用通用函数将所需的端点获取到所需的工作表。 dearAPI(endpoint, sheetname, dig)

Dig:这是保存返回数据数组的对象:

代码:

//GLOBAL variables:
const accountID = 'id';
const secret = 'secret';

function onOpen(e) {
  SpreadsheetApp.getUi().createMenu('DEAR')
    .addItem('Update all', 'updateAll')
    .addToUi();
}

function updateAll(){
  dearAPI('product','Products','Products');
  dearAPI('salesList','Sales', 'SalesList');
}


/**
* Updates data from specific DEAR endpoint to specific sheet.
*
* @param {string} endpoint - the endpoint the get the data from.
* @param {string} sheetname - name of the sheet to write the data to.
* @param {string} dig - the object where the array of data is returned.
* @return {void}
*/
function dearAPI(endpoint, sheetname, dig) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName(sheetname)

  const dataRows = [];
  let pagenumber = 1;

  do {
  const url = `https://inventory.dearsystems.com/externalapi/v2/${endpoint}?page=${pagenumber}&limit=1000`;
  const headers = {
    "api-auth-accountid": accountID,
    "api-auth-applicationkey": secret
  };
  
  const options = {
    "method" : "get",
    "headers" : headers 
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response.getContentText())
  data[dig].forEach(item => dataRows.push(item));
  pagenumber++
  } while (data.Total != data.Page)

  const rowHeaders = Object.keys(dataRows[0]);
  const rows = [rowHeaders];
  for (let i = 0; i < dataRows.length; i++) {
    const rowData = [];
    for (let j = 0; j < rowHeaders.length; j++) {
      rowData.push(dataRows[i][rowHeaders[j]]); 
    }
    rows.push(rowData);
  }

  sheet.getRange(1,1,sheet.getLastRow(), sheet.getLastColumn()).clearContent();
  sheet.getRange(1,1,rows.length,rows[0].length).setValues(rows); 

}

【讨论】:

  • 您好,感谢您的帮助!!!但是当我尝试这段代码时,我在这一行 data[dig].forEach(item => dataRows.push(item)); pagenumber++ 喜欢 TypeError: Cannot read property 'forEach' of undefined
猜你喜欢
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多