You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Google App Script调用Snipe-IT API并写入Google Sheet

解决Google Apps Script无法将Snipe-IT资产数据写入Google Sheet的问题

你的脚本已经成功从Snipe-IT API获取到了资产ID,但缺少将数据写入Google Sheet的核心逻辑。以下是修改后的完整脚本,添加了数据写入功能:

// SETUP
const serverURL = 'SERVER-URL'; // 替换为你的Snipe-IT服务器地址
const apiKey = 'API-KEY'; // 替换为你的API密钥

function onOpen(e) {
  createCommandsMenu();
}

function createCommandsMenu() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('Run Script')
    .addItem('Get Assets By Department', 'runGetAssetsByDepartment')
    .addItem('Test Get Assets By User', 'testGetAssetsByUser') // 添加菜单选项
    .addToUi();
}

function testGetAssetsByUser() {
  const userID = "1745";
  const assets = getAssetsByUser(userID);
  writeAssetsToSheet(assets); // 调用写入函数
}

// 获取指定用户的资产ID(筛选指定类别)
function getAssetsByUser(userID) {
  const url = `${serverURL}api/v1/users/${userID}/assets`;
  const headers = {
    "Authorization": `Bearer ${apiKey}`
  };
  
  const options = {
    "method": "GET",
    "contentType": "application/json",
    "headers": headers
  };
  
  const response = JSON.parse(UrlFetchApp.fetch(url, options));
  const rows = response.rows;
  const assets = [];
  
  for (let i = 0; i < rows.length; i++) {
    const row = rows[i];
    const allowedCategories = ["Laptop", "Desktop", "2-in-1"];
    if (allowedCategories.includes(row.category.name)) {
      assets.push([row.id]); // 改为二维数组,适配表格写入
    }
  }
  return assets;
}

// 将资产ID写入Google Sheet
function writeAssetsToSheet(assets) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 获取当前活跃工作表
  // 可选:清空现有数据(根据需求调整)
  // sheet.clearContents();
  
  // 写入表头(可选)
  sheet.getRange(1, 1).setValue("资产ID");
  
  // 写入资产数据(从第二行开始)
  if (assets.length > 0) {
    sheet.getRange(2, 1, assets.length, 1).setValues(assets);
  }
  
  SpreadsheetApp.getUi().alert("数据写入完成!"); // 提示用户操作完成
}

// 仅在脚本编辑器测试时使用
// console.log(getAssetsByUser("1745"));

关键修改说明:

  • 添加写入函数:新增writeAssetsToSheet函数,使用Google Sheet服务的setValues方法将数据写入表格。注意:setValues需要接收二维数组,因此将assets.push(row.id)改为assets.push([row.id])。
  • 关联获取与写入:在testGetAssetsByUser中调用getAssetsByUser获取数据后,立即调用writeAssetsToSheet写入表格。
  • 菜单扩展:在自定义菜单中添加了"Test Get Assets By User"选项,方便直接从表格界面运行测试。
  • 代码优化:使用模板字符串简化URL拼接,用数组includes方法简化类别判断,提升代码可读性。

使用步骤:

  • 将脚本中的SERVER-URL和API-KEY替换为你的实际信息。
  • 保存脚本并刷新Google Sheet,此时会出现"Run Script"菜单。
  • 点击"Run Script" > "Test Get Assets By User",首次运行会要求授权,按照提示完成授权即可。
  • 数据会写入当前活跃工作表的第一列,表头为"资产ID",资产ID从第二行开始排列。

内容的提问来源于stack exchange,提问作者Jonathan Leyva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:57:21