Google Apps Script解析XML数据写入Google Sheets问题求解
XML员工数据导入Google Sheet解决方案
原代码错误点
- 节点匹配错误:员工列表的子节点标签为
<employee>,原代码写的getChildren("row")无法获取到任何员工记录 - 取值逻辑错误:员工的姓名、职位等信息不是
<employee>标签的属性,而是嵌套在标签内部、带id标识的<field>子节点的文本内容,直接从employee节点读取属性无法拿到值 - 条件判断逻辑错误:原代码的响应码判断
!res.getResponseCode() === 200存在运算优先级问题,永远无法正确触发报错 - 缺少空值兼容:自闭合的空字段(如示例中无值的
workPhoneExtension)直接取值会触发报错 - 缺少表头提取、数据写入Sheet的完整逻辑
修正后可直接运行的代码
function importEmployeeDataToSheet() { // 接口配置 const apiUrl = "https://api.bamboohr.com/api/gateway.php/empgtest/v1/employees/directory"; const apiKey = "替换为你的实际BambooHR API密钥"; const authHeader = "Basic " + Utilities.base64Encode(apiKey + ":x"); // 发起接口请求 const response = UrlFetchApp.fetch(apiUrl, { headers: { "Authorization": authHeader } }); if (response.getResponseCode() !== 200) { throw new Error("接口请求失败:" + response.getContentText()); } // 解析XML结构 const xmlDocument = XmlService.parse(response.getContentText()); const rootElement = xmlDocument.getRootElement(); // 提取表头:从fieldset节点获取所有字段的显示名称 const fieldDefinitionNodes = rootElement.getChild("fieldset").getChildren("field"); const tableHeaders = ["员工ID"]; const fieldIdList = []; fieldDefinitionNodes.forEach(fieldNode => { const fieldId = fieldNode.getAttribute("id").getValue(); fieldIdList.push(fieldId); tableHeaders.push(fieldNode.getText()); }); // 提取所有员工数据 const employeeNodes = rootElement.getChild("employees").getChildren("employee"); const sheetData = [tableHeaders]; employeeNodes.forEach(empNode => { const currentRow = []; // 先读取员工ID(employee节点的id属性) currentRow.push(empNode.getAttribute("id").getValue()); // 构建当前员工的字段键值对 const empFieldMap = {}; empNode.getChildren("field").forEach(fieldNode => { const fieldId = fieldNode.getAttribute("id").getValue(); empFieldMap[fieldId] = fieldNode.getText() || ""; // 空字段自动赋值为空字符串 }); // 按表头顺序填充行数据 fieldIdList.forEach(fieldId => { currentRow.push(empFieldMap[fieldId] || ""); }); sheetData.push(currentRow); }); // 写入Google Sheet const spreadSheet = SpreadsheetApp.getActiveSpreadsheet(); const targetSheet = spreadSheet.getSheetByName("员工目录") || spreadSheet.insertSheet("员工目录"); targetSheet.clearContents(); // 写入前清空旧数据 targetSheet.getRange(1, 1, sheetData.length, sheetData[0].length).setValues(sheetData); }
使用说明
- 将代码中
apiKey的取值替换为你自己的BambooHR API密钥 - 绑定到目标Google Sheet后运行脚本,首次运行会弹出授权提示,同意授权即可
- 脚本会自动创建名为「员工目录」的工作表,自动匹配接口返回的所有字段,第一行写入表头,后续每行对应一位员工的完整数据
- 空值字段会自动留空,不会触发运行错误,后续接口新增字段时无需修改代码,会自动同步到表格中
内容的提问来源于stack exchange,提问作者OZIE
相关产品推荐
相关产品推荐

